Share on Google+Share on Google+

Validate textfield in Java Swing

Advertisement
In this section,you will learn how to validate the textfield by allowing only numbers to enter.

Validate Jtextfield in Java Swing

In this section,you will learn how to validate the textfield by allowing only numbers to enter. For this purpose, we have used the keyEvent class.Using the method getKeyChar() of keyEvent class, we have allowed the user to enter only numeric digits from 0 to 9.If the user enters alphabets or other characters, an error message will get displayed.

Here is the code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Validation extends JFrame {
	JTextField text;
	Container con;
	JLabel label;

	public Validation() {
		con = getContentPane();
		setBounds(0, 0, 500, 300);
		text = new JTextField(25);
		setLayout(new FlowLayout());
		con.add(new JLabel("Enter the number"));
		con.add(text);
		con.add(label = new JLabel());
		label.setForeground(Color.red);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		text.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent EVT) {
				String value = text.getText();
				int l = value.length();
				if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() <= '9') {
					text.setEditable(true);
					label.setText("");
				} else {
					text.setEditable(false);
					label.setText("* Enter only numeric digits(0-9)");
					
				}
			}
		});
		show();
	}

	public static void main(String[] args) {
		new Validation();
	}
}

Advertisements

Advertisement

Posted on: November 9, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.