Search code examples
javaswingjtableactionlistener

Get selected row and column AFTER editing JTable


I would like to perform an action after a table cell has been edited. However, after I used tablechanged and print the source cell, there was an error. Then I managed to find that the error was due to e.source not being an instance of a tablebut instead a DefaultTableModel.How do you get the selected row and column AFTER editing?

Here's a sample code:

public static void main(String[] args) {
    JFrame main = new JFrame();

    JTable table = new JTable(6, 4);
    table.setSize(300, 300);

    table.getModel().addTableModelListener(new TableModelListener() {

        public void tableChanged(TableModelEvent e) {
            Object s = e.getSource();
            //JTable t = (JTable) s;
            //int x = t.getSelectedRow();
            //int y = t.getSelectedColumn();
            //System.out.println("Cell at " + x + "," + y);

            if (s instanceof JTable)
                System.out.println("TABLE");
            else
                System.out.println("Not a table");
        }
    });
    main.add(table);
    main.setSize(300,300);
    main.setLocationRelativeTo(null);
    main.setVisible(true);
    main.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

Solution

  • ((TableModel)e.getSource()).getValueAt and rows between e.getFirstRow/LastRow.