How to know if the JTextField is empty? - java

I am building a GUI for some Java project. I need to validate what user input on JTextField. But I have a small problem.
The JTextField is for entering Integer. So, I did try and catch for NumberFormatException. The question is: if the user fires an action (press Enter) without writing anything in the JTextField even space, How could I handle this?
int id = 0;
try {
id = Integer.parseInt(tfID.getText());
} catch (NumberFormatException e1 ) {
if (tfID.getText()==null) //This does not work
idError.setText("Enter an Integer");
else
idError.setText("Intgers only accepted");
}
I want to show a message on another JTextfield (which is idError in this case) to tell the user to enter an Integer.
Thanks in advance.

Instead of using:
if (tfID.getText()==null)
use:
if( tfID.getText().equals("") )
which will return true if and only if the two strings are equal, which is here tfID.getText() and ("").
Thanks for you all.

Related

JoptionPane closing without doing anything

Am working on a project where i need to ask the user to enter a path to save the program using jOptionPane but my problem is if the user dont put anything in the text and click cancel or ok am getting an error...i tried to control it buy checking the string if is Empty() or equals to null
Try to make a function for this JOptionPane, case you need back again, and don't forget to catch the errors with methods like NullPointerException.
public void optionPane(){
String m = JOptionPane.showInputDialog("your text...");
try{
if((m == null) || (m.equals(""))){
optionPane();
}
}catch(NullPointerException e){
optionPane();
}
}

Force User to Provide One of Two Answers?

So, in Java, I want the user to provide either Y or N to my prompt. Lets say (dream sequence begins with swirly sounds) I am currently using this code:
String output = "";
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("[P]ast or [F]uture?");
String input = scan.nextLine().toLowerCase();
if (input.equals("p") || input.equals("f")){
output = input;
break;
} else {
System.out.println("Please provide a valid answer.");
}
}
There has got to be a more efficient way of doing this. Can anyone enlighten me?
There is no way you can force the user to type in something. You'll have to sanitize the data and throw an error at the user when he types in something wrong, much like your code is doing now.
Use a GUI library such as Swing or JavaFX and only allow the allowable input. For instance if this were Swing and the user were entering input into a JTextField, you could add a DocumentFilter to the JTextField's document, preventing the user from entering anything but 'y' or 'n'.
Have you tried hasNext(String pattern) to validate that the next token consists of your desired pattern?
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
http://www.tutorialspoint.com/java/util/scanner_hasnext_pattern.htm
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Error");
sc.next();
}

JTextfield Listener for Integers

I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No Strings allowed). I've tried this recommended link on Document Listener, but I don't know what method to invoke etc.
I've never used this type of Listener before, so could anyone explain how I could write a listener on a JTextField to only allow integer values that can be accepted?
Basically after I click a JButton, and before the data is extracted out onto a variable, then Listener will not allow it to be processed until an integer is inputted.
Thanks very much appreciated.
You don't want a listener, you want to get the text from the JTextField and test if it is an int.
if (!input.getText().trim().equals(""))
{
try
{
Integer.parseInt(myString);
System.out.println("An integer"):
}
catch (NumberFormatException)
{
// Not an integer, print to console:
System.out.println("This is not an integer, please only input an integer.");
// If you want a pop-up instead:
JOptionPane.showMessageDialog(frame, "Invalid input. Enter an integer.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
You could also use a regex (a little bit of overkill, but it works):
boolean isInteger = Pattern.matches("^\d*$", myString);
You don't want a document listener. You want an ActionListener on the submit/ok button.
Make sure that listener is created with a handle to the JTextField, then put this code in the actionPerformed call:
int numberInField;
try {
numberInField = Integer.parseInt(myTextField.getText());
} catch (NumberFormatException ex) {
//maybe display an error message;
JOptionPane.showMessageDialog(null, "Bad Input", "Field 'whatever' requires an integer value", JOptionPane.ERROR_MESSAGE);
return;
}
// you have a proper integer, insert code for what you want to do with it here
how I could write a listener on a JTextField to only allow integer values that can be accepted?
You should be using a JFormattedTextField or a Document Filter.
JFormattedTextField example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
}
JFormattedTextField works well for restricting input. In addition to limiting input to numbers, it is capable of more advanced use, e.g. phone number format. This provides immediate validation without having to wait for form submission or similar event.

reading user input and detecting type of entry in Java

In my program, I have a JTextField reading the user input. The user is supposed to enter a number and then click a JButton to confirm the entry, but i want to have a catch where if the user does not enter a number, a pop-up appears telling the user it is an incorrect input. How would I implement something to detect whether or not the user enters a number when the JButton is clicked? if i need to give more code, let me know.
JButton okay = new JButton("OK");
JTextField dataEntry = new JTextfield();
okay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
firstEntry = Float.parseFloat(dataEntry.getText());
//want to see if it's a float, if true, run the following code
confirm = true;
changeText();
dataEntry.setText("");
}
});
parseFloat throws a NumberFormatException if the passed String does not contain a parseable float. You can catch this exception to detect whether the user has entered a float:
try {
firstEntry = Float.parseFloat(dataEntry.getText());
} catch (NumberFormatException e) {
// input is not a float
}
Another option is to use a Scanner if you don't want to be handling exceptions:
Scanner scanner = new Scanner(dataEntry.getText());
if (scanner.hasNextFloat()) {
firstEntry = scanner.nextFloat();
} else {
// input is not a float
}
I would avoid of using catch-mechanism of exceptions to check if the value is a number because this is a very expensive procedure in java.
It would be better if you use FormattedTextFields: formattedtextfield
This needs some code but is a very elegant solution. You can also write your own formats with this concept.

Checking whether the text in a JTextField is a certain data type

I am trying to write some validation code in my class for my GUI. How would I go about getting the text from a JTextField into a while statement and prompting a JOptionPane for the user to enter the necessary number(double)? To be more specific, how do I check if what I got from the JTextField is a string/string+number/anything other than a number?
String text=JTextField.getText();
while(text.equals*a string or anything but a number*);
JOP("Invalid input ............ etc...
If you have time, here is my GUI and my class. I am trying to do this for the rest of the methods. But the answer to the above will suffice.
http://www.mediafire.com/?f079i1xtihypg1b
http://www.mediafire.com/file/f079i1xtihypg1b/FinanceGUI.java
Update:
This is what I have so far:
//get the text entered in the amountRentText
//JTextField and parse it to a Double
String amtRentIn=amountRentText.getText();
try{Double.parseDouble(amtRentIn);}
catch(NumberFormatException nfe){
while()
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
double rent= Double.parseDouble(amtRentIn);
fin.setRent(rent);
What do I put in the while?
String amtRentIn=amountRentText.getText();
boolean incorrect = true;
while(incorrect){
try{Double.parseDouble(amtRentIn);incorrect = false;}
catch(NumberFormatException nfe){
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
}
javax.swing.InputVerifier is designed for this. Your implementation of verify() could invoke parseDuble(). Here's another example.
A "cheap" not too beautiful solution that occurs to me would be using the Double.parseDouble(..) on that string, and being ready to catch the parsing exception that would occur in the event the String had any non-numeric content.

Categories