Swing配置JTextField只能接受数字吗? [英] It's possible in Swing configure a JTextField to only accept numbers?

查看:110
本文介绍了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.

推荐答案

使用带有 SpinnerNumberModel JSpinner - 最终用户会感谢您。好吧,不是字面意思,但至少他们不会诅咒你的名字,因为他们强迫他们输入他们想要用箭头键选择的东西。

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只能接受数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆