首页 文章

在JavaFX中为草绘程序创建一个可拖动的选择框

提问于
浏览
0

我正在尝试为JavaFX中的草绘程序创建一个可拖动的选择框,如下所示:
Selection box from Paint

我只是不确定该怎么做 . 我最初想要这样做:在按下鼠标时捕获鼠标坐标,并在拖动结束时再次执行,然后计算高度和宽度,并使用带有黑色边框的透明按钮来显示这些属性 .

但是,我意识到当我这样做时,除非你绘制和删除很多按钮,否则在缩放平面时不可能看到按钮 .

所以,我想知道是否有更好的方法来做这样的事情,或者我的推理是否正确?谢谢

1 回答

  • 2

    我会使用 Rectangle 而不是 Button . 只需执行您描述的操作,但在鼠标拖动时更新矩形的大小(和位置),而不是仅在释放鼠标时添加它 .

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class SelectionRectangle extends Application {
    
        private double mouseDownX ;
        private double mouseDownY ;
    
        @Override
        public void start(Stage primaryStage) {
            Rectangle selectionRectangle = new Rectangle();
            selectionRectangle.setStroke(Color.BLACK);
            selectionRectangle.setFill(Color.TRANSPARENT);
            selectionRectangle.getStrokeDashArray().addAll(5.0, 5.0);
    
            Pane pane = new Pane();
            pane.setMinSize(600, 600);
    
            pane.getChildren().add(selectionRectangle);
    
            pane.setOnMousePressed(e -> {
                mouseDownX = e.getX();
                mouseDownY = e.getY();
                selectionRectangle.setX(mouseDownX);
                selectionRectangle.setY(mouseDownY);
                selectionRectangle.setWidth(0);
                selectionRectangle.setHeight(0);
            });
    
            pane.setOnMouseDragged(e -> {
                selectionRectangle.setX(Math.min(e.getX(), mouseDownX));
                selectionRectangle.setWidth(Math.abs(e.getX() - mouseDownX));
                selectionRectangle.setY(Math.min(e.getY(), mouseDownY));
                selectionRectangle.setHeight(Math.abs(e.getY() - mouseDownY));
            });
    
            primaryStage.setScene(new Scene(pane));
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    您可以根据需要通过查看矩形的 xywidthheight 属性,使用鼠标释放处理程序来确定所选内容 .

相关问题