Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaFX: HBox.setHgrow refuses to do its job

Taking this code, shouldn’t the word "Label" be on the right side of the application window?
To be more specific about my problem: Why doesn’t the HBox.setHgrow give the label all the horizontal space available?

package com.example.javafxwindow

import javafx.application.Application
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.Label
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.stage.Stage


class HelloApplication : Application()
{
    override fun start(stage: Stage)
    {
        val label = Label("Label")
        label.alignment = Pos.CENTER_RIGHT
        HBox.setHgrow(label, Priority.ALWAYS)
        val hbox = HBox(label)

        val scene = Scene(hbox, 400.0, 400.0)
        stage.scene = scene
        stage.show()
    }
}

fun main()
{
    Application.launch(HelloApplication::class.java)
}

This is, slowly but surely, driving me nuts.
I don’t know what to do else. Maybe I’m blind by now … where’s the error?

I would really appreciate any help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The label is bounded by its maxWidth which defaults to its prefWidth.

You want to make the maxWidth unbounded, so call:

label.setMaxWidth(Integer.MAX_VALUE)

Different controls have different defaults for maxWidth. For buttons and labels the maxWidth default to their prefWidth, so, unless you reset the maxWidth they won’t grow even if you provide hints which you might think would make them do so.

Quoting the Oracle JavaFX layout sizing tutorial (it would be nice if this was also in the java doc):

UI controls also provide default minimum and maximum sizes that are based on the typical usage of the control. For example, the maximum size of a Button object defaults to its preferred size because you don’t usually want buttons to grow arbitrarily large. However, the maximum size of a ScrollPane object is unbounded because typically you do want them to grow to fill their spaces.

An alternative is to insert a spring pane into the hbox before the label and set the hgrow on the spring pane instead. That will push the label all the way to the right. For info on that approach see:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading