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?
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.
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",
Hey, so I wanna ask how I need to create a method who will remove word if in that word is 2 same chars. Example: "Potato" in this word there is a 2 "o" chars so this word will need to be removed. "Forum" in this word there is no ...
Help! I want to create a java program that finds the highest even integer among the values entered by the user. Stop asking values when a value less than 1 have been entered. If no even integer is entered, display "No Even Integer"
I am writing a java program that needs to execute shell commands, so I wrote a function that would take the command to execute as a string (ie: "mkdir ~/Folder1") and execute that command with the shell. Here is the function:
Runtime run = Runtime.getRuntime();
Process pr = ...