javafx 面板空白处右键菜单



import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Test1 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Right Click Menu Example");

        // 创建根容器
        Pane root = new Pane();

        // 创建场景
        Scene scene = new Scene(root, 300, 200);

        // 创建右键菜单
        ContextMenu contextMenu = new ContextMenu();

        // 创建菜单项
        MenuItem menuItem1 = new MenuItem("Option 1");
        MenuItem menuItem2 = new MenuItem("Option 2");

        // 设置点击事件监听器
        menuItem1.setOnAction(event -> System.out.println("Option 1 selected."));
        menuItem2.setOnAction(event -> System.out.println("Option 2 selected."));

        // 将菜单项添加到右键菜单
        contextMenu.getItems().addAll(menuItem1, menuItem2);

        // 监听场景上的鼠标右键点击事件
        scene.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, event -> {
            if (event.getButton() == javafx.scene.input.MouseButton.SECONDARY) {
                contextMenu.show(root, event.getScreenX(), event.getScreenY());
            } else if (event.getButton() == MouseButton.PRIMARY) {
                contextMenu.hide();
            }
        });

        // 设置舞台的场景
        primaryStage.setScene(scene);

        // 显示舞台
        primaryStage.show();
    }
}

你可能感兴趣的:(服务器,运维)