Results 1 to 3 of 3

Thread: Restricting user input in a JTextField

  1. #1
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default Restricting user input in a JTextField

    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
    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();
                    }
            }

  2. #2
    Join Date
    Nov 2004
    Posts
    143
    Rep Power
    0

    Default

    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=ja...ient=firefox-a

    site reference:

    http://java.sun.com/developer/JDCTec...01/tt1120.html

    hope that helps

  3. #3
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default

    thanks alot for your fast response I'll take a look at it when I get home

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •