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


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01