Проблемы с JComboBox и JButton
У меня проблема с моими JButtons и JComboBox. Мне нужно показать сообщение, если пользователь не выбирает состояние, тогда он получает предупреждение, пока не выберет состояние. Но он продолжает портиться, и когда я выбираю состояние, он все равно говорит выбрать состояние. Затем для JButtons пользователю предлагается выбрать один пол, но он может выбрать оба, и я не уверен, почему он делает это, когда он должен выбрать только один.
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);
}
}
2 ответа
Для более дружественного поля со списком не храните и не пустите. Вместо этого используйте пользовательский рендерер для отображения сообщения, такого как "Выбрать состояние".
Затем вы можете просто проверить, выбрано ли состояние, убедившись, что метод getSelectedIndex() в JComboBox не равен -1.
Проверьте Combo Box Prompt для пользовательского рендерера, который сделает это за вас.
Предупреждения для тех, кто работает лучше, но сейчас я сталкиваюсь с другой проблемой. Я установил предупреждение, если пользователь не поместил ничего в JTextFields для своего имени и фамилии, но пропустил оператор предупреждения if и вместо этого пошел на попытку / отлов. что теперь мне делать?
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");
}
}
});