简体   繁体   中英

How do you validate a text field in Netbeans so that it can only accept number between 1 and 100?

How do you validate a text field so that it can only accept number between 1 and 100? I want to input numbers between 1 and 100 into the text field txtSeatNo. When the button btnContinue is clicked I then want it to make sure that there is a number between 1 and 100 in the text field. I am using Netbeans and have a simple GUI.

Find a simplified example how to use a InputVerifier on a JTextFiled .

public class VerifierTest extends JFrame {

    void createAndShowGUI() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();

        JTextField tf1 = new JTextField(3);
        // you can leave the field only it the verifier retruns true
        tf1.setInputVerifier(new RangeVerifier());

        JTextField tf2 = new JTextField(3);

        panel.add(new JLabel("input [1..100]: "));
        panel.add(tf1, BorderLayout.NORTH);
        panel.add(new JLabel("some other input"));
        panel.add(tf2, BorderLayout.SOUTH);

        this.add(panel);
        this.setSize(300, 60);
        this.setVisible(true);
    }

    class RangeVerifier extends InputVerifier {
        @Override
        public boolean verify(JComponent input) {
            JTextField tf = (JTextField) input;
            boolean check = false;
            // check if the input contains only one till three digits
            // alternatively you could use a JFormattedTextField instead
            // of a plain JTextField, then you could define an input mask
            if (tf.getText().matches("^[0-9]{1,3}$")) {
                int parseInt = Integer.parseInt(tf.getText());
                // check if the number is in the range
                check = parseInt >= 1 && parseInt <= 100;
            };
            if (check) {
                tf.setBackground(Color.GREEN);
            } else {
                tf.setBackground(new Color(0xff8080));
            }
            return check;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new VerifierTest().createAndShowGUI();
            }
        });
    }
}

Assuming that you are using swing on netbeans and not matice, what you are lokking for is a JSpinner and not a JTextField. Here's a link where you can find an answer to your question : Click on me !

But if for ax/y raison you really want to use a JTextField you could use Integer 's method to obtain the numeric value and then check (value > 0 && value <= 100) this value. (all that maybe in an event listener ?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM