- Trending Categories
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
- Related Articles
- How can we implement a rounded JTextField in Java?
- How can we add padding to a JTextField in Java?
- How can we limit the number of characters inside a JTextField in Java?
- How can we implement cut, copy and paste functionality of JTextField in Java?
- Can we save content from JTextField to a file in Java?
- JavaScript - Accept only numbers between 0 to 255 range?
- How to make Java ArrayList read only?
- How to ceate right justified JTextField in Java?
- Can we make Array volatile using volatile keyword in Java?
- How to make an ArrayList read only in Java?
- How to make a collection read only in java?
- How to create regular expression only accept special formula?
- How can we display the line numbers inside a JTextArea in Java?
- How can we extract the numbers from an input string in Java?
- Can we make static reference to non-static fields in java?

Advertisements