在 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());
}
});
}
}
相关文章