How to Create JTextField Validation in java swing.
How to Create JTextField Validation in java swing
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.
package javaGuiProject;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public 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();
}
}
Comments
Post a Comment