如何通过JavaFX中的场景构建器向我的应用程序中添加一个style.css?

时间:2018-10-29 20:02:15

标签: java css javafx

我正在尝试将style.css添加到intellij中的Java应用程序中。因此,我添加了一个名为resources的新目录,并将style.css放入该文件夹中。在我的场景生成器内部,我已在GridPane中指定IO希望资源中的文件“ style.css”来控制视图。但是,每当我运行代码时,都会出现此错误。

错误:

Oct 29, 2018 3:56:58 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not find stylesheet: file:/C:/Users/Troy22/Desktop/Java/EMCGrabExtension/out/production/resources/style.css

我尝试了不同的方法,但似乎没有帮助。再次感谢您的帮助

代码:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Scene scene = new Scene(root,770,450);
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(scene);
        scene.getStylesheets().add("style.css");
        primaryStage.show();
    }


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

2 个答案:

答案 0 :(得分:1)

尝试将其添加到您的Main中:

        scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();

答案 1 :(得分:0)

您可以尝试通过Scenebuilder添加它(在顶层节点上,因此,如果您的根节点是BorderPane,则可以在此节点上添加它):

enter image description here

不过,我建议在我之前添加以下内容:

command

不要忘记“ getResource()”方法之后的“ .toExternalForm()”。 并确保您的资源文件夹位于类路径中,以便Java可以找到它。