How to validate if Text entered is a numeric number? - java

I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text1 = jTextField1.getText(); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = jTextField2.getText(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (text1 and text2 != <numeric number>){
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
// TODO add your handling code here:
}
Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?

Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float num1, num2, result;
try {
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
}

If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.
Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.
That said, you can, among other things, use Integer.parseInt(String s) to see if an arbitrary string can be parsed into an int; the method throws NumberFormatException if it can't. There are also Double.parseDouble, etc.
See also
Java Tutorials/Swing/How to use Formatted Text Field
How to use the Focus Subsystem/Input Validation
Java Tutorials/Internationalization/Formatting - Numbers and Currencies
Related questions
A simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?
A textbox class only accept integers in Java
Validating an integer or String without try-catch - java.util.Scanner option

try {
Integer.parseInt(foo);
} catch (NumberFormatException e) {
// Naughty
}

Try this:
String temp = txtField.getText();
try
{
int val = Integer.parseInt(temp);
}
catch(NumberFormatException e) {
System.out.println("Invalid");
}
To make it more enjoyable, use JOptionPane (makes it more more interactive)

textFieldCrDays = new JTextField();
textFieldCrDays.addKeyListener(new KeyAdapter() {
//// validate onlu numeric value
public void keyTyped(KeyEvent e) {
if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
{
// Optional
super.keyTyped(e);
}
else
{
// Discard the event
e.consume();
}
}
});

A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.
Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListener for the keyType event and check for the Char value. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers.
You could also do a relative length here as well:
textField.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent keyEvent)
{
if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
{
// Optional
super.keyTyped(keyEvent);
}
else
{
// Discard the event
keyEvent.consume();
}
}
});
You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example).
A good place for this would be on the focusLost event(?).
If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.
EDIT: Using Character.isLetter(keyEvent.getKeyChar()) is even more clear.

Related

Having trouble clearing a text field when an improper character is entered

I am trying to retrieve the values from a JTextField on a keypress to do something if the values are integers and to clear the field if the values are not integers. Every time I try to retrieve the value, I am getting the value entered before that(if I enter 12 I get 1 back then if I enter 123 I get 12 back) and when I try to clear the field on an invalid character everything but the invalid character gets cleared?
public void setUpListeners()
{
JTextField jT [] = myV.getTextFields();
jT[0].addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
int id = e.getID();
if (id == KeyEvent.KEY_TYPED)
{
char c = e.getKeyChar();
try
{
//check if chars entered are numbers
int temp = Integer.parseInt(String.valueOf(c));
String tempS = jT[0].getText();
System.out.println(tempS);
}
catch(Exception ex)
{
jT[0].setText("");
System.out.println("Not an integer");
}
}
}
});
}
You could do the following:
public static boolean validateNumber(char num){
return (num >= '0' && num <='9');
}
And then use parameter KeyEvent "e":
if(!validateNumber(e.getKeyChar()))
e.consume();
And instead of using
public void keyTyped(KeyEvent e){
use
public void keyReleased(KeyEvent e){
I think you will get what you need, I hope I have helped you ;)
Swing components use Model-View-Controller (MVC) [software] design pattern / architecture. The model holds the data. For a JTextField the data is the text it displays. The default model for JTextField is PlainDocument, however JTextField code actually refers to the Document interface which PlainDocument implements.
Look at the code for method getText() in class JTextComponent (which is the superclass for JTextField) and you will see that it retrieves the text from the Document.
When you type a key in JTextField, the character gets passed to the Document. It would appear that your keyTyped() method is invoked before the character you typed reaches the Document, hence when you call getText() in your keyTyped() method, you're getting all the text apart from the last character you typed.
That's one of the reasons not to use a KeyListener in order to validate the text entered into a JTextField. The correct way is detailed in the question that tenorsax provided a link to in his comment to your question.
Apart from DocumentFilter or JFormattedTextField (or even InputVerifier), you can add an ActionListener to JTextField which will execute when you hit Enter in the JTextField. You will find many on-line examples of how to implement each one of these options, including the link provided in tenorsax comment.

How to perform an action when only first key pressed?

I want a JTextFeild event when keyboard button pressed.I want concatenate "ADZ" text to the front whole text.(If we enter "2" whole text should be "ADZ2") THe Action will performed only first key press.After any key pressing action won't be performed.Action will performed only once.
I tried below code,but if type 22 it gives"ADZADZ22".
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
JTextFeild1.setText("ADZ"+num1);
I want this if type 22, it will gives ADZ22.
A simple way to solve it, is to check if the prefix is already there.
This avoids that the same prefix is added twice.
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
if (!num1.startsWith("ADZ"))
{
num1 = "ADZ" + num1;
JTextFeild1.setText(num1);
}
...
}
Please note: Java coding rules would suggest to make field names (e.g. jTextField) start with a lower case character. The same goes for method names (e.g. private void jTextField1KeyTyped)
public static int counter = 0;
Maintain a static counter at class level. At key press increase it by one. check :
if(counter == 1) {
// do your operation
}
Check if your JTextField is empty and then set a prefix. This method sets "ADZ" when the field is empty and you type something and then appends everything you type.
public void keyTyped(KeyEvent ke) {
if(txfInput.getText().equals("")) {
txfInput.setText("ADZ");
}
}

Catching String exceptions

I'm making a jTextField restrict integer input in netbeans and I don't know what to do.
I'm doing it like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
try {
String j = (String) txtName.getText();
} catch ("Which Exception to Catch?") {
if (!txtAge.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null,
"Please enter string values");
txtAge.setText(txtAge.getText().replaceAll("[^a-z]", ""));
}
}
}
What should I put on the catch?
You could just test the input against a regular expression using String.matches() to make sure it's only digits (no need to catch an exception such as a NumberFormatException - it can be considered bad practice to provoke exceptions to validate conditions).
String j = txtAge.getText();
if (!j.matches("\\d+")) {
// It is not a number
}
If you just want to try to convert to an Integer directly and catch an exception you should use Integer.parseInt() (it will throw a NumberFormatException if the input can't be parsed as an Integer):
String j = txtAge.getText();
try {
Integer i = Integer.parseInt(txtAge);
}
catch (NumberFormatException e) {
// j isn't a number...
}
EDIT: There seems to be a little confusion with the answer you provided. In your question the error message was Please enter integer values, as if valid input was only digits. In the answer you posted the message was Please enter String values.
If you want to validate the input doesn't have any numbers, you'll have to use another regex, such as .*\\d.*". If it matches, it means it has a digit. Or you could also use \\D+ to ensure it has one or more non-digits.
I've solved my problem like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
String j = (String)txtName.getText();
if ( j.matches("\\d+") && !txtName.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null, "Please enter String values");
txtName.setText("");
} }
Thanks for the ones who tried to help me :)

Display message dialog if JTextField does not contain data

I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}

How to check an empty Double JTextField

I've been working this for 2 days but I can't still figure how to check if the jtextfield is empty (Double not String) before passing it to my database.
I figured it out how to validate String if the field is empty, but I need to put the right code on how to validate Double if the field is empty.
Thanks in advance.
Here's my code:
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
String inventnamef = inventNameField.getText();
String categ = cmbname.getSelectedItem().toString();
double inventreorderf = Double.parseDouble(inventReorderField.getText());
..............
if ((inventCodeField.trim().Length()==0) || (inventNameField.trim().Length()==0)
To enforce formatting (numeric etc) you can use JFormattedTextField.
To ensure values are not blank see No blanks in JTextField
You are reading the double at first as a String. So, you can do something like this:
double inventreorderf;
if (inventReorderField.getText().trim().length == 0)
{
//Do something which should happen when the field is empty
}
else
{
try
{
inventreorderf = Double.parseDouble(inventReorderField.getText());
}
catch (Exception e)
{
//The user has entered an invalid number. Notify him/her here.
}
}

Categories

Resources