Mastering JavaFX 10
上QQ阅读APP看书,第一时间看更新

Size of the Controls

Control (or any Region derived class) has three size limitations:

  • minSize: Minimal size
  • prefSize: Preferred size
  • maxSize: Maximal size

Layout managers, while handling their children, try to use their prefSize. If it's not possible, they are obliged to not shrink any child smaller than their minSize and not let them grow bigger than their maxSize.

Controls usually set their prefSize by themselves based on their content.

For example, button prefSize is based on the length of the text inside, minSize is just enough to show ellipsis instead of text, and the maxSize of  Button is similar to prefSize.

Thus, you don't need to care about a size of the Button in the following sample:

        VBox root = new VBox(5);
root.setPadding(new Insets(20));
Button btnShort = new Button("short");
btnShort.setMinWidth(50);
root.getChildren().addAll(
new Button("hi"),
btnShort,
                new Button("mediocre"),
new Button("wide-wide-wide")
);

And, if you try to resize the window, the button btnShort keeps its width, as shown in the following screenshots:

If you want your Control or other Region to always have a fixed size, you need to set all three sizes to the same value.

If you want to use Control's own prefSize to be used as max or min you can use a special constant—Control.USE_PREF_SIZE. For example, btn.setMinHeight(Control.USE_PREF_SIZE);.