pen1993 pen1993 - 4 months ago 485
Java Question

How to add background-image to AnchorPane by using Scene Builder in JavaFX?

How add background image to an

AnchorPane
by using Scene Builder?

I've tried it as:

-fx-background-image url('C:/Users/Documents/page_background.gif')


How I set this in Scene Builder.

And the generated FXML:

<AnchorPane id="LoginAnchorPane" fx:id="LoginAnchorPane" prefHeight="400.0" prefWidth="600.0" style="-fx-background-image: url('C:/Users/Documents/page_background.gif');" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafx_lsdu.LoginController">



Answer

You can try to set it directly in Scene Builder as:

-fx-background-image: url('file:C:/Users/Documents/page_background.gif')

It requires the scheme/protocol to be specified.

But the suggested way, to separate CSS styling in a CSS file. For instance you can create a CSS style-class in your CSS file (let's call it "application.css"):

application.css

.anchor {
    -fx-background-image:url('file:/C:/Users/Documents/page_background.gif');
}

Then in the FXML file you add this stylesheet to the root and you add the anchor style-class to the AnchorPane:

<AnchorPane prefHeight="545.0" prefWidth="712.0" styleClass="anchor" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.60">
  <stylesheets>
    <URL value="@application.css" />
  </stylesheets>
</AnchorPane>

Note: Stylesheets should be added to the root node (in the example the AnchorPane is the root).