![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we make JTextField accept only numbers in Java?
By default, a JTextField can allow numbers, characters, and special characters. Validating user input that is typed into a JTextField can be difficult, especially if the input string must be converted to a numeric value such as an int.
In the below example, JTextField only allows entering numeric values.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextFieldValidation extends JFrame { JTextField tf; Container container; JLabel label; public JTextFieldValidation() { container = getContentPane(); setBounds(0, 0, 500, 300); tf = new JTextField(25); setLayout(new FlowLayout()); container.add(new JLabel("Enter the number")); container.add(tf); container.add(label = new JLabel()); label.setForeground(Color.red); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); tf.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { String value = tf.getText(); int l = value.length(); if (ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9') { tf.setEditable(true); label.setText(""); } else { tf.setEditable(false); label.setText("* Enter only numeric digits(0-9)"); } } }); setVisible(true); } public static void main(String[] args) { new JTextFieldValidation(); } }
Output
Advertisements