21

如何检测/处理 JavaFX 中的右键单击?

4

3 回答 3

26

这是一种方法:

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.input.*;

var r = Rectangle {
    x: 50, y: 50
    width: 120, height: 120
    fill: Color.RED
    onMouseClicked: function(e:MouseEvent):Void {
        if (e.button == MouseButton.SECONDARY) {
            println("Right button clicked");
        }
    }
}

Stage {
    title : "ClickTest"
    scene: Scene {
        width: 200
        height: 200
        content: [ r ]
    }
}
于 2009-10-05T16:03:07.037 回答
10

如果您想知道如何在 JavaFX 中处理右键单击事件,并且发现 2009 年的答案现在有些过时了......这是 java 11 (openjfx) 中的一个工作示例:

public class RightClickApplication extends Application
{

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        primaryStage.setTitle("Example");
        Rectangle rectangle = new Rectangle(100, 100);
        BorderPane pane = new BorderPane();
        pane.getChildren().add(rectangle);

        rectangle.setOnMouseClicked(event ->
        {
            if (event.getButton() == MouseButton.PRIMARY)
            {
                rectangle.setFill(Color.GREEN);
            } else if (event.getButton() == MouseButton.SECONDARY)
            {
                rectangle.setFill(Color.RED);
            }
        });
        primaryStage.setScene(new Scene(pane, 200, 200));
        primaryStage.show();
    }
}
于 2019-05-27T14:58:35.343 回答
2

这对我来说很好:

rectangle.setOnMouseClicked(event ->
    {
//left click
        if (event.isPrimaryButtonDown()) {
              
        }
//right click
        if (event.isSecondaryButtonDown()) {
              
        }
});
于 2020-12-29T13:40:26.173 回答