In my applcation I have a JText field for entering a phone number.
Is it possible to make it only accept numerical characters? Or should i wite a method to alert the user if they enter any other characters into it?
Thanks

Have a look at the API doc for JTextField. The intro shows how to create a custom field - in that example one that takes upper-case letters only. You should be able to use that example and its accompanying explanation to create your own numeric-only field.

Alternatively, if you have a bit more time to spare, you should look at using a JFormattedTextField with an instance of a javax.swing.text.NumberFormatter as the formatter. Frankly, it's quite a lot more to understand than just the JTextField solution, but it teaches you the more general way to access all the pre-written input field formatting classes that come with Swing.

Edited 4 Years Ago by JamesCherrill

another possibility is by adding an implementation of the KeyListener interface to your textfield. there are several ways of doing what you're trying to do, just look at your application, whether you need it once, twice, a lot of times, in one java class, in several java classes, ...

I took the easy way out and wrote a method to check if the sting is all numbers and display a message if it is not. Then just called it where I need it.
Heres my method.

    public boolean phone(String string)
    {
      char[] c = string.toCharArray();
      for(int i=0; i < string.length(); i++)
      {
          if ( !Character.isDigit(c[i]))
          {
              JOptionPane.showMessageDialog(frame, "Phone numer is not valid", "Warning",
                                          JOptionPane.WARNING_MESSAGE);
             return false;
          }
     }
     return true;
   }
This question has already been answered. Start a new discussion instead.