JavaFX EventHandler pass parameter

喜夏-厌秋 提交于 2019-12-06 07:03:21

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!