Number Validation: Only numbers in TextField using Java GUI

Some of my students before always asked how to filter a textbox with only numbers that can be inputted. Right away, they always made a mistake on writing the code because they are just using the NumberFormatException code. But actually it isn't wrong, it is just sometimes not applicable and not functioning at times when I can still remember my college days. But now, I wrote this code to filter numbers on textbox or any controls in Java. I want to share and teach about this code. Now let's begin this tutorial! 1. Create a program with a file name of numberValidation.java. 2. Import the following libraries.
  1. import java.awt.*;
  2. import java.io.*;
  3. import javax.swing.*;
  4. import java.util.*;
  5. import java.awt.event.*;
You seemed to figure out that we always used asterisk (*). This asterisk means getting all the classes inside the libraries of awt, io, swing, and util. awt means Abstract Windowing Toolkit. This is a set of application program interfaces ( API) to create graphical user interface (GUI) objects, such as buttons, textfields, or any controls. awt.event gets the action performed or when clicking a button or any events of the controls. 3. Create a numberValidation that will extend JFrame because we will put a frame here.
  1. public class numberValidation extends JFrame{
  2.        
  3.         JPanel panel1 = new JPanel();
  4.  
  5.         JTextField txtNum = new JTextField(20);
  6.         String dialogmessage;
  7.     String dialogs;
  8.     int dialogtype = JOptionPane.PLAIN_MESSAGE;
  9.     public static int record;
The name txtNum is our variable in textfield with only 20 characters to be inputted. 4. Create a class named j2 that extends panel. We will make use of the Panel to put our textfield there.
  1. class j2 extends JPanel
  2.         {  
  3.                 public j2()
  4.                         {  
  5.                         setLayout(new FlowLayout(0,0,0));
  6.                       setBackground(Color.black);
  7.                          
  8.                         }
  9.                         public void paint(Graphics g)
  10.                                 {
  11.                                         super.paint(g);
  12.                                        
  13.                                   g.setFont(new Font("Cooper Black",Font.BOLD,40));
  14.                                 g.drawString("Number Validation",60,70);
  15.                                 }
  16.                 public Dimension getPreferredSize(){return new Dimension(40,50);}      
  17.                              
  18.         }
5. Create a method name Numvalidator that has the parameter of JTextField with txtField variable. This will filter all those characters that are not numbers in the textfield. And will prompt "Only numbers are allowed!".
  1. public void Numvalidator(JTextField txtField)
  2.         {
  3.                 txtField.addKeyListener(new KeyAdapter() {
  4.         public void keyTyped(KeyEvent e) {
  5.         char c = e.getKeyChar();
  6.         if (!(Character.isDigit(c) ||
  7.                 (c == KeyEvent.VK_BACK_SPACE) ||
  8.             (c == KeyEvent.VK_DELETE))) {
  9.              e.consume();
  10.               JOptionPane.showMessageDialog(null, "Only numbers are allowed!","WARNING!!",JOptionPane.WARNING_MESSAGE);
  11.            }
  12.          }
  13.        });
  14.         }
6. Create a constructor named numberValidation() that is the same with the filename.
  1. public numberValidation()
  2.     {
  3.        
  4.         super("Number Validation ");
  5.         panel1.setLayout(new GridLayout(7,7));
  6.        
  7.             panel1.add(txtNum);
  8.             panel1.setOpaque(true);
  9.                
  10.         getContentPane().setLayout(new GridLayout(3,1));
  11.         getContentPane().add(new j2(),"NORTH");
  12.         getContentPane().add(panel1,"CENTER");
  13.  
  14.         Numvalidator(txtNum);
  15.         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  16.     }
7. Lastly, create your Main form. This will the contents of your UI with the size, visibility, and location to be displayed.
  1. public static void main(String []args){
  2.                 numberValidation p1= new numberValidation();
  3.                 p1.setSize(650,630);
  4.                 p1.setLocation(300,50);
  5.                 p1.setVisible(true);
  6.         p1.setResizable(false);
  7.         }

Output:

output output Here's the full code of this tutorial..
  1. import java.awt.*;
  2. import java.io.*;
  3. import javax.swing.*;
  4. import java.util.*;
  5. import java.awt.event.*;
  6.  
  7. public class numberValidation extends JFrame{
  8.        
  9.         JPanel panel1 = new JPanel();
  10.  
  11.         JTextField txtNum = new JTextField(20);
  12.         String dialogmessage;
  13.     String dialogs;
  14.     int dialogtype = JOptionPane.PLAIN_MESSAGE;
  15.     public static int record;
  16.    
  17.  
  18.       class j2 extends JPanel
  19.         {  
  20.                 public j2()
  21.                         {  
  22.                         setLayout(new FlowLayout(0,0,0));
  23.                       setBackground(Color.black);
  24.                          
  25.                         }
  26.                         public void paint(Graphics g)
  27.                                 {
  28.                                         super.paint(g);
  29.                                        
  30.                                   g.setFont(new Font("Cooper Black",Font.BOLD,40));
  31.                                 g.drawString("Number Validation",60,70);
  32.                                 }
  33.                 public Dimension getPreferredSize(){return new Dimension(40,50);}      
  34.                              
  35.         }
  36.     public numberValidation()
  37.     {
  38.        
  39.         super("Number Validation ");
  40.         panel1.setLayout(new GridLayout(7,7));
  41.        
  42.             panel1.add(txtNum);
  43.             panel1.setOpaque(true);
  44.                
  45.         getContentPane().setLayout(new GridLayout(3,1));
  46.         getContentPane().add(new j2(),"NORTH");
  47.         getContentPane().add(panel1,"CENTER");
  48.  
  49.         Numvalidator(txtNum);
  50.         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  51.     }
  52.  
  53.     public void Numvalidator(JTextField txtField)
  54.         {
  55.                 txtField.addKeyListener(new KeyAdapter() {
  56.         public void keyTyped(KeyEvent e) {
  57.         char c = e.getKeyChar();
  58.         if (!(Character.isDigit(c) ||
  59.                 (c == KeyEvent.VK_BACK_SPACE) ||
  60.             (c == KeyEvent.VK_DELETE))) {
  61.              e.consume();
  62.               JOptionPane.showMessageDialog(null, "Only numbers are allowed!","WARNING!!",JOptionPane.WARNING_MESSAGE);
  63.            }
  64.          }
  65.        });
  66.         }
  67.        
  68.         public static void main(String []args){
  69.                 numberValidation p1= new numberValidation();
  70.                 p1.setSize(650,630);
  71.                 p1.setLocation(300,50);
  72.                 p1.setVisible(true);
  73.         p1.setResizable(false);
  74.         }
  75.  
  76. }
Best Regards, Engr. Lyndon R. Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09102918563 Landline: 826-9296 E-mail:[email protected] Visit and like my page on Facebook at: https://www.facebook.com/BermzISware For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment