Java FX设置保证金



这个简单的例子创建了一个区域,其中有两个用红色标记的矩形区域。我想使用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);
}
}

您使用的是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>

最新更新