JavaFX EventHandler传递参数

时间:2014-05-29 07:33:04

标签: java javafx eventhandler

    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);

如何点击rect1打印aaa,点击rect2打印bbb?

在我的真实节目中,我有数百个矩形,在这种情况下,我有很多事情要做。所以我不想为每一个声明事件。

谢谢!

1 个答案:

答案 0 :(得分:3)

像这样:

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);