PDA

View Full Version : Restricting user input in a JTextField



SKYDev
August 4, 2008, 06:39 PM
Im really new to java, so i neeed a little help. I know that you can restrict a users input to Integers by throwing a exception if anything other than a Integer is input. But how would you restrict a users input to a string with aplphabetical characters only. Heres my code

String user = textArea.getText();

if (e.getSource() == button2) {
System.exit(0);
}
if (e.getSource() == button1) {
if (user.length() == 0 ) {
label2.setForeground(Color.BLUE);
JOptionPane.showMessageDialog(null, "Please enter a name", "Alert", JOptionPane.ERROR_MESSAGE);
}else {
this.remove(panel1);
label4.setText("Welcome " + user);
this.add(panel2);
this.pack();
}
}

GeorgePong
August 4, 2008, 06:47 PM
Try using a listener... by checkin one character at a time... heres a sample code:

keyText.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE)))) {
getToolkit().beep();
e.consume();
}
}
});


yes ur amazed at the speed of my response and the accuracy... but im not a java guru...

im a google guru

http://www.google.com.jm/search?q=java+code+jtextfield+accept+integer+throw +exception&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

site reference:

http://java.sun.com/developer/JDCTechTips/2001/tt1120.html

hope that helps

SKYDev
August 4, 2008, 06:48 PM
thanks alot for your fast response I'll take a look at it when I get home