I have a JTable
with the following columns:
rowNumber | Element | Quantity
And a JButton
that adds rows every time it's clicked. The column Element has a custom JComboBox
cell editor that gets filled with elements from a database. However i need to do the following:
Suppose i have these elements in the JComboBox
of the first row in my table: Element1 Element2 Element3
I select Element2 from the JComboBox
in the first row and then I proceed to add another row. This new row must not show Element2 any more in its JComboBox
. And the previous (first) row must not show the Element selected in the second row and so on.
Create a custom CustomCellEditor like this.
final JComboBox<String> comboBox = new JComboBox<String>();
table.getColumnModel().getColumn(1).setCellEditor(new CustomCellEditor(comboBox){
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel();
model.removeAllElements();
{//Add what you need according the row.
model.addElement("X");
model.addElement("Y");
model.addElement("Z");
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
});
I think it may help to know the expected cardinality of the Set<Element>
. Accordingly, @mKorbel raises the important question of scalability, citing this related discussion . In that case, the question proposes a List<DefaultCellEditor>
, when a much simpler renderer will do.
Here, a CellEditor
can manage a List<DefaultComboBoxModel<Element>>
, selecting the correct combo model for the row currently being edited and invoking setModel()
on the editor component. As each new table row is added, the editor would add a new element to the List
and adjust existing elements as required. I would expect the complexity to grow as O(n 2 ) , where n is the cardinality of the Set
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.