在我的JFX应用程序中,我创建了一个数组列表来跟踪选项卡。我主要是想知道用户关闭了哪些选项卡,以便我处理由于删除特定选项卡而发生的更改。
我试图使用下面的代码从数组列表中删除关闭的选项卡。我使用一种setOnClosed
方法来触发此代码:(String id = closedTab.getId();
此ID是在首次创建标签时分配的,因此它不为null。)
for (Tab aTab : allTabsList) {
if (aTab.getId().equals(id)) {
allTabsList.remove(aTab);
break;
}
}
我在该getId
方法上得到一个空指针异常。不知道为什么。
因此,我尝试执行以下操作:
for (Tab aTab : allTabsList) {
if (aTab.equals(closedTab)) {
allTabsList.remove(closedTab);
if allTabsList.contains(closedTab){
System.out.println("tab is still there");
}
}
}
删除后,我检查了arrayList是否包含此选项卡,并且它的代码没有进入if语句,因此它不应该包含它。但是,数组列表的大小不会改变。
有任何想法吗?
我实际上喜欢一种更好的方法。这里是:
设置是这样的:
我创建了一个“ MyTab”类来包装JavafX Tab对象。我认为包装它可以使我轻松控制嵌入字段。javaFX Tab变量的名称如下:fxTab。
fxTab从单独的FXML文件获取其内容。在下面的代码中,内容/场景的根是“ sceneRoot”。这样,我可以创建多个fxTab(程序中部分功能)。
然后,我为MyTab对象创建了一个ID变量,并将其通过fxTab.serUserData()传递给了fxTab;
然后,我添加一个setOnClosed方法并使用ID来标识哪个fxTab已关闭,然后从arrayList(allMyTabs)中删除其包装。关闭fxTab时,我在我的arrayList中查找所有MyTab对象,并比较userData以确定我需要哪些对象。当然,ID变量总是递增的。因此,不会有具有相似ID的标签。
sceneRoot = (AnchorPane) loader.load();//load the tab scene root from the FXML loader
Tab fxTab = new Tab();
fxTab.setContent(sceneRoot);//add the tab scene root node to the tab
fxTab.setClosable(true);//make the tab closable
fxTab.setId(ID.toString());//set its ID.
//add a close action to the created tab stage
fxTab.setOnClosed(new EventHandler<Event>() {
@Override
public void handle(Event t) {
Tab fxTab = (Tab) t.getSource();//get the source of the action...
for (MyTab myTabObj: allMyTabs) {
if (myTabObj.ID.equals(fxTab.getUserData())) {
fxTab = myTabObj;//f so, this is the one
break;//break the loop
}
}
allMyTabs.remove(myTabObj);
System.out.println("You closed Tab: " + fxTab.getUserData());
System.out.println("Total number of remaining tabs is:" + allMyTabs.size());
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句