Hi,
Not sure if this is a bug or implementation issue.
When trying to use the setSelectedItem(int) method of JComboBox, what's being displayed in the panel is not the same item that is selected when you open the dropdown.
If you run the example code below a few times in a row you'll see that it eventually displays something other than "Item 2". However, if you open the combobox it will always display the correct value. So, just on a whim I surrounded the setSelectedIndex(int) call with the SwingUtilities.invokeLater method and it all started to work. I was able to run it 6 times in a row and always displayed the correct value. Whereas without it usually by the 3rd run, I'd see the issue.
So, my question is - Should I be putting all setSelectedXXX() methods in SwingUtilities.invokeLater methods? We originally found this issue in our JApplets. I made the code below so I could post it, but essentially it's the same thing. We do use Javascript to call back into the JApplet to set the indexes. I'm guessing I DO need to since we're dealing with different Threads and Swing?
Thanks,
- Tim
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author tmulle
*/
public class Test {
public static void main(String[] args) {
// Create the Frame
JFrame f = new JFrame();
final JComboBox combo = new JComboBox();
// Add some items to the combo
for (int x = 0; x < 20; x++) {
combo.addItem("Item " + x);
}
// Create a scrollpane
JScrollPane pane = new JScrollPane(combo);
f.getContentPane().add(pane);
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Tester thread
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// Uncomment this and things seem to work consistently
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// combo.setSelectedIndex(2);
// }
// });
// Comment this out when uncommenting above
// This is supposed to select the 2 index in the list
// However, run running the example multiple times you'll see
// that it sometimes displays something other than the correct
// value. But the correct items is selected in the dropdown
combo.setSelectedIndex(2);
}
});
// Start the thread
t.start();
// Show the frame
f.setVisible(true);
}
}