Skip to content
Advertisement

I have an array of Circle objects and I need to fill a circle if it is clicked. How do I write the event handling for this?

//making the circles clickable
   circle[i].setOnMouseClicked(new EventHandler<MouseEvent>() { 
       @Override 
       public void handle(MouseEvent e) { 
          
           
         circle[i].setFill(Color.BLUE);
          
       } 
    });  

Is there any way to change the element at i without getting a “Local variable i defined in an enclosing scope must be final or effectively final” error?

Advertisement

Answer

If you look at the docs for MouseEvent, you will see that it has a source field that it inherits from EventObject:

The object on which the Event initially occurred.

So you can use this directly like so:

   circle[i].setOnMouseClicked(new EventHandler<MouseEvent>() { 
       @Override 
       public void handle(MouseEvent e) { 
         ((Button)e.source).setFill(Color.BLUE);
       } 
    });  

One point of advice: setOnMouseClicked() is a very low level event. Java provides other higher level events such as ActionListener. Using it is very similar. You can use this with circle[i].setActionListener() and override the actionPerformed() method. I suggest you read more about different listeners that are available so that you know which one to choose for a particular event.

Note: all links are for Java 7 documentation. Be sure to check the documentation for the version of Java which you are using.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement