0

I'm trying to call ports.removeAllItems(); with ports being a JComboBox, I am getting this error

Exception in thread "Thread-3" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1
at java.util.BitSet.get(BitSet.java:623)
at javax.swing.DefaultListSelectionModel.clear(DefaultListSelectionModel.java:278)
at javax.swing.DefaultListSelectionModel.setState(DefaultListSelectionModel.java:584)
at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:652)
at javax.swing.plaf.basic.BasicListUI$Handler.intervalRemoved(BasicListUI.java:2601)
at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:179)
at javax.swing.DefaultComboBoxModel.removeAllElements(DefaultComboBoxModel.java:174)
at javax.swing.JComboBox.removeAllItems(JComboBox.java:771)
at view.MainFrame.lambda$startPortsUpdate$3(MainFrame.java:188)
at java.lang.Thread.run(Thread.java:745)

This error happens inside a function where I periodically update the contents of the JComboBox.

private void startPortsUpdate() {
    Thread t = new Thread(() -> {
        while (currentCard.equals(IView.PORT)) { // while we're in port-selection screen
            try {
                Thread.sleep(500);
                ports.removeAllItems();
                for (Object o : getSerialPorts()) {
                    ports.addItem(o);
                }
                ports.revalidate();
            } catch (InterruptedException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    t.start();
}

I find it kind of hard to reproduce and don't really know what to do about it. It's not a big issue at the moment, but if someone has an idea what is causing this, I would be grateful. Also, if you have any suggestions for updating my JComboBox in a better fashion, feel free to suggest something.

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • 2
    For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Jan 11 '17 at 16:01
  • You are modifying a Swing component on an own thread. Swing components may **only** be modified on the Event Dispatch Thread (EDT). Put all the lines `ports.removeAllItems() ... ports.revalidate()` into an own method (but NOT the `sleep` call!). Then, put the execution of this method on the EDT, with `SwingUtilities.invokeLater(() -> yourNewMethodThatModifiesTheComboBox());`. But **note** that there *might* be additional threading issues. You did not provide enough code. – Marco13 Jan 11 '17 at 16:55

0 Answers0