[英]How to automatically resize buttons on BorderPane as the window is resized?
I am intermediate in Java and fairly new to JavaFX. 我是Java的中级专家,对JavaFX还是相当陌生。 I'm developing an application that makes use of BorderPane in JavaFX 8. I have two buttons at the bottom of the BorderPane.
我正在开发一个使用JavaFX 8中的BorderPane的应用程序。我在BorderPane的底部有两个按钮。
Bpane.setAlignment(bttmBttn, Pos.BOTTOM_CENTER)
Bpane.setAlignment(bttmBttn,位置:BOTTOM_CENTER)
but didn't work. 但是没有用 I want them an the center at all times.
我一直希望他们成为中心。 It looks like this :
看起来像这样:
To align the buttons at the center of the bottom section of the BorderPane, an easy and convenient way to do it is to use a HBox as the parent containers of the two buttons. 要将按钮对准BorderPane底部的中心,一种简单方便的方法是将HBox用作两个按钮的父容器。
HBox box = new HBox(10, button1, button2); // 10 is spacing
box.setAlignment(Pos.CENTER);
borderPane.setBottom(box);
Since, you want the buttons to expand when you expand the screen, you can make the HGROW for these buttons to Priority.ALWAYS
. 由于您希望在扩展屏幕时扩展按钮,因此可以将这些按钮的HGROW设置为
Priority.ALWAYS
。
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
You would also have to remove the maxSize
constraint from the buttons by calling : 您还必须通过调用以下命令从按钮中删除
maxSize
约束:
button1.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button2.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
There is one small issue with this approach. 这种方法存在一个小问题。 The buttons will capture the whole available area and we do not want that.
这些按钮将捕获整个可用区域,我们不希望如此。 An easy way to get rid of it is to add two fixed length, transparent rectangles at the beginning and end of the HBox.
摆脱它的一种简单方法是在HBox的开头和结尾添加两个固定长度的透明矩形。
MCVE MCVE
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
button1.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button2.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
Rectangle rect1 = new Rectangle(60, 20);
rect1.setFill(Color.TRANSPARENT);
Rectangle rect2 = new Rectangle(60, 20);
rect2.setFill(Color.TRANSPARENT);
HBox box = new HBox(10, rect1, button1, button2, rect2);
box.setAlignment(Pos.CENTER);
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
BorderPane root = new BorderPane();
root.setBottom(box);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Main Stage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.