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 配置为只接受数字吗?


基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01