It#39;s possible in Swing configure a JTextField to only accept numbers?(在 Swing 中可以将 JTextField 配置为只接受数字吗?)
问题描述
可能重复:
有没有办法只接受数字JTextField 中的值?
Swing 的 JTextField 上是否有任何功能只允许数字范围内的正数?
There any functionality on the JTextField of Swing that allow only positive numbers inside a range of numbers?
示例:我只能输入 10 到 30 之间的数字.超出此范围的数字甚至不会出现在字段中.
Example: I can only enter numbers between 10 and 30. Numbers out of this range will not even appear in the field.
推荐答案
使用 JSpinner
和 SpinnerNumberModel
- 最终用户会感谢你的.好吧,不是字面意思,但至少他们不会因为强迫他们使用箭头键输入他们想要选择的内容而诅咒你的名字.
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.
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());
}
});
}
}
这篇关于在 Swing 中可以将 JTextField 配置为只接受数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swing 中可以将 JTextField 配置为只接受数字吗?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01