【问题标题】:Right click in JavaFX?右键单击JavaFX?
【发布时间】:2009-10-04 03:57:44
【问题描述】:

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

【问题讨论】:

    标签: javafx javafx-1


    【解决方案1】:

    这是一种方法:

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

    【讨论】:

    • 太棒了!那很完美。我在任何地方都找不到关于它的东西。非常感谢!
    • @mikewilliamson 我可以在单击鼠标右键时更改此button 的按钮名称吗?
    • 那是 Kotlin 吗?
    • 不是 Kotlin,它是 Sun 开发的原始 JavaFX 脚本 - 现在早已不受支持。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这对我来说很好用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 2014-07-31
        • 2012-11-06
        • 1970-01-01
        • 2011-01-11
        • 2020-11-21
        相关资源
        最近更新 更多