java JComboBox setSelectedItem 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16756367/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:54:13  来源:igfitidea点击:

JComboBox setSelectedItem does not work

javaswingjpaneljcombobox

提问by Yevgraf Andreyevich Zhivago

I am trying to set the setSelectedItemof the JComboBoxin the constructor of my JPanelclass just after populating the combobox.

我想设置setSelectedItemJComboBox在我的构造函数JPanel类只是填充组合框后。

I am set the value for textbox, but I can't figure out why setSelectedItemdoes not seem to work. Any ideas?

我设置了文本框的值,但我不知道为什么setSelectedItem似乎不起作用。有任何想法吗?

public StudentProfilePanel(StudentInfo si) {

        yesButton.setBounds(50, 346, 69, 40);
        noButton.setBounds(121, 346, 56, 40);
        this.add(yesButton);
        this.add(noButton);
        setLayout(null);
        comboBoxYear.setModel(new DefaultComboBoxModel(years()));
        comboBoxYear.setBounds(202, 365, 62, 23);
        if(si.birthdate!=null){
            //System.out.println("year value : ["+dateofbirth(si.birthdate)[2]+"]");
            comboBoxYear.setSelectedItem(dateofbirth(si.birthdate)[2]);

        }

        add(comboBoxYear);
        comboBoxMonth.setModel(new DefaultComboBoxModel(new String[]{"01","02","03","04","05","06","07","08","09","10","11","12"}));
        comboBoxMonth.setBounds(285, 365, 56, 23);

        //set month value
        if(si.birthdate!=null){
            //comboBoxMonth.setSelectedItem(dateofbirth(si.birthdate)[1]);
            comboBoxMonth.setSelectedItem("04");
            System.out.println("month value : ["+dateofbirth(si.birthdate)[1]+"]");
        }
        add(comboBoxMonth);
        comboBoxDay.setModel(new DefaultComboBoxModel(days()));
        comboBoxDay.setBounds(351, 365, 54, 23);
        if(si.birthdate!=null){
            //comboBoxDay.setSelectedItem(dateofbirth(si.birthdate)[0]);
            comboBoxDay.setSelectedItem(dateofbirth(si.birthdate)[0]);
        }
        add(comboBoxDay);

        textFieldFirstName = new JTextField();
        textFieldFirstName.setBounds(21, 321, 171, 21);
        add(textFieldFirstName);
        textFieldFirstName.setColumns(10);
        // set the value of first name
        textFieldFirstName.setText(si.firstName);

        textFieldLastName = new JTextField();
        textFieldLastName.setBounds(242, 321, 163, 21);
        add(textFieldLastName);
        textFieldLastName.setColumns(10);
        //set the value of the last name
        textFieldLastName.setText(si.lastName);

        JPanel panelPersonPhoto = new ImagePanel(
                "C:\Users\MDJef\Pictures\Wallpaper\General\11.jpg");
        panelPersonPhoto.setBorder(new TitledBorder(null, "",
                TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panelPersonPhoto.setBounds(21, 20, 384, 291);
        add(panelPersonPhoto);
    }

Thanks very much.

非常感谢。

helper methods that I used

我使用的辅助方法

    // jf : helper method
    public String[] years() {
        String[] results = new String[90];
        for (int i = 0; i < 90; i++) {
            results[i] = Integer.toString(1900 + i);
        }
        return results;
    }

    // jf : helper method
    public String[] months() {
        String[] results = new String[12];
        for (int i = 0; i < 12; i++) {
            results[i] = Integer.toString(i + 1);
        }
        return results;
    }

    // jf : helper method
    public String[] days() {
        String[] results = new String[31];
        for (int i = 0; i < 31; i++) {
            results[i] = Integer.toString(i + 1);
        }
        return results;
    }

    // jf : helper method
    public String[] dateofbirth(String dob) {
        String[] tokens = dob.split("-");
        return tokens;
    }

回答by MadProgrammer

The values assigned to the combo box are not the same values you are trying set.

分配给组合框的值与您尝试设置的值不同。

For example, the years are Strings from 1900 - 1990, but if I supply a value 72, there is no matching value in the combo box to match to.

例如,年份是String从 1900 年到 1990 年,但如果我提供一个 value 72,则组合框中没有匹配的值可以匹配。

Equally, your daysand monthsmethods are only returning values that are not padded (ie 01), where as, in your code, you're trying to set the value using a padded value (ie 04), meaning there is no matching value...

同样,您的daysmonths方法仅返回未填充的值(即01),因为在您的代码中,您尝试使用填充值(即04)设置值,这意味着没有匹配的值...

You have a number of options...

你有很多选择...

You could...

你可以...

Convert all the values to an int, meaning that the values in the combo box are simply ints. You would then need to convert the date values to ints as well.

将所有值转换为 an int,这意味着组合框中的值只是ints。然后,您还需要将日期值转换为ints。

This would make your helper code look more like...

这会让你的助手代码看起来更像......

public int[] years() {
    int[] results = new String[90];
    for (int i = 0; i < 90; i++) {
        results[i] = 1900 + i;
    }
    return results;
}

public int[] months() {
    int[] results = new String[12];
    for (int i = 0; i < 12; i++) {
        results[i] = i + 1;
    }
    return results;
}

public int[] days() {
    int[] results = new String[31];
    for (int i = 0; i < 31; i++) {
        results[i] = i + 1;
    }
    return results;
}

public int[] dateofbirth(String dob) {
    int[] tokens = dob.split("-");
    int[] values = new int[tokens.length];
    for (int index = 0; index < tokens.length; index++) {
      values[index] = Integer.parse(tokens[index]);
    }
    return index;
}

A better solution

更好的解决方案

Would be to use a JSpinner, which would take care of date rolling issues and validation automatically.

将使用 a JSpinner,它将自动处理日期滚动问题和验证。

Check out Using Standard Spinner Models and Editors

查看使用标准 Spinner 模型和编辑器

回答by Daniel Lerps

When you call comboBoxMonth.setSelectedItem("04");you try to select a newly created String which is not equal to the one which is in your JComboBox. Ergo it does not get selected.

当您打电话时,comboBoxMonth.setSelectedItem("04");您尝试选择一个新创建的字符串,该字符串与您的JComboBox. 因此它不会被选中。

You can try something like this instead:

你可以尝试这样的事情:

String[] months = new String[] {"01","02","03","04","05","06","07","08","09","10","11","12"};
comboBoxMonth.setModel(new DefaultComboBoxModel(months));

comboBoxMonth.setSelectedItem(months[3]);

Edit:Try this. It uses the index of the item instead. Just make sure you add the months in order to the array.

编辑:试试这个。它使用项目的索引代替。只要确保将月份添加到数组中即可。

String[] months = new String[] {"01","02","03","04","05","06","07","08","09","10","11","12"};
comboBoxMonth.setModel(new DefaultComboBoxModel(months));

if(si.birthdate!=null)
{
    comboBoxMonth.setSelectedIndex(Integer.parseInteger(dateofbirth(si.birthdate)[1]) - 1);
}

回答by camickr

Not related to your problem, but:

与您的问题无关,但是:

yesButton.setBounds(50, 346, 69, 40);
noButton.setBounds(121, 346, 56, 40);
setLayout(null);

Don't use a null layout and setBounds(...). Swing was designed to be used with Layout Manager. In the long run you will save time.

不要使用空布局和 setBounds(...)。Swing 旨在与布局管理器一起使用。从长远来看,您将节省时间。

if(si.birthdate!=null){

Don't access variables in your class directly. Create a getter method to access the properties of your class.

不要直接访问类中的变量。创建一个 getter 方法来访问类的属性。

//System.out.println("year value : ["+dateofbirth(si.birthdate)[2]+"]");
comboBoxYear.setSelectedItem(dateofbirth(si.birthdate)[2]);

Don't always try to force you code into a single statement. Instead do something like:

不要总是试图强迫你把代码写成一个单一的语句。而是执行以下操作:

String birthdate = dateofbirth(si.birthdate[2]);
System.out.println("year value : [" + birthdate +"]");
comboBoxYear.setSelectedItem(birthdate);

This helps with your debugging because now you know that the variable you display is the same variable that you are trying to use in the setSelectedItem() method. It saves typing the statement twice and avoids typing mistakes.

这有助于您的调试,因为现在您知道您显示的变量与您尝试在 setSelectedItem() 方法中使用的变量相同。它可以节省两次输入语句并避免输入错误。

回答by Pramod

Use the following: comboBoxMonth.setSelectedItem(index of the array);

使用以下内容: comboBoxMonth.setSelectedItem(index of the array);

回答by asdf

For other developer with the same issue: A closer look into the implementation of setSelectedItem(Object anObject)from JComboBoxmight help:

对于具有相同问题的其他开发人员:仔细研究setSelectedItem(Object anObject)from的实现JComboBox可能会有所帮助:

public void setSelectedItem(Object anObject) {
    Object oldSelection = selectedItemReminder;
    Object objectToSelect = anObject;
    if (oldSelection == null || !oldSelection.equals(anObject)) {

        if (anObject != null && !isEditable()) {
            // For non editable combo boxes, an invalid selection
            // will be rejected.
            boolean found = false;
            for (int i = 0; i < dataModel.getSize(); i++) {
                E element = dataModel.getElementAt(i);
                if (anObject.equals(element)) {
                    found = true;
                    objectToSelect = element;
                    break;
                }
            }
            if (!found) {
                return;
            }
        }

...

In the loop your object is compared with an object of the dataModel with the specific type E. In the implementation of equals() from String you can see a verification of class/interface, length and each character one after another. That means, our object must have same type and all characters must be the same!

在循环中,您的对象与具有特定类型的 dataModel 对象进行比较E。在 String 的 equals() 实现中,您可以看到一个接一个地验证类/接口、长度和每个字符。这意味着,我们的对象必须具有相同的类型并且所有字符必须相同!

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

And this is the most annoying part if (anObject.equals(element))in setSelectedItem! You cant override equals method from your element. For example StudentInfoand compare other types like strings or integers to it. Simple example. You implement combobox like this JComboBox<StudentInfo>and you want to select the student with int id = 2;. So it compares now Integerwith StudentInfo. Here you have to override equals from Integer...

这是最恼人的部分if (anObject.equals(element))setSelectedItem!您不能从您的元素覆盖 equals 方法。例如StudentInfo,将其他类型(如字符串或整数)与其进行比较。简单的例子。您像这样实现组合框,JComboBox<StudentInfo>并且想要选择带有int id = 2;. 所以它现在IntegerStudentInfo. 在这里,您必须从Integer...

My proposal is to swap it. Create own class, add boolean selectingItemand override setSelectedItem(Object anObject)and contentsChanged(ListDataEvent e)(this method one-to-one). Nevertheless, I had side effects in one project...

我的建议是换掉它。创建自己的类,添加boolean selectingItem和覆盖setSelectedItem(Object anObject)contentsChanged(ListDataEvent e)(此方法一对一)。尽管如此,我在一个项目中产生了副作用......

回答by BabaNew

The item you wish to set as selected must share the classof the objects stored in the JComboBox.

您希望设置为选中的项目必须共享存储在 JComboBox 中的对象的类

public static void main(String[] args) {
    String[] items = {"1", "2", "3"};
    JComboBox jcb = new JComboBox(items);
    jcb.setSelectedItem(3);
    System.out.println(jcb.getSelectedItem());
    jcb.setSelectedItem(3+"");
    System.out.println(jcb.getSelectedItem());
}

Output of the above code:

上面代码的输出:

1
3