java 如何检查是否未选择 jcombobox 选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29271171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if jcombobox selection has not been selected?
提问by MBN
comboGender.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Male", "Female" }));
comboCivilStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Single", "Married", "Widow / Widower", "Divorced" }));
if(txtAddress.getText().trim().equals("")){
JOptionPane.showMessageDialog(null, "INVALID ADDRESS");
}else if(comboGender.getSelectedItem().toString().equals("")){
JOptionPane.showMessageDialog(null, "SELECT A GENDER");
}else if(comboCivilStatus.getSelectedItem().toString().equals("")){
JOptionPane.showMessageDialog(null, "SELECT A CIVIL STATUS");
}
*just a portion of my code *
*只是我代码的一部分*
hello stackoverflow. i am new here. and i am also a novice in java programming. i seem to be having a problem that i cannot figured out how solve.
你好计算器溢出。我刚来这地方。而且我也是java编程的新手。我似乎遇到了一个我不知道如何解决的问题。
i am trying to make if and else if statements to check whether my textfields and comboboxes are empty. and then trying to return a showMessageDialog telling me to input something. i already figured out how to do the textboxes. but the combobox i cannot seem to understand how to do the syntax. can anyone please help? thank you.
我正在尝试使用 if 和 else if 语句来检查我的文本字段和组合框是否为空。然后试图返回一个 showMessageDialog 告诉我输入一些东西。我已经想出了如何做文本框。但是组合框我似乎无法理解如何执行语法。有人可以帮忙吗?谢谢。
by the way i am using java netbeans.
顺便说一下,我正在使用 java netbeans。
采纳答案by MadProgrammer
You can use JComboBox#getSelectedIndex
, which will return -1
if nothing is selected or JComboBox#getSelectedItem
which will return null
if nothing is selected.
您可以使用JComboBox#getSelectedIndex
,-1
如果未选择任何内容JComboBox#getSelectedItem
,它将返回,或者如果未选择任何内容,它将返回null
。
//...
}else if(comboGender.getSelectedIndex() == -1){
//...
Take a look at How to Use Combo Boxesfor more details
查看如何使用组合框以获取更多详细信息