問題描述
在 Netbeans 中,我使用 GUI Builder 將 JTable 插入到我的應用程序中.
到目前為止,我只有一個類 (CustomerDB):
I have just one class (CustomerDB) so far which is:
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
}
每當用戶更改表格中的數據時,我都想獲取該單元格的舊值(可選)和新值.
為了獲取這些數據,我嘗試實現一個事件監聽器:
In order to get this data, I tried to implement an event listener:
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 來監聽變化更容易,但它仍然存在無法訪問舊值的問題.
It is easier to use a TableModelListener to listen for changes but it still has the problem of not being able to access the old value.
查看表格單元偵聽器,了解可讓您訪問的解決方案舊值"和新值".
Check out the Table Cell Listener for a solution that gives you access to the "old value" as well as the "new value".
這篇關于JTable:檢測單元格數據變化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!