Monday, February 2, 2015

JavaFX detect right click on mouse

JavaFX example to detect right click on mouse, by setOnMouseClicked(new EventHandler<MouseEvent>(){...}).


package javafxmouseclick;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXMouseClick extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Label label = new Label();
        Button btn = new Button();
        btn.setText("Click ME");
        btn.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                MouseButton button = event.getButton();
                if(button==MouseButton.PRIMARY){
                    label.setText("PRIMARY button clicked on button");
                }else if(button==MouseButton.SECONDARY){
                    label.setText("SECONDARY button clicked on button");
                }else if(button==MouseButton.MIDDLE){
                    label.setText("MIDDLE button clicked on button");
                }
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(btn, label);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        root.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                MouseButton button = event.getButton();
                if(button==MouseButton.PRIMARY){
                    label.setText("PRIMARY button clicked");
                }else if(button==MouseButton.SECONDARY){
                    label.setText("SECONDARY button clicked");
                }else if(button==MouseButton.MIDDLE){
                    label.setText("MIDDLE button clicked");
                }
            }
        });
        
        Scene scene = new Scene(root, 400, 300);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
}

No comments:

Post a Comment