ContextMenu is helpful, when you right click on the content area and you would like to see a pop up menu.
Example
ContextMenu contextMenu = new ContextMenu();
How to add MenuItems to ContextMenu?
Use getItems() method.
MenuItem red = new MenuItem("Red");
MenuItem green = new MenuItem("Green");
contextMenu.getItems().addAll(green, red);
How to display context menu?
Use ‘setOnContextMenuRequested’ method on any node to display context menu on mouse right click.
circle.setOnContextMenuRequested(event -> {
contextMenu.show(circle, event.getScreenX(), event.getScreenY());
});
Find the below working application.
ContextMenuDemo.java
package com.sample.app.widgets;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ContextMenuDemo extends Application {
@Override
public void start(Stage stage) {
ContextMenu contextMenu = new ContextMenu();
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetX(5);
dropShadow.setOffsetY(5);
dropShadow.setColor(Color.GRAY);
Circle circle = new Circle();
circle.setRadius(120);
circle.setFill(Color.AQUA);
circle.setEffect(dropShadow);
circle.setOnContextMenuRequested(event -> {
contextMenu.show(circle, event.getScreenX(), event.getScreenY());
});
VBox vBox = new VBox();
vBox.setPadding(new Insets(80, 0, 0, 140));
vBox.setSpacing(5);
vBox.setStyle("-fx-background-color:white");
vBox.getChildren().addAll(circle);
MenuItem red = new MenuItem("Red");
red.setOnAction(event -> {
circle.setFill(Color.RED);
});
MenuItem green = new MenuItem("Green");
green.setOnAction(event -> {
circle.setFill(Color.GREEN);
});
contextMenu.getItems().addAll(green, red);
Scene scene = new Scene(vBox, 600, 400);
stage.setTitle("ContextMenu Demo");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Output
Right click on circle, you will see a context menu.
Click on color of your choice, you will observe that the same color is filled by circle. For example, I selected menu item ‘Red’ circle is filled with red color.
Previous Next Home
No comments:
Post a Comment