My first attempt to play with JavaFX, and I'm trying to understand a little about prototyping. How to access the preferred size of the control?
In the example below, I am trying to set the maximum width to 200 pixels wider than the preferred width. That is, I want the button to increase (to the maximum) as the frame width increases.
However, when I run the code, the preferred width is -1, so adding 200 to the preferred width gives a maximum width of 199.
import javafx.application.Application; import javafx.event.*; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.geometry.Insets; public class BorderPaneSSCCE extends Application { @Override public void start(Stage primaryStage) { Button button = new Button( "Button at PreferredSize" ); button.setMaxWidth( button.getPrefWidth() + 200 ); System.out.println(button.prefWidth(-1) + " : " + button.getPrefWidth()); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Width: " + button.getWidth()); } }); HBox root = new HBox(); HBox.setHgrow(button, Priority.ALWAYS); root.getChildren().add(button); Scene scene = new Scene(root); primaryStage.setTitle("Java FX"); primaryStage.setScene(scene); primaryStage.show(); System.out.println(button.prefWidth(-1) + " : " + button.getPrefWidth()); } public static void main(String[] args) { launch(args); } }
When I run the code and click on the button, I see: Width: 139.0
After resizing the frame so that the button is as large as possible, and I click the button that I see: Width: 199.0
I was hoping to see Width: 339.0 (i.e. 139 + 200)
So, how do we access the preferred size / width of the control?
source share