Reputation: 1668
I have this basic example of JavaFX tabs with right click menu.
// 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);
I want when I right click with the mouse on the tab name to select option close
. When I select close
I want to remove the selected tab from the tab pane. How I must modify the code to get this functionality.
Upvotes: 2
Views: 889
Reputation: 3855
Try this,
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Close Tab");
tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem());
}
});
Upvotes: 4