【发布时间】:2019-05-10 22:33:40
【问题描述】:
我想在 JavaFX 中创建一个没有中心窗格的 BorderPane 布局。
目前我写的代码只实现了左右边框,如下:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class GUI_Practice extends Application {
@Override
public void start(Stage stage) throws Exception {
String blackBorder = "-fx-border-style: solid; -fx-border-width: 1; -fx-border-color: black";
/* Left column */
Button save = new Button("Save");
Button del = new Button("Delete");
HBox settings = new HBox(save, del);
VBox leftCol = new VBox(settings);
leftCol.setStyle(blackBorder);
/* Right column */
Button calculate = new Button("Calculate");
Button cancel = new Button("Cancel");
HBox runButtons = new HBox(calculate, cancel);
VBox rightCol = new VBox(runButtons);
rightCol.setStyle(blackBorder);
/* Set up borderpane */
BorderPane root = new BorderPane();
root.setPadding(new Insets(15));
root.setLeft(leftCol);
root.setRight(rightCol);
Scene scene = new Scene(root, 800, 600);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
它给出的输出如下图所示:
但是,我希望它看起来更像这样:
左右列的宽度相等并占据窗口的整个宽度。另外,列的宽度不会随着窗口的变化而变化,所以中间的空白会随着窗口的变大而变大。
我需要更改哪些内容才能使列填充窗口的宽度?
(P.S.我还在学习,所以如果解决方案可以避免FXML(我还不明白),那就太好了)
编辑: 根据@k88 的建议,我的启动方法现在看起来像这样:
public void start(Stage stage) throws Exception {
String blackBorder = "-fx-border-style: solid; -fx-border-width: 1; -fx-border-color: black";
Button calculate = new Button("Calculate");
Button cancel = new Button("Cancel");
HBox runButtons = new HBox(calculate, cancel);
VBox rightCol = new VBox(runButtons);
rightCol.setStyle(blackBorder);
Button save = new Button("Save");
Button del= new Button("Delete");
HBox settings = new HBox(save, load);
VBox leftCol = new VBox(settings);
leftCol.setStyle(blackBorder);
HBox root = new HBox(leftCol, rightCol);
root.setPadding(new Insets(15));
Scene scene = new Scene(root, 800, 600);
stage.setScene(scene);
stage.show();
}
给出一个看起来像这样的窗口:
【问题讨论】:
-
你不能把它放在 HBox 里吗?然后在 HBox 的每个节点中添加一个 BorderPane 或任何你想要的东西?基本上用 HBox 替换 BorderPane,因为我认为 BorderPane 在这里没有任何用处。
-
@k88 90% 的初学者使用
BorderPane却不知道他们为什么使用它。我认为这是因为它是全新安装中的默认Pane(现在不记得了)。 -
@k88 感谢您的建议,但是当我这样做时,它看起来就像我的问题中的屏幕截图,但右列与左列接触,并且它们的右侧都有空格.
-
这是因为您为
Scene定义了固定大小,但您的内容不需要这么多空间 - 所以空间必须放在某个地方。BorderPane将其分配给“中心”节点,该节点无论如何都是空的,而HBox将其分配给右侧。 -
@JolonB 你能做的最好的就是在左右两边平均分配额外的空间。你可以试试
HBox.setAlignment(Pos.CENTER)。
标签: java css javafx borderpane