右键单击JavaFX?

时间:2009-10-04 03:57:45

标签: javafx javafx-1

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

3 个答案:

答案 0 :(得分:22)

这是一种方式:

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 ]
    }
}

答案 1 :(得分:2)

这对我来说很好:

rectangle.setOnMouseClicked(event ->
    {
//left click
        if (event.isPrimaryButtonDown()) {
              
        }
//right click
        if (event.isSecondaryButtonDown()) {
              
        }
});

答案 2 :(得分:1)

如果您想在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();
}