无法从 jcombobox 中删除第一个元素

发布于 2024-11-30 22:45:34 字数 2478 浏览 6 评论 0原文

我无法从 jcombobox 中删除第一个元素。我的代码如下,

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

为了测试运行,我在 cBox 中有 3 个项目。当到达removeItemAt(0)时,调试变得混乱,进入一些完全不相关的文件访问代码。执行此操作两次然后得到以下异常。我尝试了removeAllItems(),它直接得到相同的异常。然而,removeItem(1) 会正常工作,直到只剩下 1 个元素。该异常不会使应用程序崩溃,并且我在组合框中看不到任何项目,因此它工作了一点。我到底做错了什么。

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)

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, removeItem(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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我要还你自由 2024-12-07 22:45:34

你的条件语句是不是错了?将 while 替换为 if,如下所示:

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

这是一个 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);
            }
        }
    }
}

在此处输入图像描述

当您运行此命令时,按 JButton 将删除这JComboBox。您可以一直按此按钮,直到它为空。

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

enter image description here

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

神也荒唐 2024-12-07 22:45:34

可能会发生此异常,因为删除组合项时会触发事件,并且在此事件处理方法中您仍然引用组合框项。

例如,当您使用combo.removeItemAt(0)或removeAllItems()在代码中的某个位置(除了actionPeformed()之外)删除组合框中的最后一个项目时,仍然会触发/执行事件actionPerformed。但通常情况下,actionPerformed() 方法包含对用户操作(用户单击组合框上的某处)做出反应的代码。因此,当最后一个项目被删除时,组合框中不再有项目,并且对 actionPerformed() 中的项目或索引的任何引用都将导致异常。

解决方案是将代码从 actionPerformed 移动到 mouseClicked() 或其他事件处理程序,具体取决于您想要执行的操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文