Reputation: 141
I want to make a program in JavaFX that contains a button which, when clicked, a circle gets created and added to an ArrayList of shapes. The following is my code:
createCircleBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Circle circle1 = new Circle();
shapes.add(circle1);
circle1.setCenterX(event.getX());
circle1.setCenterY(event.getY());
circle1.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// doesn't work because "circle1" must be declared final (constant)
circle1.setCenterX(event.getX());
// "this" doesn't refer to "circle1"
this.setCenterY(event.getY());
}
});
mainPane.getChildren().add(circle1);
}
});
My question is - How can I access "circle1" from inside handle method?
In JavaScript we use e.currentTarget
.
I'm unable to declare "circle1" final because I will need to change it afterwards.
Upvotes: 1
Views: 3958
Reputation: 49215
Use event.getSource(), by this can write a common event handler for multiple cicrles without worrying which exact one was clicked:
EventHandler<MouseEvent> handler = new EventHandler<>()
{
@Override
public void handle( MouseEvent event )
{
if (event.getSource() instanceof Circle) { // to be on safe side, you may
// remove this if-statement
// if you are sure
Circle c = (Circle) event.getSource();
c.setCenterX( event.getX() );
}
}
};
// use it on multiple circles
circle1.setOnMouseDragged(handler);
circle2.setOnMouseDragged(handler);
...
circleN.setOnMouseDragged(handler);
Upvotes: 0
Reputation: 209714
Nowhere in the code you show do you reassign circle1
, so you can just declare it as final
:
createCircleBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
final Circle circle1 = new Circle();
shapes.add(circle1);
circle1.setCenterX(event.getX());
circle1.setCenterY(event.getY());
circle1.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
circle1.setCenterX(event.getX());
}
});
mainPane.getChildren().add(circle1);
}
});
Note that in Java 8 your code would compile just as you have it, because circle1
is effectively final (meaning that it is only assigned once and is never reassigned).
Upvotes: 2