Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right click in JavaFX?

Tags:

How do I detect/handle a right click in JavaFX?

like image 251
mikewilliamson Avatar asked Oct 04 '09 03:10

mikewilliamson


3 Answers

Here's one way:

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 ]     } } 
like image 77
Matthew Hegarty Avatar answered Oct 19 '22 06:10

Matthew Hegarty


If you are wondering about handling right-click events in JavaFX, and find the 2009 answer is somewhat outdated by now... Here is a working example in 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();     } } 
like image 41
Paul S Avatar answered Oct 19 '22 06:10

Paul S


This worked fine for me:

rectangle.setOnMouseClicked(event ->
    {
//left click
        if (event.isPrimaryButtonDown()) {
              
        }
//right click
        if (event.isSecondaryButtonDown()) {
              
        }
});
like image 24
sstlv_seraph Avatar answered Oct 19 '22 06:10

sstlv_seraph