Search code examples
javafxmouseeventeventhandlerminesweeper

javafx Minesweeper: how to tell between right and left mouse button input


I am working on a javafx Minesweeper game, and currently am only using left mouse button input. I would like to use the right mouse button also so users can flag possible bombs. I looked at the Oracle webpage for Button class, and it says:

"When a button is pressed and released a ActionEvent is sent. Your application can perform some action based on this event by implementing an EventHandler to process the ActionEvent. Buttons can also respond to mouse events by implementing an EventHandler to process the MouseEvent."

https://docs.oracle.com/javafx/2/api/javafx/scene/control/Button.html

Ive tried this several different ways, with no success.

Included is my current EventHandler code. If anyone can explain the best way to handle right/left mouse clicks, or point me in the right direction of where to find that information, it is greatly appreciated.

MineButton is a custom class that extends Button. I would like on right click to mark as "m" and change cell color, and left click would remain the same.

    for (int row = 0; row < 8; row++){
        for (int col = 0; col <8; col++){

            MineButton button = new MineButton(row, col);
            button.setPrefSize(100, 100);
            button.setText("?");
            button.setStyle("-fx-font: 22 arial; -fx-base:#dcdcdc;");
            button.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {

                    if ( button.isAMine() == true){
                        button.setText("B");

                        for( int row1 = 0; row1 < 8; row1++){
                            for ( int col1 = 0; col1 < 8; col1++){

                            if (mineButtons[row1][col1].isAMine() == true){
                                    mineButtons[row1][col1].setText("B");
                                    mineButtons[row1][col1].setStyle("-fx-   font: 22 arial; -fx-base: #dc143c;");
                                }
                            }
                        }
                    }
                    else{

                        recursion(mineButtons, button.getX(), button.getY());

                    }       
                }   
            }); 

Solution

  • If u wanna handle the MouseEvent use this code. It will work.

    button.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if(event.getButton() == MouseButton.SECONDARY){
    //                  Type code to set flag here
                    }
                }
            });