Java FX设置保证金

Dez*_*zzo 3 layout javafx margin hbox vbox

这个简单的示例创建了一个区域,其中包含2个标记为红色的矩形区域。我想使用VBoxmargin方法将正确的区域向右推n个像素,但是什么也没有发生。为什么在这个例子中保证金不起作用?它可以在场景生成器中工作。

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Zep*_*hyr 8

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

HBox.setMargin(areaRight, new Insets(0, 0, 0, 50));
Run Code Online (Sandbox Code Playgroud)

原因是,您正在为a 的子项设置边距VBox,而areaRight为a的子项设置边距HBox。如果要使用代码,然后将其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>
Run Code Online (Sandbox Code Playgroud)

  • 哇,太快了!十分感谢。现在完全清楚了。 (2认同)