javaFX,一次两个mouseEvents

时间:2016-03-24 16:19:17

标签: javafx mouseevent

我正在尝试在程序中编写一个窗口,用于使用鼠标绘制线条。到目前为止,我已经找到了这个解决方案:

public class TrackEditor extends Stage
{
    TrackDescription editedTrackDescription;
    double startX, startY;
    LineTo line;
    MoveTo move;
    boolean pressed;

    public TrackEditor()
    {
        Path path = new Path();
        this.setTitle("New Game");
        this.setResizable(false);   

        StackPane stackPane = new StackPane();
        SquareGrid squareGrid = new SquareGrid();
        Pane drawingPane = new Pane();
        Pane activePane = new Pane();
        stackPane.getChildren().addAll(squareGrid,drawingPane, activePane);        
        drawingPane.getChildren().add(path);
        activePane.setOnMousePressed((MouseEvent me) -> {
            pressed = true;
            startX = me.getX();
            startY = me.getY();
            move = new MoveTo(me.getX(), me.getY());            
            path.getElements().add(move);
        });
        activePane.setOnMouseReleased((MouseEvent me) -> {
            pressed = false;
            line = new LineTo(me.getX(), me.getY());           
            path.getElements().add(line);
        });
        activePane.setOnMouseMoved((MouseEvent me) -> {
            if(pressed)
            {
                activePane.getChildren().clear();
                Line temporaryLine = new Line(startX, startY, me.getX(), me.getY());
                activePane.getChildren().add(temporaryLine);
            }
        });       


        Scene scene = new Scene(stackPane);


        this.setScene(scene);
        this.initModality(Modality.APPLICATION_MODAL);       
        this.sizeToScene();
        this.show();
    }    
}

但是,正如我所观察到的,按下鼠标按钮时不会绘制临时线。事件MousePressedMouse Released之间是否存在某种冲突,或者其他地方存在问题?

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试检测拖动鼠标的时间(即按下按钮时移动鼠标的时间)。您不需要自己跟踪pressed标志,基础事件系统将为您执行此操作。

activePane.setOnMousePressed((MouseEvent me) -> {
    startX = me.getX();
    startY = me.getY();
    move = new MoveTo(me.getX(), me.getY());            
    path.getElements().add(move);
});
activePane.setOnMouseReleased((MouseEvent me) -> {
    line = new LineTo(me.getX(), me.getY());           
    path.getElements().add(line);
});
activePane.setOnMouseDragged((MouseEvent me) -> {
    activePane.getChildren().clear();
    Line temporaryLine = new Line(startX, startY, me.getX(), me.getY());
    activePane.getChildren().add(temporaryLine);
});