JTable中的textField可以自动添加一些文本吗?(没有 JavaScript)
就像当用户键入 2 位数字或从该字段失去焦点时为“时间”自动添加冒号(:)。
我尝试使用一些 invokeLater()、KeyListener() 和 editCellAt(),它仅在我进入该字段(双击和 F2)时才起作用,但如果我只单击并键入则不起作用。
private JTable getTblMaster() {
if (tblMasterData == null) {
tblMasterData = new JTable() {
public boolean editCellAt(int row, int column, EventObject e){
boolean result = super.editCellAt(row, column, e);
final Component editor = getEditorComponent();
if (editor == null || !(editor instanceof JTextComponent)) {
return result;
}
/* if(column == 2){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if(((JTextComponent) editor).getText().length() == 2){
((JTextComponent) editor).setText(((JTextComponent) editor).getText() + ":");
}
}
});
}
*/
return result;
}
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel()
.getColumn(column);
TableCellEditor editor = tableColumn.getCellEditor();
try {
if (editor == null) {
final JTextField text = new JTextField();
/*
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if(text.getText().length() == 2){
text.setText(text.getText() + ":");
}
}
});
text.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e){
if(text.getText().length() == 2){
text.setText(text.getText() + ":");
}
}
public void keyReleased(KeyEvent e){
if(text.getText().length() == 2){
text.setText(text.getText() + ":");
}
}
});
*/
editor = new DefaultCellEditor(text);
;
return editor;
}
} catch (Exception e) {
LogWriter.error(e);
}
return editor;
}
};
}
return tblMasterData;
}