JTextfield Listener for Integers - java

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.

Related

How to know if the JTextField is empty?

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.

How to verify textField input?

I know this shouldn't be too difficult but my searching hasn't led to anything useful yet. All I want to do is make sure the user inputs a positive integer into a textField. I've tried:
public class myInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent jc) {
String text = ((jTextFieldMTU) jc).getText();
//Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
So in my main code I want to use this to display "OK" if successful and "Enter a positive number" if not successful.
Can someone point me in the right direction please? Thanks!
You could use a try-catch block to check if the input is an integer:
try {
int i = Integer.parseInt(input);
// input is a valid integer
}
catch (NumberFormatException e) {
// input is not a valid integer
}
String has a matches method you can use with regular expressions to see if the contents match a particular pattern. The regular expression for positive integers is ^[1-9]\d*$ so you can use it like this...
boolean matches = text.matches("^[1-9]\d*$");
if(matches){
//Do something if it is valid
}else{
//Do something if it is not
}
I suggest you use try catch.
Catch the NumberFormatException.
In this way you check if the text can be parsed to an integer. If not you can display an error message to the user.
After that you can us an if else statement to check if the number is positive if not positive you can give the user an error message. I suggest you research try catch if you don't know it.

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.

java character textfield validation

I want name textfield validation and I am using this code, what is not working perfectly.
Name_text.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent EVT){
if(EVT.getKeyChar()>='a'&& EVT.getKeyChar()<='z'|| EVT.getKeyChar()>='A'&& EVT.getKeyChar()<='Z'|| EVT.getKeyChar()==8|| EVT.getKeyChar()==26){
Name_text.setEditable(true);
}
else{
JOptionPane.showMessageDialog(null, "enter characters only");
}
You really should perform this type of validation using the DocumentFilter class, this is exactly what it's designed for. If the user pastes text into the field or you use setText, you will not be notified of the change via the KeyListener
You could also check out this for a number of examples
I guess you want to validate with this code :
if (Character.isDigit(EVT.getKeyChar())) {
Name_text.setEditable(true);
Name_text.setText("");
} else {
JOptionPane.showMessageDialog(null, "enter characters only");
}
Edited by your comment.

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