我無法刪除jcombobox中的第一個元素。我的代碼如下,無法從jcombobox中刪除第一個元素
JComboBox cBox= cBox= new JComboBox();
...
while (cBox.getItemCount() > 0)
cBox.removeItemAt(0);
對於測試運行,我有3個項目在cBox。當它到達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)
如果你把你的實際代碼放在這裏,這將會很有用。這可能是mre說的那種情況,或者是任何其他導致NPE的問題! –
問題出在您未顯示的代碼中,請參閱stacktrace的第一行:'at util.Gui $ 4.actionPerformed(Gui.java:111)' – kleopatra
我必須添加一個空白項目,然後刪除其餘項目。它似乎無法從組合框項目中刪除所有項目。 – mechanicum