Display message dialog if JTextField does not contain data - java

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;
}

Related

Checking to see if string has been parsed after event has occured?

I'm trying to make sure that the first character the user enters in this textbox is a letter. If it isn't, however, there will be a message box pop-up notifying the user that the first character cannot be a number, and must be a number. The problem is that the program completely ignores the code after the event occurs to check and see if there is a letter in the first position.
if (event.getSource() == item2)
{
string = String.format("Account number: %s", event.getActionCommand());
str = string.substring(1);
try{
Integer.parseInt(string.substring(0,1));
parsable = true;
}catch(NumberFormatException e){
parsable = false;
}
if(parsable == true)
{
JOptionPane.showMessageDialog(null, "ENTER THE LETTER CORRESPONDING WITH YOUR ACCOUNT NUMBER AS THE FIRST CHARACTER IN THE TEXT FIELD.");
}
/*
try
{
Integer.parseInt(str);
}
catch(NumberFormatException e)
{
String.format("enter a valid number");
}
*/
}
Any help is appreciated.
because you are using String.format("Account.... your string's first character will always be 'A' of Account you have to check on String which you recived from event.getActionCommand() mathod

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.
}
}

Java - Can't get getText in jTextArea to work properly

I have a seperate JFrame where there is a text box (jTextArea) that takes numbers as inputs, each separated with a new line. Upon closing the JFrame with the text box, the data is supposed to be stored in an ArrayList of integers. The ArrayList is checked when clicking a button in the main JFrame and errors are logged if they happen.
The code for the JFrame with the jTextArea looks like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
boolean success = false;
try{
selectedTime = Long.parseLong(jTextField1.getText());
if(selectedTime >= 10000){
success = true;
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
try{
for(int i = 0; i < jTextArea1.getLineCount(); i++){
n = Integer.parseInt(jTextArea1.getText(jTextArea1.getLineStartOffset(i),jTextArea1.getLineEndOffset(i)));
if(n <= 172){
worldsChosen.add(n);
}
}
}catch(Exception e){
errorsHappened = true;
}
}
}else{
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not above or equal to 10000 ms. Please try again.");
success = false;
}
}catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not set in numbers exclusively. Please try again.");
success = false;
}
if(success){
gui.hideWorlds();
}
}
Note: it also checks whether a text box has a number input equal to or above 10000 (this works).
The code for the main JFrame:
if(jCheckBox5.isSelected()){
checkWorld = true;
if(!worldsChosen.isEmpty()){
changeWorlds = true;
}else{
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{
errorsHappened = false;
}
if(errorsHappened == true){
log("One or multiple worlds weren't added due to incorrect formatting.");
log("Retry to make script automatically change worlds.");
}
Whenever I run the script with the check box selected and something formatted correctly in the text area
(like this):
1
2
3
4
5
etc.
It outputs all of the log messages (as if the check box had been selected but none of the inputs were formatted correctly).
I've tried to the best of my knowledge to fix this, but I just can't see how it messes up.
Any help appreciated :).
Mike Haye.
Read the api doc of getText(int, int): the second argument is not an offset. It's a length.
Side note 1: it should probably be easier to get all the text as a single string and split on newline chars, and the parse every string into an integer.
Side note 2: The test if (jTextArea1.equals("")) can't succeed. A JTextArea instance will never be equals to a String instance.
I didn't check the complete program, but this is wrong:
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
Did you forget to add the call of getText() ? The line as it is will always be evaluated to true, because the instance object of JTextArea is never equal to "" or null. The latter would imply that the jTextArea1 object was null itself. Which would give you a NPE when you call the equals method.
Do you reset the flag before checking the conditions? Consider the following case:
//suppose errorsHappened is true here
if(jCheckBox5.isSelected()){ //we get true here
checkWorld = true;
if(!worldsChosen.isEmpty()){ //not empty, so this branch is taken
changeWorlds = true;
}else{ //worldsChosen is not empty, so this would not be logged
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{ //checkbox is selected, so no reset to false here
errorsHappened = false;
}
//due to the checkbox being selected and worldsChosen not being empty,
//errorsHappend is still true (which is wrong)

String comparison for button events

I have a String named updatedDisplay that is set to empty in the constructor.
The buttons[] are JButtons and alarmCode is a String field.
I want the user to press four buttons (and they should be concatenated and stored in the updatedDisplay field).
The checkCode() method is executed to try match updatedDisplay against alarmCode. Trouble is, they never match. I think it may be something to do with a "space" when I originally declare my updatedDisplay as follows:
private String updatedDisplay = " ";
The updatedDisplay field doesn't seem to be storing the e.getActionCommand() value.
//add actionListeners to each button (except the "clear" button) to display value on screen
for (int i = 0; i< (buttons.length -1); i++) {
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//store the name of the button in a local variable
String command = e.getActionCommand();
System.out.println("You clicked " + command);
updatedDisplay = updatedDisplay + command;
//updatedDisplay = command;
System.out.println (updatedDisplay);
screen.setText(updatedDisplay);
}
});}
I have an armButton that, when pressed, should trigger the checkCode() method. The method checks if updatedDisplay and alarmCode are equal:
//add actionListener to the arm button
armButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
checkCode();
}
});
checkCode():
public void checkCode() {
//check if user entered the correct code
if (updatedDisplay == alarmCode)
{
updatedDisplay = "System Armed!";
screen.setText(updatedDisplay);
}
else
{
updatedDisplay = "Incorrect Code, Try again!";
screen.setText(updatedDisplay);
}
}
Even when I output the button presses to the terminal window they look right - but as I said, I suspect a "space" is being entered at the start.
Any ideas?
Solution
Try:
if( updatedDisplay.equals( alarmCode ) { // ...
Comparison
To understand this, read:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Summary
Since updatedDate and alarmCode are object references, you must ask the objects to compare their values. You can think of them as pointers whose values are locations in memory that contain strings. Rather than comparing the value of the pointers (references), you want to compare the text that starts at that memory location.

How to validate if Text entered is a numeric number?

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.

Categories

Resources