It's possible in Swing configure a JTextField to only accept numbers? [duplicate]

↘锁芯ラ 提交于 2019-11-27 15:58:32

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.

E.G.

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());
            }
        });
    }
}

create a custom classes extending PlainDocument

public class NumericDocument extends PlainDocument

In this class override the insertString. Plenty of examples online which use the Character.isDigit method to check each inputted value to check if numeric or not.

The when your creating you JTextField do so using the

JTextField numericTextOnlyField = new JTextField(new NumericDocument())

inside the insertString method you can check to see of the values inserted are within the range you allow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!