Search code examples
javaswingjtablejcomboboxtablemodel

Java Swing - inform GUI about changes to the model


I have a column in JTable that binds to the underlying boolean property on a list of business objects. I also have a combobox, which should select which items should be selected. I basically added the following code as a handler to the combobox:

            macroCombo.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JComboBox comboBox = (JComboBox) e.getSource();
                    Predicate filter = (Predicate) comboBox.getSelectedItem();
                    for(SelectableKey key : tableEntries){
                        key.setSelected(filter.evaluate(key));
                    }
                }
            });

I also have a few other controls I want to change based on the value. At the moment, only a few cells in the table change their state to be selected/deselected. Only when I click on the row, or select multiple rows, the UI updates itself. Is there a call from the handler I need to make to tell GUI to redraw itself? ALos, if I modify other controls than JTable, how would I tell them to change their state?

Thanks


Solution

  • When you update a value in your TableModel, the model should fire a corresponding TableModelEvent (type: UPDATE).

    If your TableModel for example extends from AbstractTableModel, you can call the fireTableRowsUpdated method after you have made the changes.

    Another approach is a TableModel which knows when it gets updated (for example by adding listeners to the objects it contains). This allows other code to simply update the objects contained in the TableModel, without having knowledge of the TableModel. The TableModel itself will then fire the event when it detects changes made to the objects it contains.

    I prefer the second approach, as this avoids that I have to pass that TableModel around to all my other classes.

    Consult the table tutorial for more information.