Hot questions for Using JTextField in if statement

Question:

How do I make an if statement which checks if all or just one text field is empty

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    if(jTextField1.getText().equals("") && jTextField2.getText().equals("") && jTextField3.getText().equals("")){
            JOptionPane.showMessageDialog(null, " please fill empty fields", "Input Error",JOptionPane.ERROR_MESSAGE);
    }else{
    }
}

Answer:

What I did is listing all the Widgets with a "or" statement:

 if ((attribut1.isEmpty() || attribut2.isEmpty() || attribut3.isEmpty() || attribut4.isEmpty()||attribut5.isEmpty()||attribut6.isEmpty()||attribut7.isEmpty()||attribut8.isEmpty()||attribut9.isEmpty()||attribut10.isEmpty())) {
        Toast.makeText(this, "fill in all details"

Definitely not the nicest solution but it works.

Question:

I have multiple JTextFields and JComboBox in my JFrame. So whenever I click the _Add_ button it will check if the four (4) text fields in Current Medication Panel is Empty. If it is not then Execute, but it also depends if the Personal info Panel text fields are filled.

But I have a problem when I use the if and else statement, if I use the if and else:

    if(condition if the first textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the second textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the third textfield is empty) {
        // execute something like the textfield turn to red
    } else{
        // execute save information of the patient
    }

In this situation if the 1st text field is empty then it will turn to red but if both 1st and 2nd text field is empty only the 1st text field turn to red.

I also tried the if, and if and if but were should put the else whenever there is no empty or invalid input where it will execute and save the patient info like this:

   if(condition if the first textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the second textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the third textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the fourth textfield is empty) {
     // execute something like the textfield turn to red
   } else

If I use this only the last if statement only works for the else statement. So if the last statement is true then execute, but not then else statement execute which is patient save info.

Is there any thing I can do about this? or is there any tutorial for me to learn more about Java and about if and else?


Answer:

In the Add button action listener's actionPerformed method, you can try this:

public void actionPerformed(ActionEvent e) {

    if (! textFieldsValid()) {
        // one or more of the text fields are empty
        // may be display a message in a JOptionPane
        System.out.println("The text fields are not filled with data, etc...");
        return;
    }

    // else, text fields have valid data, so do whatever processing it further...
}

/*
 * This method checks if the text fields are empty and sets their borders as red. Returns
 * a boolean false in case any of the text fields are empty, else true.
 */
private boolean textFieldsValid() {

    boolean validTextFields = true;

    if (textField1.getText().isEmpty()) {
        validTextFields = false;
        textField1.setBorder(new LineBorder(Color.RED));
    }

    if (textField2.getText().isEmpty()) {
        validTextFields = false;
        // textField2.setBorder(...)
    }

    // ... same with textField3 and textField4

    return validTextFields;
}

Question:

I am currently having two problems both at which i have been trying to solve for the past 3 hours.

  1. I cant get the input--; to decrement if input is not == to 0

  2. I cant get the JTextField input to update the the value i assign to it once the program is running. Ill type 22 in the running program click start and it will go to "test99". Pictures is an example of how i entered the value 66 then i pressed start and test99 came up instead of test66

I hope I was able to explain my problem to an extent you will be able to understand. I have read a lot of documentation about action listeners but currently the idea wont click for me. Any constructive criticism is welcome.

I also simplified my problem down as best as I could.

package test;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JButton;

public class test {

private JFrame frame;
private JButton btnStart;

/**
 * 
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                test window = new test();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public test() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */

private void initialize() {
    frame = new JFrame();
    JLabel Output = new JLabel("Time left: ");
    Output.setHorizontalAlignment(SwingConstants.CENTER);
    frame.getContentPane().add(Output, BorderLayout.CENTER);
    JTextField Input = new JTextField();
    btnStart = new JButton("start");

    Input.setText("99");
    int input = (int) (Double.parseDouble(Input.getText()));

    Input.setHorizontalAlignment(SwingConstants.CENTER);
    frame.getContentPane().add(Input, BorderLayout.SOUTH);
    Input.setColumns(10);
    frame.getContentPane().add(btnStart, BorderLayout.NORTH);
    frame.setBounds(100, 100, 300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Input.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {

          }
        });


    Timer t = new Timer(1000, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Output.setText("test" + input);

            if (input == 0) {
                ((Timer) e.getSource()).stop();
            }
            input--;
        }

    });

    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            t.start();
        }
    });

}

}


Answer:

I recommand to declare your input variables not in your function, but in your class. Otherwise you run into scope problems. Example:

public class test {

  private JFrame frame;
  private JButton btnStart;
  private int input;
  private JTextField Input;

  //...

}

Should fix the issue :)

I am not enterily sure about the second issue but if you want to count down from the entered value, you have to update your action listener:

btnStart.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        input = (int) (Double.parseDouble(Input.getText()));
        t.start();
    }
});

Question:

I have many more cases, but I'm wondering if there is a simpler way to do this. If the user enters 1 the program will convert from inches to cm, if the user enters 2, the program will convert from cm to feet, etc.

if (jTextField1.getText() == 1) {
    InchesToCm();
} else if (jTextField1.getText() == 2) {
    CmToFeet();
} else if (jTextField1.getText() == 3) {
    MetresToYards();
} else if (jTextField1.getText() == 4) {
    KmToMetres();
} else {
    jLabel8.setText("Error, try again");
}

Answer:

It depends on your definition of 'simpler' but you could use a switch statement. Like so:

switch(Integer.parseInt(jTextField1.getText())){
case 1:
    InchesToCm();
    break;
case 2:
    CmToFeet();
    break;
case 3:
    MetresToYards();
    break;
case 4:
    KmToMetres();
    break;
    default:
        jLabel8.setText("Error, try again");
        break;
}

This way you don't have to use a chain of if statements but if it's simpler is up to you.

I hope this helps :)

Question:

How can I make a JTextfield accept only Hebrew letters with if statement? I can do a long if statement with all the Hebrew letters but it will not look good. I found out that the Unicode of Hebrew first letter is \u05D0 and last one is \u05EA. How can I say that if the gettext is in between these 2 letters so show (meaning to check if the text entered is only a Hebrew letter), the user will add only one letter in each textfield. Thank you in advance


Answer:

Build an input validator with your validation logic, and attach it to your textField to verify input as you enter it. Steps: Combine the validation logic given by @peter-lawray with the mechanism of building an input verifier and you're good to go.

Question:

I am very new to Java and am taking a Java 1 class. I am trying to use a JComboBox selection in an if statement and then display an answer based on the selection in a JTextField. It all compiled correctly but the answer will not display and I don't Know what i need to change. I've searched and tried several different things but none seemed to work.

import javax.swing.*;
import java.awt.event.*;

public class HayDyGuiTempConv extends JFrame
{

public static void main(String[] args)
{
    new HayDyGuiTempConv();
}

private JButton buttonConvert;
private JButton exitButton;
private JTextField textAmount;
private String fieldText;
private JTextField field;



public HayDyGuiTempConv()
{

    this.setSize(440,150);
    this.setLocation(350,420);
    this.setTitle("Temperature Conversion");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ButtonListener bl = new ButtonListener();
    JPanel panel1 = new JPanel();
    panel1.add(new JLabel("Enter temperature to convert: "));

    textAmount = new JTextField(6);
    panel1.add(textAmount);

    JComboBox<String> comboBox = new JComboBox<> (new String[] {"C to F", "F to C"});
    comboBox.addActionListener(bl);
    panel1.add(comboBox);

    buttonConvert = new JButton("Convert");
    buttonConvert.addActionListener(bl);
    buttonConvert.setToolTipText("Convert the temperature.");
    panel1.add(buttonConvert);

    panel1.add(new JLabel("Temp: "));

    field = new JTextField(6);
    field.setEditable(false);
    panel1.add(field);

    exitButton = new JButton("Exit");
    exitButton.addActionListener(bl);
    exitButton.setToolTipText("Exit the program.");
    panel1.add(exitButton);

    this.add(panel1);

    this.setVisible(true);
}

private class ButtonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {


        if(e.getSource() == buttonConvert)
        {

            if(e.getSource() == ("C to F"))
            {
                double tempEntered = Double.parseDouble(textAmount.getText());
                double tempConverted = tempEntered - 32 * (5/9);
                String tempAmount = (Double.toString(tempConverted));
                field.setText(tempAmount);
            }
            else if(e.getSource() == ("F to C"))
            {
                double tempEntered = Double.parseDouble(textAmount.getText());
                double tempConverted = tempEntered * (9/5) + 32;
                String tempAmount = (String.format("%.2f",(tempConverted)));
                field.setText(tempAmount);
            }
        }
        else if(e.getSource() == exitButton)
        {
            System.exit(0);
        }
    }
}
}

Edit : I tried both suggestions and with both of them when I type in an number and try to convert I get this in the interactions pane: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JComboBox


Answer:

if(e.getSource() == ("C to F"))

The "source" of the event is a component, not a String. In this case it is the JComboBox.

You want to test the selected value of the combo box so the code should be something like:

JComboBox comboBox = (JComboBox)e.getSource();
int index = comboBox.getSelectedIndex();

If (index == 0)
    //  do C to F conversion
else
    //  do F to C conversion

Also, don't use "==" to compare String values. In the future for String comparison you use the equals(...) method of the String.

Edit:

I thought you were adding the ActionListener to the combobox. Then you can just automatically do the conversion when the item is selected from the combo box. There is no need for the button.

If you want to keep the button then you need to define your combo box as an instance variable in your class. Then you can just access the combo box by name.

Question:

    private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    if(pick1 > pick2 ){
    resultstf.setText("The New President is Koon!");
    }
    else if(pick2 > pick1){
    resultstf.setText("The New President is Baam!");
    }
    else if(pick1 == pick2){
    resultstf.setText("The Result for the new President is a Tie! Please Vote Again.");
    }
    if(pick3 > pick4){
    resultstf.setText("The New VP is Sachi!");
    }
    else if(pick4 > pick3){
    resultstf.setText("The New VP is Faker!");
    }
}

How do I print out multiple Text whenever I press the Result Button? Like I want to print out "The New President is Koon" and also printout "The New VP is Sachi" at the same time.


Answer:

Use a StringBuilder and build the message as you go along:

private void resultActionPerformed(java.awt.event.ActionEvent evt) {
    StringBuilder message = new StringBuilder();                                   
    // TODO add your handling code here:
    if (pick1 > pick2) {
        message.append("The New President is Koon!\n");
    }
    else if (pick2 > pick1) {
        message.append("The New President is Baam!\n");
    }
    else if (pick1 == pick2) {
        message.append("The Result for the new President is a Tie! Please Vote Again.\n");
    }
    if (pick3 > pick4) {
        message.append("The New VP is Sachi!\n");
    }
    else if (pick4 > pick3) {
        message.append("The New VP is Faker!\n");
    }

    resultstf.setText(message.toString());
}