这个简单的示例创建了一个带有2个用红色标记的矩形区域的区域。
我想使用VBox
边距方法将正确的区域向右推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);
}
}
答案 0 :(得分:6)
您正在使用VBox.setMargin()
,但应该使用HBox
方法:
HBox.setMargin(areaRight, new Insets(0, 0, 0, 50));
原因是,您正在为VBox
的子代设置边距,而areaRight
是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>