2015-02-12 2 views
0

У меня проблема с моими JButtons и JComboBox. Мне нужно показать сообщение, если пользователь не выбирает состояние, тогда он получает предупреждение, пока не выберет состояние. Но он продолжает закручиваться, и когда он я выбираю состояние, оно все еще говорит, чтобы выбрать состояние. Затем для JButtons пользователь, которому он подходит, выбирает один пол, но он может выбрать оба, и я не уверен, почему он это делает, когда он должен выбрать только один.Проблемы с JComboBox и JButton

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

} 
} 
+1

'! State.equals (state)' - когда бы объект 'state' не был равен самому себе? – immibis

+0

Думаете, вы имеете в виду '} else if (state == null) {' ... – MadProgrammer

ответ

1

Для более удобной комбинированной коробки не храните и не пустите состояние. Вместо этого используйте собственный рендерер для отображения сообщения типа «Выбрать состояние».

Тогда вы можете просто проверить, было ли выбрано состояние, убедившись, что метод getSelectedIndex() JComboBox не равен -1.

Отъезд Combo Box Prompt для индивидуального средства визуализации, который делает это за вас.

+0

, что имеет смысл, но как вы напишете это для раздела предупреждения? –

+0

может быть что-то вроде этого? '} Еще если (stateBox.getSelectedIndex() == -1) { \t \t \t \t \t \t \t \t \t \t \t \t JOptionPane.showMessageDialog (нуль, \t \t \t \t \t \t \t \t "Необходимо ввести состояние"); \t \t \t \t \t \t \t \t \t \t \t} ' –

+0

на самом деле спасибо, это был 0 не -1 –

0

Предупреждения для них работают лучше, но теперь я столкнулся с другой проблемой. Я установил предупреждение, если пользователь не поместил ничего в JTextFields для своего имени и фамилии, но пропустил оператор if из предупреждения и перешел на try/catch. теперь что мне делать?

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"); 

      } 

     } 
    }); 
+0

@camickr есть ли у вас идеи для текста? –

Смежные вопросы