问题
Rectangle rect1 = new Rectangle(10, 10, 20, 20);
Rectangle rect2 = new Rectangle(60, 10, 20, 20);
EventHandler<MouseEvent> event = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent ae) {
System.out.println("aaa");
}
};
rect1.setOnMouseClicked(event);
rect2.setOnMouseClicked(event);
How to click rect1 print aaa, click rect2 print bbb ?
In my real program, I have hundreds of rectangles, and in the event, I have many things to do. So I don't want declare event for every one.
Thanks!
回答1:
Like so:
Rectangle rect1 = new Rectangle(10, 10, 20, 20);
rect1.setUserData( "aaa" );
Rectangle rect2 = new Rectangle(60, 10, 20, 20);
rect2.setUserData( "bbb" );
EventHandler<MouseEvent> event = new EventHandler<MouseEvent>()
{
@Override
public void handle( final MouseEvent ME )
{
Object obj = ME.getSource(); // you can also try ME.getTarget()
if ( obj instanceof Rectangle )
{
System.out.println( ((Rectangle) obj).getUserData() );
}
}
};
rect1.setOnMouseClicked(event);
rect2.setOnMouseClicked(event);
来源:https://stackoverflow.com/questions/23928132/javafx-eventhandler-pass-parameter