如何防止在JTable单元格中键入除数字以外的字符? [英] How to prevent typing characters except numbers in JTable cells?
问题描述
我正在一个项目中,我必须使用JTable从用户那里获取输入.在这里,我创建了一个JTable,它将仅包含数值.我在keyTyped上对其进行了验证,并且可以正常工作,直到按F2或单击该单元格为止.当我这样做时,它将光标放在单元格中,并且还键入了其他字符.
I am working in a project where I have to get input from user by using a JTable. Here I had created a JTable which will have only numerical values. I validated it on keyTyped and its working fine until I press F2 or click on the cell. When I am doing so, it put a cursor in cell and other characters are also being typed.
jtblValues.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER && (jtblValues.getRowCount() == (jtblValues.getSelectedRow()+1)))
model.addRow(new Object[]{"", "", ""});
else if (e.getKeyCode()==KeyEvent.VK_TAB && (jtblValues.getRowCount() == (jtblValues.getSelectedRow()+1)) && (jtblValues.getColumnCount() == (jtblValues.getSelectedColumn()+1)))
model.addRow(new Object[]{"", "", ""});
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_ENTER) || (c == KeyEvent.VK_TAB))) {
getToolkit().beep();
e.consume();
}
}
} );
那么,如何通过键入数字以外的其他字符来阻止用户?
So, how to prevent user by typing other characters than numbers?
谢谢.
推荐答案
您可以通过提供适当的使用编辑器来验证
You can achieve this by providing an appropriate TableCellEditor as described in Using an Editor to Validate User-Entered Text section of How to Use Tables tutorial.
关键是使用 JFormattedTextfield 使用 NumberFormatter 和 NumberFormat .例如:
The key is using a JFormattedTextfield as editor with NumberFormatter and NumberFormat. For instance:
NumberFormat integerFormat = NumberFormat.getIntegerInstance();
NumberFormatter formatter = new NumberFormatter(integerFormat);
formatter.setAllowsInvalid(false);
JFormattedTextField textfield = new JFormattedTextField(formatter);
请参见如何使用带格式的文本字段教程进一步的细节.
See How to Use Formatted Text Fields tutorial for further details.
使用Swing时,最好使用Keybinding而不是KeyListener,这是出于本主题中讨论的原因:键绑定与键监听器在Java中.请参考以KeyBinding开始的教程:如何使用键绑定
It's preferable use Keybinding over KeyListeners when you're working with Swing for the reasons discussed in this topic: Key bindings vs. key listeners in Java. Refer to the tutorial to start with KeyBinding: How to Use Key Bindings
这篇关于如何防止在JTable单元格中键入除数字以外的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!