【发布时间】:2013-05-29 20:06:42
【问题描述】:
我想在 JAVA 中构建一个选项卡式界面,每个选项卡上都有关闭按钮。为此,我使用了以下类:ButtonTabComponent
我的 GUI 上有一个按钮,可以创建一个新选项卡。假设我按了 4 次“新标签”按钮,因此创建了 4 个标签:
|标签 0 |标签 1 |标签 2 |选项卡 3 |(每个选项卡都包含一个关闭按钮)
现在,我决定要关闭选项卡 1,但问题出现了,当我关闭中间选项卡时,所有索引都会重新排序 - 这意味着:
|标签 0 |标签 2 |标签 3 |(标签 2 的索引为 1)
如果我现在尝试创建一个新选项卡,该选项卡已创建但新选项卡:
|标签 0 |标签 2 |标签 3 | tab 1|(tab 1没有关闭按钮)
如果我再次点击新标签,我会得到:
|标签 0 |标签 2 |标签 3 |标签 1 | tab 4 |(tab 4很好,它有一个关闭按钮)
现在我决定关闭标签 2,然后我得到:
|标签 0 |标签 3 |标签 1|选项卡 4|(选项卡 3 现在将具有索引 1)
如果我创建一个新标签:
|标签 0 |标签 3 |标签 1|选项卡 4|选项卡 1 |(最后一个选项卡也没有关闭按钮)。
我相信这是由索引引起的,我在 stackoverflow 上读到了一个类似的问题:stackoverflow.com/questions/15312252/jtabbedpane-arrayindexoutofboundsexception,一个可能的解决方案是:
将选项卡项的引用而不是其在选项卡式窗格中的索引传递给侦听器。
我不知道该怎么做。如果有人有任何提示,我会非常非常感激。 我需要为每个选项卡保留可靠的参考,因为每个选项卡都会打开一个文件,并且可以保存到文件中,显然选项卡索引不可靠。
编辑:我在代码中添加新标签的方式是:
...//main class
private final JTabbedPane pane = new JTabbedPane();
//I am using an array to store the tabs created
//I initialize the array with false. the idea was that when a new tab get created, one item in the array
//gets the true value. when the tab is closed, the array item (based on the index) is set back to false
arrTabList = new boolean[10];
for(int i=0; i<10; i++){
arrTabList[i] = false;
}
...
public void newFile() //this function opens a new tab
{
//parse the array to check the first item with false status
for(int i=0; i<10; i++){
if(!arrTabList[i]) {
System.out.println("false");
PanelCounter = i;
break;
}
}
newTab t = new newTab(); //object which contains the tab content (a bunch of graphical components, input fields mostly)
pane.add("New Entry" + PanelCounter, t.createContentPane()); //adds the new tab to the main window
pane.setTabComponentAt(PanelCounter, new ButtonTabComponent(pane, this));
arrTabList[PanelCounter] = true; //sets the item array to true
}
//when a tab is closed, this function is called in the listener:
public void decreaseCounter(int i)
{
arrTabList[i] = false; //sets the item array back to false
}
【问题讨论】:
-
引用的建议在这里不适用,
ButtonTabComponent不会在内部存储标签索引,而是按需查找。我怀疑错误可能是由于您添加新标签的方式造成的;你能展示一下代码吗? -
添加了代码。感谢您的意见
标签: java swing jtabbedpane