我正在嘗試爲JTable創建一個簡單的輸入驗證程序。 我最終重寫了方法:editingStopped()。 問題是該事件不包括有關已更新單元的信息。JTable輸入驗證程序
這是我的 「僞代碼」:
If (user finished editing a cell) {
Check if cell`s value is "1" or "0" or "-" (Karnaugh-Veitch)
If (check = false)
setValue (cell, "");
}
我嘗試的第一個是這樣的位置:
table.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
inputVerify (e.getColumn(), e.getFirstRow());
}
});
public void inputVerify (int column, int row) {
boolean verified = true;
String field = table.getValueAt(row, column).toString();
if (field != null && field.length() == 1) {
if (!(field.charAt(0) == '0' || field.charAt(0) == '1' || field.charAt(0) == '-'))
verified = false;
}
else {
verified = false;
}
if (!verified) {
table.getModel().setValueAt("", row, column);
java.awt.Toolkit.getDefaultToolkit().beep();
}
System.out.println ("Column = " + column + " Row = " + row + " Value = " + table.getValueAt(row, column) +" Verified = "+verified);
}
但這最終有:StackOverflow的異常。我猜問題是:setValueAt(..)觸發另一個tableChanged()事件,並且正在生成一個無限循環。現在
,我想這在這裏:
table.getDefaultEditor(Object.class).addCellEditorListener(new CellEditorListener() {
// called when editing stops
public void editingStopped(ChangeEvent e) {
// print out the value in the TableCellEditor
System.out.println(((CellEditor) e.getSource()).getCellEditorValue().toString());
}
public void editingCanceled(ChangeEvent e) {
// whatever
}
});
但你可以看到我可以檢索電池的新的價值,而不是「座標」。 我需要調用:setValueAt(..)方法,但我不知道如何獲取單元格的座標。
或者是否有更簡單的方法來創建輸入驗證?
問候 揚K.
沒有,你不想調用setValueAt,所以你不需要座標:-) – kleopatra 2011-05-03 21:53:46