【问题标题】:JCombobox and Switch statementsJCombobox 和 Switch 语句
【发布时间】:2014-06-02 02:06:00
【问题描述】:
我使用的是 Netbeans 6.9.1
我正在尝试以酒店注册表的形式制作一个 java 桌面应用程序。在这个程序中,我有一系列JComboBox,让用户输入入住人数、预订日期等。我想这样做,所以当按下按钮时会发生一个开关,检查是否这些框是在 None 或实际项目中选择的。
我的问题是。如果尚未输入 1 个或多个组合框,我该如何做到这一点,它会显示一条消息,说明未填写的内容
这是我尝试过的,但没有成功。
case 1:
Hotel.getSelectedItem().toString().equals("None");
Out.setText("Missing Hotel Selection");
我的问题是,我怎样才能做到这一点?
我是 Java 新手,所以请用我能理解的术语解释一下。
【问题讨论】:
标签:
java
swing
switch-statement
jcombobox
【解决方案1】:
假设您有三个名为:hotelSelection、noOfPeople、dayOfBooking 的 JComboBox 对象。因此,首先使用以下代码为这些组合框设置名称。我们将在 switch-case 之后使用它。
hotelSelection.setName("Hotel Selection");
noOfPeople.setName("No of people");
dayOfBooking.setName("Day of booking");
现在点击提交按钮时会调用下面的方法。
private void submitButtonClicked(java.awt.event.ActionEvent evt) {
// Array of all combobox in that you want to check
ArrayList<JComboBox> allCombobox = new ArrayList<>();
allCombobox.add(hotelSelection);
allCombobox.add(noOfPeople);
allCombobox.add(dayOfBooking);
for (JComboBox temp : allCombobox) {
switch (temp.getSelectedItem().toString()) {
case "None":
// If it is "hotel selection" combobox
if (temp.getName().equalsIgnoreCase("Hotel Selection"))
{
System.out.println("Missing Hotel Selection");
}
// If it is "no of people" combobox
else if (temp.getName().equalsIgnoreCase("No of people"))
{
System.out.println("Missing No of people");
}
// If it is "day of booking" combobox
else if (temp.getName().equalsIgnoreCase("Day of booking"))
{
System.out.println("Missing the Day of booking");
}
}
}
}
希望你能找到答案。
【解决方案2】:
你可以使用类似...
switch (Hotel.getSelectedItem().toString()) {
case "None":
break;
// Other cases
}
仔细查看The switch Statement了解更多详情