0

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?

1
  • Can't you just add a row to the TableModel? Maybe you should post some code because this question isn't entirely clear. And take a look at an implementation of TableModel called DefaultTableModel. Commented Oct 25, 2011 at 6:15

2 Answers 2

4

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;
        }


    };
Sign up to request clarification or add additional context in comments.

2 Comments

@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
agreed with that confortly simplify and pretty restict this magic box :-)
2
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

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 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.