javajavafxjfoenix

adding custom css to button in JavaFX


I am trying to add some custom css to a button of mine, the css file is in the same folder as my testButton.java. this is my main/only class:

import com.jfoenix.controls.JFXButton;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;

public class testButton extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Vulpix Skyen");

        GridPane gridPane = createRegistrationFormPane();

        addUIControls(gridPane);

        Scene scene = new Scene(gridPane, 800, 500);

        scene.getStylesheets().clear();
        scene.getStylesheets().add(getClass().getResource("test.css").toExternalForm());


        primaryStage.setScene(scene);
        primaryStage.show();
    }


    private GridPane createRegistrationFormPane() {

        GridPane gridPane = new GridPane();

        return gridPane;
    }

    private void addUIControls(GridPane gridPane) {

        JFXButton jfoenixButton = new JFXButton("JFoenix Button");
        JFXButton button = new JFXButton("Raised Button".toUpperCase());
        button.getStyleClass().add("button-raised");
        jfoenixButton.getStyleClass().add("button-raised");
        gridPane.add(jfoenixButton, 0, 0);
        gridPane.add(button, 1, 0);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

and here is the css file:

.button-raised {
    -fx-padding: 0.7em 0.57em;
    -fx-font-size: 140px;
    -jfx-button-type: raised;
    -fx-background-color: rgb(77, 102, 204);
    -fx-pref-width: 200;
    -fx-text-fill: ORANGE;
}

And no matter what I change, my button stays the same default style. nothing in particular i am trying to add with the css, but no idea why its not changing at all.


Solution

  • You are not adding the styled button to the gridPane. The only button added to the pane is jfoenixButton which does not have the button-raised class.

    Either add the class to that button too:

    jfoenixButton.getStyleClass().add("button-raised");
    

    Or add the styled button to your gridPane:

    gridPane.add(button, 1, 0);
    

    One of the options should solve your problem.