0

I am having an issue with my JButtons and JComboBox I need to show a message if the user does not select a state then he gets a warning until he selects a state. But it keep screwing up and when it I do select a state it still tells to select a state. Then for the JButtons the user it suppost to pick one gender but he can pick both both and I am not sure why its doing that when it should only pick one.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JRadioButton;

private JPanel infoPanel = new JPanel();
private JTextField firstname;
private JTextField lastname;
private JTextField textArea;
private JLabel labelAge;
private JTextField age;
private JLabel lblState;
private JComboBox stateBox;
private JLabel labelSex;
private JRadioButton maleButton;
private JRadioButton femaleButton;

// creating the frame
public EnhancedWelcomeGUI() {

    // title
    super("Enhanced Welcome GUI");

    // Layout set up
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 506, 203);
    setContentPane(infoPanel);

    // Label to display Programmer Info
    JLabel programmerInfo = new JLabel(
            "Patrick McCully, CMIS 242, Homework 1");

    // Labeling for first name
    JLabel labelFirstName = new JLabel("First Name:");

    // text field for the first name
    firstname = new JTextField();
    firstname.setColumns(10);

    // labeling for the last name
    JLabel labelLastName = new JLabel("Last Name:");

    // text field for the last name
    lastname = new JTextField();
    lastname.setColumns(10);

    // labeling for the text field
    labelAge = new JLabel("Age:");

    // text field for the age
    age = new JTextField();
    age.setColumns(10);

    // the text field to display back to the user
    textArea = new JTextField();
    textArea.setEditable(false);

    lblState = new JLabel("State:");

    stateBox = new JComboBox();
    stateBox.setModel(new DefaultComboBoxModel(new String[] { "",
            "Alabama", "Alaska", "Arizona", "Arkansas", "California",
            "Colorado", "Connecticut", "Delaware", "Florida", "Georgia",
            "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
            "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
            "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
            "Nebraska", "Nevada", "New Hampshire", "New Jersey",
            "New Mexico", "New York", "North Carolina", "Ohio", "Oklahoma",
            "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
            "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
            "Washington", "West Virginia", "Wisconsin", "Wyoming" }));

    labelSex = new JLabel("Sex:");
    maleButton = new JRadioButton("Male");
    femaleButton = new JRadioButton("Female");

    // the submit button when the user has entered the information
    JButton buttonWelcome = new JButton("Submit");

    //layout 
    GroupLayout groupLayoutPanel = new GroupLayout(infoPanel);

    groupLayoutPanel.setHorizontalGroup(
        groupLayoutPanel.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayoutPanel.createSequentialGroup()
                .addGap(10)
                .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                    .addComponent(programmerInfo, GroupLayout.PREFERRED_SIZE, 226, GroupLayout.PREFERRED_SIZE)
                    .addGroup(groupLayoutPanel.createSequentialGroup()
                        .addComponent(labelFirstName, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE)
                        .addGap(52)
                        .addComponent(labelLastName, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE)
                        .addGap(53)
                        .addComponent(labelAge, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)
                        .addGap(71)
                        .addComponent(lblState, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE))
                    .addGroup(groupLayoutPanel.createSequentialGroup()
                        .addComponent(firstname, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
                        .addGap(10)
                        .addComponent(lastname, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
                        .addGap(10)
                        .addComponent(age, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
                        .addGap(10)
                        .addComponent(stateBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGroup(groupLayoutPanel.createSequentialGroup()
                        .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                            .addComponent(labelSex, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)
                            .addGroup(groupLayoutPanel.createSequentialGroup()
                                .addGap(28)
                                .addComponent(maleButton))
                            .addGroup(groupLayoutPanel.createSequentialGroup()
                                .addGap(77)
                                .addComponent(femaleButton)))
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(buttonWelcome, GroupLayout.PREFERRED_SIZE, 135, GroupLayout.PREFERRED_SIZE))
                    .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 471, GroupLayout.PREFERRED_SIZE)))
    );
    groupLayoutPanel.setVerticalGroup(
        groupLayoutPanel.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayoutPanel.createSequentialGroup()
                .addGap(11)
                .addComponent(programmerInfo)
                .addGap(10)
                .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                    .addComponent(labelFirstName)
                    .addComponent(labelLastName)
                    .addComponent(labelAge)
                    .addComponent(lblState))
                .addGap(11)
                .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                    .addComponent(firstname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(lastname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(age, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(stateBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(10)
                .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                    .addComponent(maleButton)
                    .addGroup(groupLayoutPanel.createSequentialGroup()
                        .addGroup(groupLayoutPanel.createParallelGroup(Alignment.LEADING)
                            .addGroup(groupLayoutPanel.createSequentialGroup()
                                .addGap(4)
                                .addComponent(labelSex))
                            .addGroup(groupLayoutPanel.createParallelGroup(Alignment.BASELINE)
                                .addComponent(femaleButton)
                                .addComponent(buttonWelcome)))
                        .addGap(6)
                        .addComponent(textArea, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                .addGap(26))
    );
    infoPanel.setLayout(groupLayoutPanel);

    buttonWelcome.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent pressing) {

            int userAge;

            // a try/catch to catch any error and display
            // back to the user that he must finish
            try {

                String first = firstname.getText();
                String last = lastname.getText();
                Object state = stateBox.getSelectedItem();
                userAge = Integer.parseInt(age.getText());
                boolean male = maleButton.isSelected();
                boolean female = femaleButton.isSelected();

                // warning section
                if (userAge <= 0) {

                    JOptionPane.showMessageDialog(null,
                            "Must be a positive age");

                } else if (!state.equals(state)) {

                    JOptionPane.showMessageDialog(null,
                            "Must select state");

                }                   

                if (male) {

                    textArea.setText("Welcome Male " + first + ", " + last
                            + " of " + userAge + " years old from " + state);

                } else if (female) {

                    textArea.setText("Welcome Female " + first + ", "
                            + last + " of " + userAge + " years old from "
                            + state);

                }

                // display back the error as a pop up
            } catch (Exception e) {

                JOptionPane.showMessageDialog(null,
                        "Must Complete your Info");

            }

        }
    });

}

// to execute the program
public static void main(String[] args) {

    EnhancedWelcomeGUI frame = new EnhancedWelcomeGUI();
    frame.setVisible(true);

}
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

2 Answers2

1

For a more friendly combo box, don't store and empty state. Instead use a custom renderer to display a message like "Select State".

Then you can simply test if a state has been selected by making sure the getSelectedIndex() method of JComboBox is not -1.

Check out Combo Box Prompt for a custom renderer that does this for you.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • that makes sense but how would you write that for the warning section? –  Feb 12 '15 at 06:39
  • maybe something like this? `} else if(stateBox.getSelectedIndex() == -1){ JOptionPane.showMessageDialog(null, "Must enter state"); }` –  Feb 12 '15 at 06:55
  • @PatrickWilliamMcCully, if you are using my suggestion and my `ComboBoxPrompt`, then you need to test -1. If you are still adding a dummy value containing "" then you would use 0. I don't recommend the second approach since the combo box should only contain valid data. – camickr Feb 12 '15 at 15:48
0

The warnings for those are working better but I am now running into another issue. I set up a warning if the user did not put anything in the JTextFields for his first name and last name but its skipping the if statement of the warning and going for the try/catch instead. now what do I do?

buttonWelcome.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent pressing) {

            int userAge;

            // a try/catch to catch any error and display
            // back to the user that he must finish
            try {

                String first = firstname.getText();
                String last = lastname.getText();
                Object state = stateBox.getSelectedItem();
                userAge = Integer.parseInt(age.getText());
                boolean male = maleButton.isSelected();
                boolean female = femaleButton.isSelected();

                // warning section

                if (firstname.getText().trim().isEmpty()) {

                    JOptionPane.showMessageDialog(null,
                            "Must enter first name");

                } else if (lastname.getText().trim().isEmpty()) {

                    JOptionPane.showMessageDialog(null,
                            "Must enter last name");

                } else if (userAge <= 0) {

                    JOptionPane.showMessageDialog(null,
                            "Must be a positive age");

                } else if (stateBox.getSelectedIndex() == 0) {

                    JOptionPane
                            .showMessageDialog(null, "Must select state");

                } else if (buttonGenders.isSelected(null)) {

                    JOptionPane.showMessageDialog(null,
                            "Must select gender");

                }

                if (male) {

                    textArea.setText("Welcome Male " + first + ", " + last
                            + " of " + userAge + " years old from " + state);

                } else if (female) {

                    textArea.setText("Welcome Female " + first + ", "
                            + last + " of " + userAge + " years old from "
                            + state);

                }

                // display back the error as a pop up
            } catch (Exception e) {

                JOptionPane.showMessageDialog(null,
                        "Must Complete your Info");

            }

        }
    });