问题
I've a JComboBox in 3rd and 4th column of a JTable but I don't know how to get its items...the problem isn't the method to get items but the cast
JComboBox combo=(JComboBox) jTable1.getColumnModel().getColumn(3).getCellEditor();
Can you help me please?
回答1:
The JComboBox
is wrapped in a CellEditor
. You must retrieve the wrapped component, for example when using DefaultCellEditor
:
DefaultCellEditor editor = (DefaultCellEditor)table.getColumnModel().getColumn(3).getCellEditor();
JComboBox combo = (JComboBox)editor.getComponent();
回答2:
Read this tutorial on how to use JCombobox as editor in JTable.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox
回答3:
Try something like this:
public void example(){
TableColumn tmpColum =table.getColumnModel().getColumn(1);
String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
JComboBox comboBox = new JComboBox(DATA);
DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
tmpColum.setCellEditor(defaultCellEditor);
tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
table.repaint();
}
/**
Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
JComboBox combo;
public CheckBoxCellRenderer(JComboBox comboBox) {
this.combo = new JComboBox();
for (int i=0; i<comboBox.getItemCount(); i++){
combo.addItem(comboBox.getItemAt(i));
}
}
public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
combo.setSelectedItem(value);
return combo;
}
}
来源:https://stackoverflow.com/questions/15717769/jcombobox-in-jtable