我有一个带有右键菜单的JavaFX标签的基本示例。
// Right-click mouse button menu
final ContextMenu contextMenu = new ContextMenu();
MenuItem item2 = new MenuItem("Close Tab");
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Close Tab");
}
});
contextMenu.getItems().addAll(item2);
// Tabs
VBox stackedTitledPanes = createStackedTitledPanes();
ScrollPane scroll = makeScrollable(stackedTitledPanes);
TabPane tabPane = new TabPane();
BorderPane mainPane = new BorderPane();
// Create Tabs
Tab tabA = new Tab();
tabA.setText("Main Component");
tabA.setClosable(false);
tabA.setContextMenu(contextMenu); // Right-click mouse button menu
// Add something in Tab
StackPane tabA_stack = new StackPane();
tabA_stack.setAlignment(Pos.CENTER);
tabA_stack.getChildren().add(new Label("Label@Tab A"));
tabA.setContent(tabA_stack);
tabPane.getTabs().add(tabA);
Tab tabB = new Tab();
tabB.setText("Second Component");
tabB.setClosable(false);
// Add something in Tab
StackPane tabB_stack = new StackPane();
tabB_stack.setAlignment(Pos.CENTER);
tabB_stack.getChildren().add(new Label("Label@Tab B"));
tabB.setContent(tabB_stack);
tabPane.getTabs().add(tabB);
Tab tabC = new Tab();
tabC.setText("Last Component");
tabC.setClosable(false);
// Add something in Tab
StackPane tabC_vBox = new StackPane();
tabC_vBox.setAlignment(Pos.CENTER);
tabC_vBox.getChildren().add(new Label("Label@Tab C"));
tabC.setContent(tabC_vBox);
tabPane.getTabs().add(tabC);
mainPane.setRight(tabPane);
mainPane.setPrefSize(300, 500);
mainPane.setLayoutY(32);
scroll.setPrefSize(395, 580);
我希望当我在选项卡名称上单击鼠标右键选择选项close
时。当我选择close
时,我想从选项卡窗格中删除选定的选项卡。我必须如何修改代码才能获得此功能。
答案 0 :(得分:4)
试试这个,
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Close Tab");
tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem());
}
});