限制Java中的文本字段

有没有办法将文本字段限制为只允许数字0-100,从而排除字母,符号等? 我找到了一种方法,但它似乎比看起来更复杂。

如果必须使用文本字段,则应使用带有NumberFormatter的JFormattedTextField 。 您可以设置NumberFormatter上允许的最小值和最大值。

NumberFormatter nf = new NumberFormatter(); nf.setValueClass(Integer.class); nf.setMinimum(new Integer(0)); nf.setMaximum(new Integer(100)); JFormattedTextField field = new JFormattedTextField(nf); 

但是,如果适合您的使用案例,Johannes建议使用JSpinner也是合适的。

我建议你应该在这种情况下使用JSpinner 。 在Swing中使用文本字段非常复杂,因为即使是最基本的单行文档也有一个完整的Document类。

您可以设置JTextField使用的PlainDocument的DocumentFilter 。 DocumentFilter的方法将在DocumentFilter的内容更改之前调用,并且可以补充或忽略此更改:

  PlainDocument doc = new PlainDocument(); doc.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { if (check(fb, offset, 0, text)) { fb.insertString(offset, text, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (check(fb, offset, length, text)) { fb.replace(offset, length, text, attrs); } } // returns true for valid update private boolean check(FilterBypass fb, int offset, int i, String text) { // TODO this is just an example, should test if resulting string is valid return text.matches("[0-9]*"); } }); JTextField field = new JTextField(); field.setDocument(doc); 

在上面的代码中,您必须完成check方法以符合您的要求,最终获取字段的文本并替换/插入文本以检查结果。

您必须实现并向textField.getDocument()添加一个新的DocumentListener 。 我在这里找到了一个实现。