我想在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(我还不了解),那就太好了)
EDIT: 根据@ 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();
}
给一个窗口看起来像:
1 回答
有不同的方法来解决这个问题 .
如果您仍希望从
BorderPane
获得好处(比如有顶部和底部窗格),可以将HBox
/GridPane
设置为中心(不设置左/右) .如果您不关心顶部和底部布局实现,那么正如@ k88建议的那样,您可以直接使用
HBox
或GridPane
作为根节点 .使用
HBox
:使用
GridPane
:Update: 在任何一种情况下,如果您希望按钮自动拉伸,请将按钮的宽度绑定到其布局 . 这样您就可以控制
HBox
中的按钮宽度比例 .Update 2 :请在下面找到示例演示 .