JavaFX Button发布了活动

时间:2016-08-12 03:46:31

标签: java javafx

我有一个Button,我想在释放时为其分配不同的操作。我在使用类似的javax.swing.ButtonModel之前在Swing中做了这个:

ChangeListener changeListnerUp = new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent event) {

       AbstractButton button = (AbstractButton) event.getSource();
       ButtonModel model = button.getModel();
       boolean pressed = model.isPressed();

       if (pressed) {
           System.out.println( "Up Button pressed, String: " + upString );
       } else
            System.out.println( "Up Button released, String: " + stopString );
       }
    }

};

任何人都可以在JavaFX中推荐合适的替代方案吗?

2 个答案:

答案 0 :(得分:2)

您可以使用节点类中的一种方法,称为addEventFilters

exampleNode.addEventFilter(MouseEvent.MOUSE_RELEASED,                
new EventHandler<MouseEvent>() {
                    public void handle(MouseEvent) {  
                    //do stuff here
                 };
              });

答案 1 :(得分:2)

您可以捕获多个事件,但在这种情况下,已经存在根据这些事件更改的属性:pressed propertyarmed property,如果离开Button鼠标应该导致事件。只需听取此属性的更改

示例:

只要按下Circle,以下代码就会为Button设置动画:

@Override
public void start(Stage primaryStage) {
    Circle circle = new Circle(300, 20, 5);
    Timeline animation = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(circle.centerYProperty(), circle.getCenterY())),
            new KeyFrame(Duration.seconds(1), new KeyValue(circle.centerYProperty(), 300))
    );
    animation.setCycleCount(Animation.INDEFINITE);
    animation.setAutoReverse(true);

    Button btn = new Button("Play");
    btn.pressedProperty().addListener((observable, wasPressed, pressed) -> {
        System.out.println("changed");
        if (pressed) {
            animation.play();
        } else {
            animation.pause();
        }
    });

    Pane root = new Pane(btn, circle);

    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}