KeyListener
s 在这种情况下是不可靠的,因为您无法保证侦听器的处理顺序。该字段可能在您之前已经处理了关键事件...
相反,您应该使用DocumentFilter
在这里查看示例
一个更简单的解决方案就是使用JSpinner
文档过滤器示例
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestNumericFilter {
public static void main(String[] args) {
new TestNumericFilter();
}
public TestNumericFilter() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(3);
((AbstractDocument) field.getDocument()).setDocumentFilter(new IntFilter());
setLayout(new GridBagLayout());
add(field);
}
}
public class IntFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
boolean valid = true;
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
valid = false;
break;
}
}
if (valid) {
int incoming = Integer.parseInt(text);
int length = fb.getDocument().getLength();
if (length == 0 && text.length() == 1) {
if (incoming >= 2 && incoming <= 3) {
super.insertString(fb, offset, text, attr);
} else {
Toolkit.getDefaultToolkit().beep();
}
} else {
String value = fb.getDocument().getText(0, length) + text;
incoming = Integer.parseInt(value);
if (incoming >= 20 && incoming <= 30) {
super.insertString(fb, offset, text, attr);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}