Java FX设置边距

10
这个简单的例子创建了一个区域,其中有2个用红色标记的矩形区域。我想使用VBox的margin方法将右边的区域向右推n像素,但是没有任何反应。为什么margin在这个例子中不起作用?尽管它在场景构建器中运行良好。
public class LayoutContainerTest extends Application {

    @Override
    public void start(Stage primaryStage) {

        VBox areaLeft = new VBox();
        areaLeft.setStyle("-fx-background-color: red;");
        areaLeft.setPrefSize(100, 200);

        VBox areaMiddle = new VBox();
        areaMiddle.setStyle("-fx-background-color: red;");
        areaMiddle.setPrefSize(100, 200);

        VBox areaRight = new VBox();
        areaRight.setStyle("-fx-background-color: red;");
        areaRight.setPrefSize(100, 200);

        VBox.setMargin(areaRight, new Insets(0,0,0,50));

        HBox root = new HBox(areaLeft,areaMiddle,areaRight);
        root.setSpacing(30);



        Scene scene = new Scene(root, 600, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
1个回答

20

您正在使用 VBox.setMargin(),但应改用 HBox 方法:

HBox.setMargin(areaRight, new Insets(0, 0, 0, 50));

原因是您正在为 VBox 的子级设置边距,而 areaRightHBox 的子级。如果您使用您的代码然后将 areaRight 放入 VBox 中,您将看到预期的边距。

您提到它在 SceneBuilder 中可以工作,但如果您检查实际的 FXML 代码,您会看到 SceneBuilder 正确地使用了 HBox

<VBox fx:id="areaRight" prefHeight="200.0" prefWidth="100.0" style="-fx-background-color: red;">
     <HBox.margin>
        <Insets left="50.0" />
     </HBox.margin>
  </VBox>

2
哇,速度真快!非常感谢。现在完全清楚了。 - Dezzo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接