I have empty TableModel. When I set this model to JTable it hasn't rows. I want to create one empty row, where user can select value in combo box editor. If user selects not-null value, then second row added and I have one object in model. How can I add empty row, when there is not object for this row in model?
2 Answers
The TableModel is your friend: implement it's setValueAt method to add a row after setting the value. Here's an example for doing so by subclassing DefaultTableModel:
DefaultTableModel model = new DefaultTableModel(1, 3) {
/**
* @inherited <p>
*/
@Override
public void setValueAt(Object aValue, int row, int column) {
super.setValueAt(aValue, row, column);
if (shouldAddRow(row, column)) {
addRow(new Object[] {});
}
}
private boolean shouldAddRow(int lastEditedRow, int lastEditedColumn) {
// implement your logic here
return lastEditedRow == getRowCount() -1;
}
};
2 Comments
kleopatra
@mKorbel that was pure lazyness (as you know, I'm not a big fan of subclassing :-) - doing the same in a TableModelListener would have implied to correctly detangle the "update" from the given TableModelEvent, which I hate to do without SwingX TableUtils at hand
mKorbel
agreed with that confortly simplify and pretty restict this magic box :-)
I want to create one empty row, where user can select value in combo box editor.
that isn't empty row,
you can add null value to the JTable Cell, more in the tutorial about JTable and JComboBox as an Editor, and examples here
1 Comment
kleopatra
the values of the TableModel might well be empty (aka: return null values) - at that moment only the combo's popup has values != null (if I understand the OP correctly, not much to go on :-)