Can't seem to get TableModelListener to work

I am creating a UI class in which everything will work (another class will work as a runner). In this class, I have a table, and the table should create TableModeEvents when it changes, but it doesn't seem to be that way.

The console should print a β€œtest” whenever I do something with a table, but it’s not. I made another SSCCE, and they work fine as long as I keep everything in one program (in the main method and only with subclasses and anonymous classes), but I cannot get it to work through the classes.

Any idea what I'm doing wrong?

package SSCCE; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; public class SSCCE { static Object[][] data = { {"Abyss", Boolean.FALSE},{"Scepter", Boolean.FALSE},{"FoN", Boolean.FALSE} }; public static void main(String[] args){ //table model------------------------------------------ TableModel model = new AbstractTableModel(){ Object[][] rowData = { {"Abyss", Boolean.FALSE},{"Scepter", Boolean.FALSE},{"FoN", Boolean.FALSE} }; String[] columnNames = {"Name","Boolean"}; public int getColumnCount() {return columnNames.length;} public String getColumnName(int column) {return columnNames[column];} public int getRowCount() {return rowData.length;} public Object getValueAt(int row, int column) {return rowData[row][column];} public Class getColumnClass(int column) {return (getValueAt(0, column).getClass());} public void setValueAt(Object value, int row, int column) {rowData[row][column] = value;} public boolean isCellEditable(int row, int column) {return (true);} }; JTable table = new JTable(model); //tableChanged------------------------------------------ model.addTableModelListener(new TableModelListener(){ public void tableChanged(TableModelEvent e) { System.out.println("test"); } }); //frame stuff, ignore----------------------------------- JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.add(table,BorderLayout.CENTER); frame.setSize(500,400); frame.setLocation(400,200); frame.setDefaultCloseOperation(3); frame.setVisible(true); } } 
+4
source share
1 answer

When you change the value of any of the table cells, the setValueAt method is setValueAt , but no event occurs there.

Try adding the method of the fireTableCellUpdated(row, column) method to your setValueAt method, for example:

 public void setValueAt(Object value, int row, int column) { rowData[row][column] = value; fireTableCellUpdated(row, column); } 

Please note that you can also fireTableDataChanged() , but this will lead to the majority of events, and it said that you are launching the most specific one, as it avoids unnecessary work and is able to maintain the state of choice.

+12
source

All Articles