I am intermediate in Java and fairly new to JavaFX. I'm developing an application that makes use of BorderPane in JavaFX 8. I have two buttons at the bottom of the BorderPane.
Bpane.setAlignment(bttmBttn, Pos.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.
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
.
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
You would also have to remove the maxSize
constraint from the buttons by calling :
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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.