1

I am trying to add images in the GUI I ve created using JavaFx. My JavaFx is the following:

StackPane layoutTSignUp = new StackPane();
layoutTSignUp.setStyle("-fx-background-color: #FFFF;");

How can I instead of having a color I can add images. Furthermore how can I achieve the same in my buttons:

teacherButton.setStyle("-fx-font: 45 Arial; -fx-base: #FFFF");
DVarga
  • 21,311
  • 6
  • 55
  • 60
konstantin
  • 853
  • 4
  • 16
  • 50
  • You second question about images in buttons is duplicate of: [JavaFX - create custom button with image](http://stackoverflow.com/questions/10518458/javafx-create-custom-button-with-image) – jewelsea May 19 '16 at 19:03

1 Answers1

2

Programatically

For your StackPane you can use BackgroundImage class:

BackgroundImage backgroundImage= new BackgroundImage(new Image(getClass().getResource("thinking-man.jpg").toExternalForm(),32,32,false,true),
                BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
                BackgroundSize.DEFAULT);

stackPane.setBackground(new Background(backgroundImage));

For buttons: Buttons have a graphic property:

button.setGraphic(new ImageView(new Image(getClass().getResource("thinking-man.jpg").toExternalForm())));

Using CSS

If you would prefer to use stylesheets to set background images you can use:

-fx-background-image, -fx-background-repeat, -fx-background-position and -fx-background-size.

For details you can read the JavaFX CSS reference for Region class.

Using the same example with StackPane:

stackPane.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
stackPane.getStyleClass().add("stackpane-with-background");

In application.css:

.stackpane-with-background{
    -fx-background-image: url("thinking-man.jpg");
    -fx-background-repeat: stretch;   
    -fx-background-size: 900 506;
    -fx-background-position: center center;
    -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); 
}

Hope this helps.

DVarga
  • 21,311
  • 6
  • 55
  • 60