Bozo Wahlrus III
Bozo Wahlrus III

Reputation: 49

Event Handler act on Event source

So I am trying to get a grid of buttons from an array

Button[][] btn=new Button[10][10];  

and I have the code to display them working properly. Now I am trying to add an event listener where if the user clicks a button, it changes its text to "clicked". I have looked around on other questions and the Oracle Docs and I've used getSource() to get the source of the button when clicked, so it gives something like Button@280448f1[styleClass=button]'1, 5'. Is there an efficient way to use this and act on this specific button? Am I going about this the right way or is there something else I should be doing? Here is the part of my code. Right now there is an error at the first event handler and the IDE says it is "Not a statement".

for(int i=0;i<btn.length;i++){
        for(int j=0;j<btn[i].length;j++){
            btn[i][j] = new Button(); //Create new button
            btn[i][j].setMinSize(60,60); //Set size
            btn[i][j].setText(i+", "+j); //Set coordinates as text
            btn[i][j].setBackground(background); //Set image
            GridPane.setColumnIndex(btn[i][j],i); //Set x
            GridPane.setRowIndex(btn[i][j],j); //Set y
            root.getChildren().addAll(btn[i][j]); //Add to gridpane

            btn[i][j].setOnAction(new EventHandler<ActionEvent>() {
                //Click Handler
            @Override
            public void handle(ActionEvent event) {
                (Button)(event.getSource()).setText("Cliked");
            }
            });


            btn[i][j].setOnMouseEntered(new EventHandler<MouseEvent>() {
                //Mouse enter area Handler
            @Override
               public void handle(MouseEvent t) {
               System.out.println(t.getSource());
               }
            });

        }


    }

Upvotes: 2

Views: 244

Answers (1)

Keyur Bhanderi
Keyur Bhanderi

Reputation: 1544

You are incorrectly casting the event source type to Button. As it is now you are attempting to cast the result of setText method

Just replace this line:

(Button)(event.getSource()).setText("Cliked");

To this:

((Button) event.getSource()).setText("Cliked");

Upvotes: 2

Related Questions