Ich habe diesen Teil des Codes versucht, Werte von einem JComboBox
zu bekommen, das innerhalb eines JTable
ist, aber es funktioniert nicht!Wie nehme ich den Wert von JComboBox, der in JTable ist?
Ich möchte den Wert der ausgewählten Zelle abrufen, um in DB einzufügen.
package fx;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class ComboInTable extends JFrame {
private static JFrame jFrame;
public ComboInTable() throws HeadlessException {
jFrame=this;
JTable table=new JTable();
DefaultTableModel model= (DefaultTableModel) table.getModel();
model.addColumn("A",new Object[]{"item1"});
model.addColumn("B",new Object[]{"item2"});
JScrollPane scrollPane=new JScrollPane(table);
String[] value1=new String[]{"1","2","3"};
String[] value2=new String[]{"a","b","c"};
TableColumn col0=table.getColumnModel().getColumn(0);
TableColumn col1=table.getColumnModel().getColumn(1);
col0.setCellEditor(new MyComboBoxEditor(value1));
col0.setCellRenderer(new MyComboBoxRenderer(value1));
col1.setCellEditor(new MyComboBoxEditor(value2));
col1.setCellRenderer(new MyComboBoxRenderer(value2));
JComboBox comboBox=new JComboBox(value1);
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{
System.out.println(e.getItem());
}
}
});
jFrame.setLayout(new FlowLayout());
jFrame.add(scrollPane);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setSize(400, 400);
jFrame.setVisible(true);
}
public static void main(String[] args) {
ComboInTable comboInTable=new ComboInTable();
}
}
Ich habe MyComboBoxEditor
und MyComboBoxRenderer
Klassen.
package fx;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
public MyComboBoxRenderer(String[] items) {
super(items);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(isSelected){
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
package fx;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
public class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}