Allow Only Number Inputs in Java

0
41

This tutorial entitled “Allow Only Number Inputs in Java” will help you on how your text field accept only a number inputs. This features is very helpful to a program that received contact information from a user to avoid wrong contact information stored in database.

The functions will execute if there is a key event happening in the program. The program uses KeyListener, KeyAdapter, and KeyEvent. Also uses KeyAdapter and KeyEvent Libararies. Follow all the steps to complete this tutorial.

Allow Only Number Inputs in Java Steps

  1. Create a new JFrame Form into your source package.

2. Design your form just like the image below. In my case, I want to accept three types of contact numbers, the home, work, and mobile numbers.

3. Insert the following codes to access the required libraries.

  1. import java.awt.event.KeyAdapter;
  2. import java.awt.event.KeyEvent;

4. Insert the following codes below inside your public method.

  1. //for home number
  2. jTextField1.addKeyListener(new KeyAdapter() {
  3. @Override
  4. public void keyTyped(KeyEvent e){
  5. char c = e.getKeyChar();
  6. if (!((c >= '0') && (c <= '9') ||
  7. (c == KeyEvent.VK_BACK_SPACE) ||
  8. (c == KeyEvent.VK_DELETE))) {
  9. getToolkit().beep();
  10. e.consume();
  11. }
  12. }
  13. });
  14. //for work number
  15. jTextField2.addKeyListener(new KeyAdapter() {
  16. @Override
  17. public void keyTyped(KeyEvent e){
  18. char c = e.getKeyChar();
  19. if (!((c >= '0') && (c <= '9') ||
  20. (c == KeyEvent.VK_BACK_SPACE) ||
  21. (c == KeyEvent.VK_DELETE))) {
  22. getToolkit().beep();
  23. e.consume();
  24. }
  25. }
  26. });
  27. //for jTextField3 number
  28. jTextField1.addKeyListener(new KeyAdapter() {
  29. @Override
  30. public void keyTyped(KeyEvent e){
  31. char c = e.getKeyChar();
  32. if (!((c >= '0') && (c <= '9') ||
  33. (c == KeyEvent.VK_BACK_SPACE) ||
  34. (c == KeyEvent.VK_DELETE))) {
  35. getToolkit().beep();
  36. e.consume();
  37. }
  38. }
  39. });

5. Run your program and the output should look like the image below.

After completing this tutorial, you are now understand the importance of restricting the text field especially in when handling contact information. We can also allow text field to accept only letters. If you have comments about Allow only number inputs in Java, feel free to contact us.

Related Articles You May Like:

Create MySQL Connection in Java

 

Facebook Comments
(Visited 37 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here