我是 Java 和 JavaFX 的新手,遇到了一个问题。我试图将一个 css 文件添加到 javafx 应用程序,但我只是收到错误“找不到资源 Style.css”。 大部分代码都基于我在 YouTube 上找到的教程。 css 文件与 Main.java 文件位于同一目录中。我不确定这是否是将样式表添加到 javafx 的正确方法,但这适用于教程。
package sample;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
Stage window;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Title");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(8);
grid.setHgap(10);
//Name label
Label nameLabel = new Label("Username:");
GridPane.setConstraints(nameLabel, 0 ,0);
//Name input
TextField nameInput = new TextField("Emil");
GridPane.setConstraints(nameInput, 1, 0);
//Password label
Label passLabel = new Label("Password:");
GridPane.setConstraints(passLabel, 0, 1);
//Password input
TextField passInput = new TextField();
passInput.setPromptText("password");
GridPane.setConstraints(passInput, 1, 1);
//Login button
Button loginButton = new Button("Log In");
GridPane.setConstraints(loginButton, 1, 2);
grid.getChildren().addAll(nameLabel, nameInput, passLabel, passInput, loginButton);
Scene scene = new Scene(grid, 600, 350);
scene.getStylesheets().add("Style.css");
window.setScene(scene);
window.show();
}
}
最佳答案
假设您的 css 文件与 Main.java 位于同一目录中,请尝试像这样添加您的 css:
String css = this.getClass().getResource("Style.css")
.toExternalForm();
scene.getStylesheets().add(css);
编辑:因为你的 css 文件在同一个目录中,它应该像这样工作。抱歉,过度阅读了您问题中的这句话。
通常你的类文件被编译到一个 bin 目录中(如果你使用的是 eclipse),但是你没有你的 css 资源,这就是为什么找不到它的原因
关于java - 将样式表添加到 javafx 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004741/