Zhao Yi
Zhao Yi

Reputation: 2475

Changing row height with JTable.setRowHeight not working

I'm working on a table that have rows suiting the contents. I install a TableModelListener to the table model so that whenever a new row is added, the height of the new added row is automatically changed. Here's my testing code:

final DefaultTableModel model = new DefaultTableModel(0, 1);
final JTable table = new JTable(model);
model.addTableModelListener(new TableModelListener() {
    @Override
    public void tableChanged(TableModelEvent e) {
        // TO DO: replace 100 with the actual preferred height.
        table.setRowHeight(e.getFirstRow(), 100);
    }
});

JButton button = new JButton("Add Row");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        model.addRow(new String[] {"abc"});
    }
});

I expect that when "Add Row" button is clicked, a new row is added to the table and has a height of 100 pixels, but it doesn't work - the row height never changes. A weirder thing is that the JTable.setRowHeight method can work correctly if I move the call to the button's action listener like this:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        model.addRow(new String[] {"abc"});
        talbe.setRowHeight(table.getRowCount() - 1, 100);
    }
});

Definitely I can't rely on this "solution" because the table model can be changed from other places. Do I correctly use TableModelListener or is this a bug?

Upvotes: 3

Views: 6005

Answers (2)

aterai
aterai

Reputation: 9808

How about to use EventQueue.invokeLater(...)

model.addTableModelListener(new TableModelListener() {
  @Override public void tableChanged(final TableModelEvent e) {
    // TO DO: replace 100 with the actual preferred height.
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        table.setRowHeight(e.getFirstRow(), 100);
      }
    });
  }
});

Upvotes: 4

MadProgrammer
MadProgrammer

Reputation: 347244

Have you tried to invalidate/repaint the table after setting the row height value?

Upvotes: 1

Related Questions