简体   繁体   中英

Java Swing: JTable tableChanged does not work after model is updated

On load, my JTable has 2 columns - . So its a string in the first column and a checkbox in the second column. When I click on the checkbox tableChanged is fired and I can print the row data that was selected.

I need to change the table data when user selects a new category in the dropdown. When the table data is updated, and I click on the checkbox the tableChanged is no longer fired. This is what I have: This is how I am updating the table data:

 comboBox.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {

                    String t = (String) comboBox.getSelectedItem();
                    if (t.equals("survey2")) {
                        String[] columnNames = { "Volume Name", "Select" };
                        Object[][] data = { { "pt1", false }, { "pt2", false },
                                { "pt3", false }, { "pt4", false },

                        };

                        model = new DefaultTableModel(data, columnNames);

                        table.setModel(model);

                    }
                }
            });

This is my tableChanged:

table.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {


                if ((Boolean)table.getModel().getValueAt(table.getSelectedRow(), 1)) {


                    System.out.println(">\t"
                            + table.getValueAt(table.getSelectedRow(), 0));

                } else {

                    System.out.println(">\t"
                            + table.getValueAt(table.getSelectedRow(), 0));
                }

            }
        });

I do not understand why the event is not fired after updating the model. Am I updating the table incorrectly?

You area creating a new TableModel but you added the ChangeListener to the old TableModel .

Don't create a new TableModel!

You can clear the data by using setRowCount(0) .

The you can add the new data back to the DefaultTableModel by using:

  1. the setDataVector(...) method, or
  2. by adding data back to the model one row at a time using the addRow(...) method.

So there is no need to create a new TableModel. If you want to create a new TableModel then you also need to add your ChangeListener to this new model.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM