开发者

can't remove first element from jcombobox

I cannot remove the first element from jcombobox. my code is as follows,

JComboBox cBox= cBox= new JComboBox();
...    
while (cBox.getItemCount() > 0)
  cBox.removeItemAt(0);

For a test run, i had 3 items in the cBox. When it gets to removeItemAt(0), the debug goes haywire going in to some File access code which is absolutely not related. Does this twice then gets the below exception. I tried removeAllItems() which directly gets the same exception. However, removeI开发者_如何学Gotem(1) works as it should until theres only 1 element left. The exception doesn't crash the app and i can see no items in the combobox after so it worked a little. What exactly am i doing wrong.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at util.Gui$4.actionPerformed(Gui.java:111)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.AbstractListModel.fireContentsChanged(Unknown Source)
at javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeElementAt(Unknown Source)
at javax.swing.JComboBox.removeItemAt(Unknown Source)
at util.Gui.prepareSubLists(Gui.java:164)
at util.Gui$3.actionPerformed(Gui.java:97)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)


Isn't your conditional statement wrong? Replace while with if, as such

if(cBox.getItemCount() > 0){
  cBox.removeItemAt(0);
}

Here's an SSCCE:

public final class JComboBoxDemo {
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();             
            }
        });
    }

    public static void createAndShowGUI(){
        final JFrame frame = new JFrame("JComboBox Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(JComboPane.newInstance());
        frame.setSize(new Dimension(250, 100)); // for demonstration purposes only
        //frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class JComboPane extends JPanel{
        private JComboPane(){
            super();
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            JCenteredComboBox comboBox = JCenteredComboBox.newInstance();
            JCenteredButton button = JCenteredButton.newInstance(comboBox);
            add(comboBox);
            add(button);
        }

        public static final JComboPane newInstance(){
            return new JComboPane();
        }

        private static final class JCenteredComboBox extends JComboBox{
            private JCenteredComboBox(){
                super(new String[]{"Item 1", "Item 2", "Item 3"});
                setAlignmentX(Component.CENTER_ALIGNMENT);
            }

            public static final JCenteredComboBox newInstance(){
                return new JCenteredComboBox();
            }
        }

        private static final class JCenteredButton extends JButton{
            private JCenteredButton(final JComboBox comboBox){
                super("Remove First Item");
                setAlignmentX(Component.CENTER_ALIGNMENT);
                addActionListener(new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if(comboBox.getItemCount() > 0){
                            comboBox.removeItemAt(0); // your logic
                        }
                    }
                });
            }

            public static final JCenteredButton newInstance(final JComboBox comboBox){
                return new JCenteredButton(comboBox);
            }
        }
    }
}

can't remove first element from jcombobox

When you run this, pressing the JButton will remove the first item in the JComboBox. You can keep pressing this until it is empty.


This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.

For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.

The solution to this is to move the code from actionPerformed to e.g. mouseClicked() or another event handler depending on what you want to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜