How do I detect/handle a right click in JavaFX?
Right click in JavaFX?
36.2k Views Asked by mikewilliamson At
3
There are 3 best solutions below
0

This worked fine for me:
rectangle.setOnMouseClicked(event ->
{
//left click
if (event.isPrimaryButtonDown()) {
}
//right click
if (event.isSecondaryButtonDown()) {
}
});
0

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();
}
}
Here's one way: