Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: Layout problem with BorderPane - bug or user error?

Tags:

I am experiencing a strange behaviour with a FlowPane within (the center of) a BorderPane. Example

If I enlarge the width of the window or reduce it, everything is fine. It is just a narrow width +- 5 pixels that causes this effect. Code to reproduce:

public class LayoutBugTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }
    
    public void start(Stage stage) {
        TextField tf1 = new TextField("");
        TextField tf2 = new TextField("");
        TextField tf3 = new TextField("");
        tf1.setPrefColumnCount(20);
        tf2.setPrefColumnCount(10);
        tf3.setPrefColumnCount(10);     
        FlowPane flow = new FlowPane(10,10, tf1,tf2,tf3);
        
        BorderPane box = new BorderPane();
        box.setTop(new Label("Heading"));
        box.setCenter(flow);
        box.setStyle("-fx-border-width: 2px; -fx-border-color: black; -fx-border-radius: 1em; -fx-padding: 5px;");
        
        VBox anyLayout = new VBox(5, new Label("Before"), box, new Label("After"));
        
        Scene scene = new Scene(anyLayout);
        stage.setScene(scene);
        stage.show();
    }

}

Did I miss something or is this a layout bug?

like image 513
taranion Avatar asked Mar 08 '21 10:03

taranion


1 Answers

This appears to be an odd bug. I added some debugging information.

scene.widthProperty().addListener(evt ->{
        System.out.println( "box: " + box.prefHeight(anyLayout.getWidth()) + ", " + box.minHeight(anyLayout.getWidth()) + ", " + box.getHeight() );
        System.out.println( "flow: " + flow.prefHeight(box.getWidth()) + ", " + flow.minHeight(box.getWidth()) + ", " + flow.getHeight());

    });

When the program is started. The two fields narrow fields are side by side, and the preferred sizes are:

box: 95.0, 95.0, 95.0
flow: 64.0, 64.0, 64.0

As we decrease the width of the window the FlowPane switches orientation, but it's minimum and preferred sizes don't change.

box: 95.0, 95.0, 95.0
flow: 64.0, 64.0, 101.0

When we decrease further and the layout looks good again.

box: 132.0, 132.0, 132.0
flow: 101.0, 101.0, 101.0

So it appears BorderPane is using the correct width for the FlowPane to "layout" but it is using the incorrect width when requesting the preferred height. eg

flow.prefHeight(box.getWidth() - 14);

That pref. height follows the actual height of the FlowLayout. 14 from the padding and the border.

like image 165
matt Avatar answered Oct 12 '22 23:10

matt