java 在 Swing 中可以将 JTextField 配置为仅接受数字吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6111003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
It's possible in Swing configure a JTextField to only accept numbers?
提问by Renato Dinhani
Possible Duplicate:
Is there any way to accept only numeric values in a JTextField?
There any functionality on the JTextField of Swing that allow only positive numbers inside a range of numbers?
Swing 的 JTextField 上是否有任何功能只允许在一定范围内的正数?
Example: I can only enter numbers between 10 and 30. Numbers out of this range will not even appear in the field.
示例:我只能输入 10 到 30 之间的数字。超出此范围的数字甚至不会出现在字段中。
回答by Andrew Thompson
Use a JSpinner
with a SpinnerNumberModel
- the end user will thank you. OK not literally, but at least they will not curse your name for forcing them to type in something they'd like to choose using the arrow keys.
使用 aJSpinner
和 a SpinnerNumberModel
- 最终用户会感谢您。好吧,不是字面意思,但至少他们不会因为强迫他们使用箭头键输入他们想要选择的内容而诅咒您的名字。
E.G.
例如
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());
}
});
}
}
回答by cduggan
create a custom classes extending PlainDocument
创建一个自定义类扩展 PlainDocument
public class NumericDocument extends PlainDocument
In this class override the insertString. Plenty of examples online which use the Character.isDigit method to check each inputted value to check if numeric or not.
在这个类中覆盖了 insertString。很多在线示例使用 Character.isDigit 方法检查每个输入的值以检查是否为数字。
The when your creating you JTextField do so using the
当您创建 JTextField 时,请使用
JTextField numericTextOnlyField = new JTextField(new NumericDocument())
inside the insertString method you can check to see of the values inserted are within the range you allow
在 insertString 方法中,您可以检查插入的值是否在您允许的范围内