Search code examples
javafxgluongluon-mobile

Title in AppBar grows too large


On some views I show the name of a selected item as the title of the AppBar. But when the name is very long, the VBoxcontaining the title label grows to the prefWidth of the label. You can see the result on the first picture. As a workaround I add a styleClass to the appBar, which sets the maxWidth for the label.

   view.setOnShown(e -> getAppBar().getStyleClass().add("myStyleClass"));

Although it's working, it's bad practice to set the maxWidth like that, because it can't be adjusted to different screen sizes.

How can I achieve the result on the second picture, and make the title's width adapt to different screen sizes?

enter image description here


Solution

  • A quick and dirty workaround to set the max width of the label based on the scene dimensions could be, on a View subclass:

    @Override
    protected void updateAppBar(AppBar appBar) {
        appBar.setTitleText("Very very very long title");
        ((Label) appBar.getTitle()).maxWidthProperty().bind(appBar.getScene().widthProperty().subtract(100));       
    }
    

    where the amount to subtract will depend on the number of buttons (nav icon, action icons or menu button) you have in that view.