user5446333
user5446333

Reputation:

JavaFX BorderPane will not take on background colour

I'm trying to teach myself basic JavaFX by following the tutorials provided by Oracle.

In the BorderPane tutorial (https://docs.oracle.com/javafx/2/layout/builtin_layouts.htm) it specifies a background colour.

This is a snippet of my code:

/**
 * This Method creates and defines a horizontal box with a button.
 */
public HBox addHorizontalBoxWithButton() {
    // set up horizontal box and button
    HBox hBox = new HBox();
    hBox.setPadding(new Insets(10, 10, 10, 10));
    hBox.setSpacing(10);
    hBox.setStyle("-fx-background-colour: #FFFFFF;");
    hBox.setAlignment(Pos.CENTER);
    Button startButton = new Button("CLICK ME");
    startButton.setPrefSize(100, 30);
    // set up a message
    Text message = new Text("Click the button to get started.");
    message.setId("message");

    hBox.getChildren().add(message);
    hBox.getChildren().add(startButton);

    return hBox;
}

I have tried various different background colours, none of which work. Am I missing something here?

Also, I am using a .css file but it only adds style to the 'message'.

Upvotes: 2

Views: 11656

Answers (2)

James_D
James_D

Reputation: 209330

The only problem with the original code is that you have a "typo" (anglification?) in your style setting. It should be

hBox.setStyle("-fx-background-color: #FFFFFF;");

not

hBox.setStyle("-fx-background-colour: #FFFFFF;");

Using an external style sheet with

#hbox {
    -fx-background-color: red ;
}

is a better solution than using inline styles.

Upvotes: 4

user5446333
user5446333

Reputation:

Okay I just solved this.

I changed my code like so:

/**
 * This Method creates and defines a horizontal box with a button.
 */
public HBox addHorizontalBoxWithButton() {
    // set up horizontal box and button
    HBox hBox = new HBox();
    hBox.setId("hBox");
    hBox.setPadding(new Insets(10, 10, 10, 10));
    hBox.setSpacing(10);
    // hBox.setStyle("-fx-background-colour: #FFFFFF;");
    hBox.setAlignment(Pos.CENTER);
    Button startButton = new Button("CLICK ME");
    startButton.setPrefSize(100, 30);
    // set up a message
    Text message = new Text("Click the button to get started.");
    message.setId("message");

    hBox.getChildren().add(message);
    hBox.getChildren().add(startButton);

    return hBox;
}

And I added this to the .css file:

#hBox {
-fx-background-color: linear-gradient(#04B45F, #81F79F);
}

Upvotes: 1

Related Questions