JTable:检测单元格数据更改
2022-09-01 23:02:38
在 Netbeans 中,我使用 GUI 生成器将 JTable 插入到我的应用程序中。
到目前为止,我只有一个类(CustomerDB),它是:
package CustomerDB;
import [...];
public class CustomerDB extends javax.swing.JFrame {
CellEditorListener ChangeNotification = new CellEditorListener() {
public void editingCanceled(ChangeEvent e) {
System.out.println("The user canceled editing.");
}
public void editingStopped(ChangeEvent e) {
System.out.println("The user stopped editing successfully.");
}
};
public CustomerDB() {
customerTable = new javax.swing.JTable();
customerTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"ID", "Name", "Address", "Phone"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
customerTable.getDefaultEditor(String.class).addCellEditorListener(ChangeNotification);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CustomerDB().setVisible(true);
}
});
}
// Variables declaration - do not modify
[...]
private javax.swing.JTable customerTable;
[...]
// End of variables declaration
}
每当用户更改表中的数据时,我都希望获取该单元格的旧值(可选)和新值。
为了获取此数据,我尝试实现一个事件侦听器:
CellEditorListener ChangeNotification = new CellEditorListener() {
public void editingCanceled(ChangeEvent e) {
System.out.println("The user canceled editing.");
}
public void editingStopped(ChangeEvent e) {
System.out.println("The user stopped editing successfully.");
}
};
然后,我将此 CellEditorListener 分配给表(其单元格编辑器):
customerTable.getDefaultEditor(String.class).addCellEditorListener(ChangeNotification);
到目前为止,这仍然有效。但是它还不能使我检测此单元格的旧值和新值。我还需要做什么?
非常感谢你提前!