Home Tutorial Java Swing JTextField Validation in java swing

 
 

JTextField Validation in java swing
Posted on: December 4, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to validate jtextfield in java swing.

JTextField Validation in java swing

In this tutorial, you will learn how to validate jtextfield in java swing. Here we have created a textfield on frame and allowed the user to enter. If the user enter characters or symbols or special character, it cannot be inserted in the textfield, the textfield will not respond to any character, it only accepts numbers.

Example:

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

class TextValidation extends JFrame{
JTextField text;
JLabel label;
JPanel p;
TextValidation(){
text=new JTextField(15);
label=new JLabel("Enter number:");
p=new JPanel();
p.add(label);
p.add(text);
text.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){

                char ch = e.getKeyChar();
                if(Character.isDigit(ch)){
                }
                else{
                    JOptionPane.showMessageDialog(null, "Only numbers are allowed!");
                    text.setText(" ");
                }
            }
});
add(p);
setVisible(true);
setSize(300,100);
}
public static void main(String[]args){
TextValidation v=new TextValidation();
}
}
Advertisement

Related Tags for JTextField Validation in java swing:


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.

Posted on: December 4, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com