我添加和刪除JTabbedPane中的標籤動態。代碼:JTabbedPane - ArrayIndexOutOfBoundsException
//Method which adds new tab
private void addTab(String title, MainPanel panel) {
tabbed.addTab(title, panel);
int index = tabbed.indexOfComponent(panel);
JPanel tabPanel = new JPanel();
tabPanel.setOpaque(false);
tabPanel.add(panel.getLabel());
JButton closeButton = new JButton(new CloseTabAc(index));
tabPanel.add(closeButton);
panel.getLabel().setText(title);
tabbed.setTabComponentAt(index, tabPanel);
tabbed.setSelectedIndex(index);
currentPanel = panel;
}
//Action to close tab
private class CloseTabAc extends AbstractAction {
private int tabNum;
CloseTabAc(int tabNum) {
putValue(Action.NAME, "x");
this.tabNum = tabNum;
}
@Override
public void actionPerformed(ActionEvent ev) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainPanel panel = (MainPanel) tabbed.getComponentAt(tabNum);
tabbed.remove(tabNum);
}
});
}
}
所以這是代碼。當切換,刪除標籤我得到這個錯誤:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at javax.swing.JTabbedPane.getComponentAt(JTabbedPane.java:1224)
at jnotepad.MainFrame$CloseTabAc$1.run(MainFrame.java:247)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
...
我試圖解決它的幾天,但我沒有看到什麼是錯的。唯一我看到這個錯誤發生在當我打開幾個選項卡並隨機關閉它們的情況下。所以例如。我打開3個選項卡:1,2和3.如果按順序關閉它們:3,2,1,我會得到例外,但一切都接近。但是當我嘗試按順序關閉它們時:3,1,2然後3將關閉,但是會拋出1個異常,並且現在或之後都不會關閉。所以請幫我解決我的問題。
編輯:我根據吉恩的解決方案修改了代碼,現在我得到的異常以下:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:371)
at java.util.ArrayList.get(ArrayList.java:384)
at javax.swing.JTabbedPane.getComponentAt(JTabbedPane.java:1224)
at jnotepad.MainFrame$ChangeHandler.stateChanged(MainFrame.java:228)
at javax.swing.JTabbedPane.fireStateChanged(JTabbedPane.java:416)
at javax.swing.JTabbedPane$ModelListener.stateChanged(JTabbedPane.java:270)
...
看起來例外是行228這是我的stateChanged聽衆:
private class ChangeHandler implements ChangeListener {
@Override
public void stateChanged(ChangeEvent ev) {
currentPanel = (MainPanel) tabbed.getComponentAt(tabbed.getSelectedIndex());
}
}
每標籤中有MainPanel實例。當選擇另一個選項卡時,我得到此面板並將其設置爲MainFrame中的currentPanel。這個異常並沒有像以前那樣破壞我的GUI,但是我喜歡去掉它。
感謝它幫助,但現在有另一個例外(看看我的編輯)。什麼會導致它? – user2102972 2013-03-09 15:33:46
看起來像是從您移除的標籤中調用了監聽器,並且尚未選擇任何選項卡。嘗試檢查tabbed.getSelectedIndex()是否返回範圍(> = 0和
2013-03-09 16:53:25