netbeans 重置JComboBox的值

azpvetkf  于 2022-11-10  发布在  其他
关注(0)|答案(3)|浏览(246)

我有一个JComboBox,其中包含一些雇员ID号(它们是整数值)。
我想将“Select employee”设置为JComboBox的默认值。由于此值是字符串格式,因此它会向我抛出一个异常,如“java.lang.NumberFormatException:对于输入字符串:“选择员工”"。如何执行此操作?
我的代码是:

public void clear()
 {
    cmb_emp_id.setSelectedItem("Select Employee");
    txt_emp_name.setText("");
    txt_department.setText("");
    txt_designation.setText("");
    joining_date.setDate(new Date());
    resign_date.setDate(new Date());
    txt_description.setText("");
 }

我如何才能做到这一点?

50pmv0ei

50pmv0ei1#

很难准确地说出您所追求的是什么,尤其是当您谈论的是数字格式异常时。
但是,要将JComboBox重置为其原始选择,只需执行以下操作

cmb_emp_id.setSelectedIndex(0);
vddsk6oq

vddsk6oq2#

请尝试以下方法:setSelectedIndex(int anIndex)
anIndex -一个整数,指定要选择的列表项,其中0指定列表中的第一项,-1表示没有选择

new9mtju

new9mtju3#

首先你必须把你的组合框写在一个数组中,这样你就可以调用索引的个数。

String[] array= { "name1","name2" };
    for (int i = 0; i < countries.length; i++) {
        comboBox.addItem(countries[i]);

然后如果你想重置组合框,你必须再次调用数组,然后使用以下代码:

for (int i = 0; i < array.length; i++) {
                                     //here you can give your combo the number of index
                comboBox.setSelected Index(0);
                comboBox.add Item(countries[i]);
            }

相关问题