首页 > 解决方案 > 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.

标签: javajavafxjfoenix

解决方案


您没有将样式按钮添加到gridPane. 添加到窗格的唯一按钮是jfoenixButton没有button-raised类的按钮。

也可以将类添加到该按钮:

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

或者将样式按钮添加到您的 gridPane:

gridPane.add(button, 1, 0);

其中一个选项应该可以解决您的问题。


推荐阅读