如何为多个按钮更改OnMouseReleaseEvent?

时间:2016-10-06 10:54:22

标签: java javafx event-handling

我试图弄清楚如何一次更改多个按钮的OnMouseReleaseEvent。该应用程序是一个屏幕钢琴,我想删除释放事件,以便播放的音符持续,而不是在短暂点击后关闭。

我的代码段适用于一个键:

@FXML
public void changeOnMouseRelease(){
        if (getOriginalEvent() == null) {
            setOriginalEvent(keyC.getOnMouseReleased());
        }
        if (getOriginalEvent() == keyC.getOnMouseReleased()) {
            keyC.setOnMouseReleased(event -> {
                System.out.println("Mouserelease-Event empty \n");
            });
        } else keyC.setOnMouseReleased(getOriginalEvent());
    }
}

这些是原始事件的getter和setter:

private void setOriginalEvent(EventHandler originalEvent){
    this.originalEvent = originalEvent;
}

private EventHandler getOriginalEvent(){
    return this.originalEvent;
}

当我尝试这个时,它不起作用:

@FXML
public void changeOnMouseRelease(){
    for(Button b : pianoKeys) {  // pianoKeys is just an array of the 13 piano buttons
        if (getOriginalEvent() == null) {
            setOriginalEvent(b.getOnMouseReleased());
        }
        if (getOriginalEvent() == b.getOnMouseReleased()) {
            b.setOnMouseReleased(event -> {
                System.out.println("Mouserelease-Event empty \n");
            });
        } else b.setOnMouseReleased(getOriginalEvent());
    }
}

我认为它与getter / setter有关,但我不确定如何正确处理。

1 个答案:

答案 0 :(得分:0)

通过向事件处理程序添加MouseEvent参数,您可以使用此信息来检索已按下的Button。您可以关联允许您选择如何使用Button处理按键操作的信息,例如使用userData

控制器

@FXML
private void onMouseReleased(MouseEvent event){
    Button b = (Button) event.getSource();
    System.out.println("released key "+b.getUserData());
}


@FXML
private void onMousePressed(MouseEvent event){
    Button b = (Button) event.getSource();
    System.out.println("pressed key "+b.getUserData());
}

FXML

...
<Button onMousePressed="#onMousePressed" onMouseReleased="#onMouseReleased" userData="D#" />
...

这消除了循环按钮的需要。