我动态添加和删除JTabbedPane中的标签页。代码:
//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个异常并且它不会立即关闭。所以请帮我解决我的问题。
编辑:我根据Jean的解决方案修改了我的代码,现在我得到了以下异常:
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,但我想摆脱它。
答案 0 :(得分:1)
如果您有三个标签
|标签0 |选项卡1 |标签2 |
如果删除标签1,标签2索引将为1.这就是您获得IndexOutOfBoundsException
的原因。
将对选项卡项的引用(而不是选项卡式窗格上的索引)传递给侦听器。