Javafx - 如何为窗格中添加的组件设置拖动范围

时间:2014-09-16 05:08:52

标签: javafx javafx-2

我尝试过以下示例,其中边框窗格的左侧区域将包含组件列表,边框窗格的中心将充当画布区域,这里我在运行时添加了一个矩形作为子窗口的窗格设置为BorderPane的中心部分。但是当拖动矩形时,它会移动到为中心分配的区域之外,所以我怎么能只在中心窗格内部进行拖动。

enter image description here

@Override
public void start(Stage stage) throws Exception {
    stage.setTitle("BPM");
    BorderPane border = new BorderPane();

    Pane canvas = new Pane();
    canvas.setStyle("-fx-background-color: #F0F0F0;");
    border.setLeft(compList());
    border.setCenter(canvas);
    //
    Anchor start = new Anchor(null, "Start", Color.PALEGREEN, new SimpleDoubleProperty(170), new SimpleDoubleProperty(170));

    final Rect rect=new Rect(100, 70,new SimpleDoubleProperty(10), new SimpleDoubleProperty(100));        
    rect.setX(100);
    rect.setY(100);

    canvas.getChildren().add(rect);
    canvas.getChildren().add(start);



    Scene scene = new Scene(border, 800, 600);
    stage.setScene(scene);
    stage.show();

}

1 个答案:

答案 0 :(得分:1)

实际上,默认情况下, Pane 类并不能确保其所有子节点都被剪切,因此子节点可能会超出 Pane 的边界。要确保在指定边界内拖动所有子项(在您的情况下为矩形),您必须在拖动子项时手动检查边界。以下是我的实施示例:

@Override
public void start(Stage stage){
    stage.setTitle("BPM");
    BorderPane mainPanel = new BorderPane();

    VBox nameList = new VBox();
    nameList.getChildren().add(new Label("Data"));
    nameList.setPrefWidth(150);

    Pane canvas = new Pane();
    canvas.setStyle("-fx-background-color: #ffe3c3;");
    canvas.setPrefSize(400,300);

    Circle anchor = new Circle(10);

    double rectWidth = 50, rectHeight = 50;
    Rectangle rect = new Rectangle(50,50);
    rect.setX(100);
    rect.setY(100);

    canvas.getChildren().addAll(rect, anchor);

    // set the clip boundary
    Rectangle bound = new Rectangle(400,300);
    canvas.setClip(bound);

    rect.setOnMouseDragged(event -> {

        Point2D currentPointer = new Point2D(event.getX(), event.getY());

        if(bound.getBoundsInLocal().contains(currentPointer)){

            if(currentPointer.getX() > 0 &&
                    (currentPointer.getX() + rectWidth) < bound.getWidth()){
                rect.setX(currentPointer.getX());
            }
            if(currentPointer.getY() > 0 &&
                    (currentPointer.getY() + rectHeight) < bound.getHeight()){
                rect.setY(currentPointer.getY());
            }
        }
    });

    mainPanel.setLeft(nameList);
    mainPanel.setCenter(canvas);
    Scene scene = new Scene(mainPanel, 800, 600);
    stage.setScene(scene);
    stage.show();
}