我正在尝试制作一个 JTextField,它只允许数字输入并且只允许两个字符(换句话说,只允许数字 0-99)。到目前为止,我看过一些教程并试图将输入限制为仅数字。 到目前为止,我的代码存在的问题是接受所有关键输入。我尝试反转大于和小于符号,它根本停止接受任何输入。我相信问题出在关键字符代码上,但一些帮助会很好,因为我找不到任何有用的东西(我看到的每个地方都有不同的 Java 键盘映射)。
if(event.getSource() == txtMasterSound)
{
if(event.getKeyCode() < 0 || event.getKeyCode() > 9)
{
System.out.println("Your input was invalid");
event.consume();
}
else
{
System.out.println("Your input was valid");
return;
}
}
至于限制字符,我真的不知道从哪里开始,所以一些指向正确的方向也很好。
最佳答案
- 使用 JFormattedTextField相反
- 或者使用 DocumentFilter在过滤无效输入的字段文档上。
- 或者使用InputVerifier .
例如,一个 DoumentFilter
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class MyDocFilter {
private static void createAndShowGUI() {
JTextField field1 = new JTextField(10);
PlainDocument doc = (PlainDocument) field1.getDocument();
doc.setDocumentFilter(new DocumentFilter() {
private boolean isValid(String testText) {
if (testText.length() > 2) {
return false;
}
if (testText.isEmpty()) {
return true;
}
int intValue = 0;
try {
intValue = Integer.parseInt(testText.trim());
} catch (NumberFormatException e) {
return false;
}
if (intValue < 0 || intValue > 99) {
return false;
}
return true;
}
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if (isValid(sb.toString())) {
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
int end = offset + length;
sb.replace(offset, end, text);
if (isValid(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
int end = offset + length;
sb.delete(offset, end);
if (isValid(sb.toString())) {
super.remove(fb, offset, length);
}
}
});
JPanel panel = new JPanel();
panel.add(field1);
JFrame frame = new JFrame("MyDocFilter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
关于java - 如何将 JTextField 输入限制为仅数字和 2 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979270/