JComboBox setSelectedItem does not work

14,179

Solution 1

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.

Equally, your days and months methods 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...

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.

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.

Check out Using Standard Spinner Models and Editors

Solution 2

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.

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);
}

Solution 3

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.

if(si.birthdate!=null){

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

//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.

Share:
14,179
June
Author by

June

Applied Data Scientist, MCSA, CPA Australia Accountant

Updated on June 04, 2022

Comments

  • June
    June almost 2 years

    I am trying to set the setSelectedItem of the JComboBox in the constructor of my JPanel class just after populating the combobox.

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

    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;
        }
    
  • June
    June almost 11 years
    With your solution, I now can set the value for comboboxmonth, but it failed again when I try to do it inside the if(si.birthdate!=null){ clause
  • Daniel Lerps
    Daniel Lerps almost 11 years
    Do you get the output of System.out.println("month value : ["+dateofbirth(si.birthdate)[1]+"]"); on your console when you run the program?
  • MadProgrammer
    MadProgrammer almost 11 years
    "you try to select a newly created String which is not equal to the one which is in your JComboBox" - My simple test didn't show this problem...
  • June
    June almost 11 years
    yeah, println works fine. month value : [04] month value : [04] month value : [07] month value : [04] month value : [04] month value : [07]
  • Daniel Lerps
    Daniel Lerps almost 11 years
    It's a bit hard to tell without knowing what dateofbirth() does. Does it create new Strings for it's return array?
  • June
    June almost 11 years
    it splits a string into string array by delima
  • Daniel Lerps
    Daniel Lerps almost 11 years
    It's maybe better to go with a selection via the index. See The update above.
  • June
    June almost 11 years
    Thanks Daniel, I have just tried that, but it failed again. Thanks anyway. Something wired is going on with my code, this should not be that hard.
  • Alberto Martín
    Alberto Martín almost 9 years
    MadProgrammer was right when saying the problem was not with creating new objects, but with the correct content of the objects. JComboBox doesn't care about the addresses of the objects.