Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a table listener to a JTable?

I am having problems with fixing something in my program. Basically I know how to use action Listeners but there is no option to add one to a JTable. How is this done?

Basically I want to add an action Listener to my table so that every time a value is changed it will update that field in my data base.

I.E.

JTable.addActionListener (new ActionListener) {
    // text is changed
    updateDataBase();
};
like image 272
Seamus O Connor Avatar asked Feb 06 '15 05:02

Seamus O Connor


2 Answers

You should add a listener to the TableModel:

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

  public void tableChanged(TableModelEvent e) {
     // your code goes here, whatever you want to do when something changes in the table
  }
});

TableModelEvent contains row and column number and type of modification.

TableModelEvent is used to notify listeners that a table model has changed.

like image 181
Sharp Edge Avatar answered Oct 03 '22 06:10

Sharp Edge


Start by taking a look at How to Use Tables

What you will want to do is register a TableModelListener with the JTable's model and monitor for changes there

You may also find How to Write a Table Model Listener of some use

The kind of thing you are look for is

  • TableModel#getType equals TableModelEvent.UPDATE
  • TableModel#getFirstRow and TableModel#getLastRow are typically equals (singularly that a single row was update), this may or may not be relevant, that's up to you to decide
  • TableModel#getColumn is not equal to TableModelEvent.ALL_COLUMNS, this signifies that a single cell was updated. Again, this may or may not be important, but if the cell was edited by the user, this will be set

Take a look at javax.swing.event.TableModelEvent for more details

like image 41
MadProgrammer Avatar answered Oct 03 '22 04:10

MadProgrammer