aeruhxi
aeruhxi

Reputation: 556

Why does my background color go beyond the size of node in Javafx FXML application?

My scene is:

Scene scene = new Scene(root, 320, 220);

in FXML, Grid pane is:

<GridPane fx:id="base"
      alignment="CENTER"
      maxHeight="200.0"
      maxWidth="300.0"
      stylesheets="@style.css"
      vgap="0" xmlns="http://javafx.com/javafx/8"
      xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="sample.Controller">
...

CSS for gridpane:

-fx-background-color: red;

Even though my gridpane's max height and width are 200 and 300 respectively, the background goes beyond that covering the whole scene. I have made the background red to make it apparent. Picture here

Can anyone explain this, please? And what is the way of making the background limited to only gridpane instead of the whole scene?

Upvotes: 0

Views: 770

Answers (2)

James_D
James_D

Reputation: 209330

A Scene performs no layout to speak of. The root of the Scene will fill the dimensions of the Scene regardless of any maximum (or minimum) size that has been set. So what is happening here is not that the "background color is going beyond the size of the node" so much as the node is filling the scene (and taking on a size larger than the max size you set). Basically, there is nothing that is managing the size of your GridPane and ensuring it doesn't grow beyond the maximum size you set for it.

To ensure your maxWidth and maxHeight are respected, you need to place the grid pane in a layout pane that will perform layout and pay attention to those properties. So you can do:

Scene scene = new Scene(new StackPane(root), 320, 220);

which will place the GridPane (root) in a StackPane. The StackPane manages the layout of root and ensures it doesn't grow beyond the maximum size you have set.

You can of course include the StackPane (or whatever you choose to manage the GridPane) in the FXML instead, if you prefer.

Perhaps off-topic, but if you are looking to have a gap between the grid pane and whatever surrounds it, you might consider doing this purely in your CSS:

#base {
    -fx-background-color: transparent, red ;
    -fx-background-insets: 0, 10 ;
    -fx-padding: 10 ;
}

Then you can add the grid pane directly to the scene, and (while it still fills the scene) it has a 10 pixel transparent border around the edge.

Note the CSS solution behaves differently to the first solution when you resize the window, so these are not equivalent.

Upvotes: 0

Venkat Prasanna
Venkat Prasanna

Reputation: 732

You check in css whether you have applied the background color for grid pane or to the scene. Or you can apply background color to gridPane through code itself as given below. Try this..

gridPane.setStyle("-fx-background-color:red");

Upvotes: 0

Related Questions