简体   繁体   中英

How to implement event handler for JTable Cell change

I would like to know how to implement the event handler for a jTable cell change. Where i have this jtable and i dynamically add data to this jtable

The code segment for adding data is :

JSONArray objResponseArray = (JSONArray) response.get("response");
DefaultTableModel model = (DefaultTableModel) tblAccounts.getModel();
for (int i = 0; i < objResponseArray.size(); i++) {
    JSONObject objTempAccount = (JSONObject) objResponseArray.get(i);
    Object[] row = {
         objTempAccount.get("Account ID").toString(),
         objTempAccount.get("Account Type").toString(),
         objTempAccount.get("Account Number").toString(),
         objTempAccount.get("Sort Code").toString(),
         objTempAccount.get("Balance").toString(),
         objTempAccount.get("Card").toString()
   };
   model.addRow(row);
}

In this table i have made the cells to be edited. From that being said, How can i trigger an event handler to trigger when a cell is changed. And when it is triggered i would like to get the entire row and update the database.

IMPORTANT: I am using Netbeans and the event handlers are selected from the events in the properties window in the jtable element therefor please help me to implement this.

You can add a TableModelListener to your TableModel . An event will be generated when data is changed. However it also generates an event if you start editing a cell and table to another cell without changing any data.

So instead you may want to consider the Table Cell Listener which will only generate an event when the data in the cell is actually changed.

In both cases the event will contain the row/column of the cell changed, so you can easily get the date from other columns in the row by using the getModel().getValueAt(...) method of the table.

I am using Netbeans ...

That should be irrelevant. You should learn how to use Swing, not the IDE. If you ever switch the IDE the code may not be portable, especially the code to build the frame. That is you will need to manually modify the code in another IDE anyway.

    CellEditorListener ChangeNotification = new CellEditorListener() { 
   public void editingCanceled(ChangeEvent e) {

       //Action to be performed
    }


    public void editingStopped(ChangeEvent e) {
        //Action to be performed
    }
};
use the above code inside the class before the constructor.

Inside the constructor give

tablename.getDefaultEditor(String.class).addCellEditorListener(ChangeNotification);

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