在 Netbeans 中,我使用 GUI Builder 将 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);
到目前为止有效。但它还不能让我检测到这个单元格的旧值和新值。我还需要做什么?
非常感谢您!
最佳答案
But it doesn't yet enable me to detect the old and the new value of this cell. What else do I have to do?
使用 TableModelListener 来监听变化更容易,但它仍然存在无法访问旧值的问题。
查看 Table Cell Listener寻找一个让您可以访问“旧值”和“新值”的解决方案。
关于java - JTable:检测单元格数据变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889694/