0

In JavaFX, is there a way to "autofit" elements on a page so they take up the entire thing?

Currently, I'm trying to make the window have two buttons that together take up the entire canvas, but I am not sure how to do that, given that it is possible to stretch the window, etc. I've tried playing around with Button.setPrefSize, but the button size stays the same, it just shows you a window with two outsized buttons, the text of which is not visible.

What I currently have

What I currently have

What I want (but for any window size)

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ryan Fu
  • 349
  • 1
  • 5
  • 22
  • Currently I'm using Flowpane, but if there's a better way to do this, that's fine too. – Ryan Fu Dec 24 '21 at 18:22
  • 1
    `button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE)`. Study: [tips for sizing and slinging nodes](https://docs.oracle.com/javase/8/javafx/layout-tutorial/size_align.htm#JFXLY133) and the other info on layout panes in that tutorial. – jewelsea Dec 24 '21 at 18:55
  • 1
    Edit the question to add additional info instead of writing comments. Provide your code as a [mcve]. – jewelsea Dec 24 '21 at 18:56
  • Related: [JavaFX buttons with same size](https://stackoverflow.com/questions/25754524/javafx-buttons-with-same-size) – jewelsea Dec 24 '21 at 19:02
  • 1
    Canvas means something else in JavaFX (research it), try to use accurate terminology. – jewelsea Dec 24 '21 at 19:05

1 Answers1

2

Here's one way (code here but also possible in Scene Builder and FXML):

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class TestApplication extends Application {
    
    @Override
    public void start(Stage stage) throws Exception {
        Button button1 = new Button("Button1");
        HBox.setHgrow(button1, Priority.SOMETIMES);
        button1.setMaxWidth(Double.MAX_VALUE);
        button1.setMaxHeight(Double.MAX_VALUE);

        Button button2 = new Button("Button2");
        HBox.setHgrow(button2, Priority.SOMETIMES);
        button2.setMaxWidth(Double.MAX_VALUE);
        button2.setMaxHeight(Double.MAX_VALUE);

        HBox hBox = new HBox(button1, button2);
        AnchorPane.setLeftAnchor(hBox, 0.0);
        AnchorPane.setRightAnchor(hBox, 0.0);
        AnchorPane.setTopAnchor(hBox, 0.0);
        AnchorPane.setBottomAnchor(hBox, 0.0);
        AnchorPane rootContainer = new AnchorPane(hBox);

        Scene scene = new Scene(rootContainer, 600, 600);
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}
Manius
  • 3,594
  • 3
  • 34
  • 44