Is there any way to accept only numeric values in a JTextField?

Viewed 100775

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

20 Answers
DataTF.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent eve) {
                String AllowedData="0123456789.";
                char enter = eve.getKeyChar();
                if (!AllowedData.contains(String.valueOf(enter))) {
                    eve.consume();
                }
            }       
        });  

I see many Java programmers are taking Object Oriented Programming too seriously in their code instead of just simplifying things as much. What you can simply do is read the text of JTextField object and check its content with this regular expression using String.match() method at the form submission time. This way it will run or call the events system only once per each form submission:

String regex="^[0-9]+(\.?)[0-9]*$";

This regex will match any decimal number . If the JTextField content is not in the decimal number format, then just write a function return or any logic of exiting or stopping the current context. And if you want it strictly integer then fix the regex as such:

String regex = "^[0-9]+$";

This is a sample code :

class  MyWindow extends JFrame {
 //put this (JTextField input) and the (JButton button) as member variable of 
 //the current class to access it globally easily
 JTextField input=new JTextField(); 
 JButton button =new JButton("Click me");

public MyWindow() {
 button.addActionListener(new ActionListener() {
             @Override
            public void actionPerformed(ActionEvent e) {
               String jtextfield_contents=input.getText().trim();
               String regex="^[0-9]+(\.?)[0-9]*$";
               if (!jtextfield_contents.match(regex) || jtextfield_contents.isBlank()){
                  return; //here is your exit or escape from exceptions point. 
            }
            // below this line and inside actionPerformed
           // write the logic where the input number is considered OK and acceptable to you. 
               }
       );    
 JPanel jp =new JPanel();
 jp.add(button);
 this.add(jp);
 this.setVisible(true);
}
}
Related