How do I detect/handle a right click in JavaFX?
Asked
Active
Viewed 3.5k times
3 Answers
27
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 ]
}
}

Matthew Hegarty
- 3,791
- 2
- 27
- 42
-
Brilliant! Thats perfect. I couldn't find a thing about it anywhere. Thanks a bunch! – mikewilliamson Oct 06 '09 at 19:36
-
@mikewilliamson can I change the button name for this [button](https://paste.ubuntu.com/25684310/) when mouse right button clicked? – alhelal Oct 06 '17 at 06:21
-
1Is that Kotlin? – Max Jun 01 '18 at 14:38
-
Not Kotlin, it is the original JavaFX script developed by Sun - now long since unsupported. – Matthew Hegarty Jun 02 '18 at 15:14
10
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();
}
}
2
This worked fine for me:
rectangle.setOnMouseClicked(event ->
{
//left click
if (event.isPrimaryButtonDown()) {
}
//right click
if (event.isSecondaryButtonDown()) {
}
});

sstlv_seraph
- 83
- 4