Swing配置JTextField只能接受数字吗?

可能重复:
有没有办法只接受JTextField中的数值?

Swing的JTextField上有任何function只允许在一系列数字中使用正数吗?

示例:我只能输入10到30之间的数字。此范围之外的数字甚至不会出现在字段中。

使用带有SpinnerNumberModelJSpinner – 最终用户会感谢你。 好吧,不是字面意思,但至少他们不会诅咒你的名字,因为他们强迫他们输入他们想要用箭头键选择的东西。

例如

 import javax.swing.*; class NumberChooser { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { SpinnerNumberModel numberModel = new SpinnerNumberModel( new Integer(15), // value new Integer(10), // min new Integer(30), // max new Integer(1) // step ); JSpinner numberChooser = new JSpinner(numberModel); JOptionPane.showMessageDialog(null, numberChooser); System.out.println("Number: " + numberChooser.getValue()); } }); } } 

创建一个扩展PlainDocument的自定义类

 public class NumericDocument extends PlainDocument 

在此类中重写insertString。 大量在线示例使用Character.isDigit方法检查每个输入值以检查是否为数字。

你创建JTextField的时候是这样做的

 JTextField numericTextOnlyField = new JTextField(new NumericDocument()) 

在insertString方法中,您可以检查插入的值是否在您允许的范围内