Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a type of listener to a JTable (Java)?

I have a column with plain text in it.

If the user double-clicks a row in that column, the column allows itself to be edited for that row (as it should).

I need something to detect when that text is done with being edited (when the user hits the enter key, for example). When that happens, I need something to get the row ID of that change (0-based of course).

Any ideas?

Thanks!

like image 686
Dylan Wheeler Avatar asked Jan 18 '23 17:01

Dylan Wheeler


2 Answers

You should add a listener to the TableModel:

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

      public void tableChanged(TableModelEvent e) {
         // your code goes here;
      }
    });

TableModelEvent contains row and column number and type of modification.

like image 102
Oleg Pavliv Avatar answered Jan 30 '23 08:01

Oleg Pavliv


I think the easiest way to get the location of the click in terms of row and column would be this:

table.addMouseListener(new java.awt.event.MouseAdapter() {
    @Override
    public void mouseClicked(java.awt.event.MouseEvent e) {
        int row = table.rowAtPoint(e.getPoint());
        int column = table.columnAtPoint(e.getPoint());
        if (row >= 0 && column >= 0) {
            ......

        }
    }
});
like image 25
Costis Aivalis Avatar answered Jan 30 '23 09:01

Costis Aivalis