我想用ContextMenu实现TabPane以关闭除选定选项卡
之外的其他选项卡public class MainApp extends Application
{
@Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("Tabs");
Group root = new Group();
Scene scene = new Scene(root, 400, 250, Color.WHITE);
final TabPane tabPane = new TabPane();
BorderPane borderPane = new BorderPane();
for (int i = 0; i < 5; i++)
{
Tab tab = new Tab();
tab.setText("Tab" + i);
HBox hbox = new HBox();
hbox.getChildren().add(new Label("Tab" + i));
hbox.setAlignment(Pos.CENTER);
tab.setContent(hbox);
tabPane.getTabs().add(tab);
ContextMenu contextMenu = new ContextMenu();
MenuItem close = new MenuItem();
MenuItem closeOthers = new MenuItem();
MenuItem closeAll = new MenuItem();
close.setText("Close");
closeOthers.setText("Close Others");
closeAll.setText("Close All");
contextMenu.getItems().addAll(close, closeOthers, closeAll);
tab.setContextMenu(contextMenu);
final ObservableList<Tab> tablist = tabPane.getTabs();
close.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem());
}
});
closeOthers.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
tabPane.getTabs().removeAll();
}
});
closeAll.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
tabPane.getTabs().removeAll(tablist);
}
});
}
// bind to take available space
borderPane.prefHeightProperty().bind(scene.heightProperty());
borderPane.prefWidthProperty().bind(scene.widthProperty());
borderPane.setCenter(tabPane);
root.getChildren().add(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
但代码无效。你能帮我实现这个解决方案。
有没有更好的方法来实现这个?
答案 0 :(得分:0)
这很简单。只需遍历选项卡列表中的所有选项卡对象,并标记应删除的选项卡。迭代后,删除标记的Tab-Objects。
closeOthers.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
// ArrayList of Tab-Objects in which we store Tabs which should be deleted..
ArrayList<Tab> markedTabs = new ArrayList<>();
// Iterate through all Tabs in tablist
for (Tab tab : tablist) {
// Is the tab the current active tab? if not, add it to the markedTabs-ArrayList
if (tab != tabPane.getSelectionModel().getSelectedItem())
markedTabs.add(tab);
}
// Remove them from the tabPane..
tabPane.getTabs().removeAll(markedTabs);
}
});