JavaFX EventHandler pass parameter


Question

    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
3
5/29/2014 7:46:39 AM

Accepted Answer

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);     
3
5/30/2014 3:32:47 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon