JavaFX构建一个新的事件链

时间:2015-12-10 20:53:14

标签: java javafx mouseevent

我正在制作跳棋游戏。 3个主要组件是Board类,BoardPiece和GamePiece。所有GamePiece对象对鼠标来说都是不可见的。当单击板块时,执行检查以查看BoardPiece上当前是否存在GamePiece。因此,一旦单击BoardPiece并找到一块,则该块需要处理该事件(用于拖放)。以下是BoardPiece课程的摘录:

setOnMousePressed(e -> {
    if (e.getTarget() instanceof BoardPiece) {
        BoardPiece bp = (BoardPiece)e.getTarget();
        GamePiece p = bp.getPiece();
        if (p != null) {
            p.fireEvent(e);
        }
    }
});
setOnMouseDragged(e -> {
    if (e.getTarget() instanceof BoardPiece) {
        BoardPiece bp = (BoardPiece)e.getTarget();
        GamePiece p = bp.getPiece();
        if (p != null) {
            p.fireEvent(e);
        }
    }
});
setOnMouseReleased(e -> {
    if (e.getTarget() instanceof BoardPiece) {
        BoardPiece bp = (BoardPiece)e.getTarget();
        GamePiece p = bp.getPiece();
        if (p != null) {
            p.fireEvent(e);
        }
    }
});

如您所见,我必须手动告诉该部分处理每个事件,而不是整个事件链。我相对较新的JavaFX和Java,所以我主要关注学习最有效的做事方式。

1 个答案:

答案 0 :(得分:0)

您必须单独设置所有事件处理程序,但由于每个处理程序具有相同的功能,您可以简化:

EventHandler<? super MouseEvent> mouseEventHanlder = e -> {
    if (e.getTarget() instanceof BoardPiece) {
        BoardPiece bp = (BoardPiece)e.getTarget();
        GamePiece p = bp.getPiece();
        if (p != null) {
            p.fireEvent(e);
        }
    }
};
setOnMousePressed(mouseEventHanlder);
setOnMouseDragged(mouseEventHanlder);
setOnMouseReleased(mouseEventHanlder);