我正在尝试使用javafx进行css。我的项目很简单,有2个场景,2个按钮。按钮在场景之间切换。包含主类的java文件如下:
package stageandscene;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.control.Label;
public class StageAndScene extends Application {
Scene scene1, scene2;
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
Button btn2= new Button();
btn.setText("Go to Scene 2");
btn.setOnAction(e ->primaryStage.setScene(scene2));
Label lebel= new Label("Hi there!! You are on scene 1");
GridPane grid = new GridPane();
grid.setHgap(20);
grid.setVgap(5);
grid.addRow(1, lebel,btn);
grid.setAlignment(Pos.CENTER);
scene1 = new Scene(grid, 300, 250);
scene1.getStylesheets().add("viper.css");
Label lebel2= new Label("Hi there!! You are on scene 2");
btn2.setText("Go to Scene 1");
btn2.setOnAction(e ->primaryStage.setScene(scene1));
GridPane grid2 = new GridPane();
grid2.setHgap(20);
grid2.setVgap(5);
grid2.addRow(1, lebel2,btn2);
grid2.setAlignment(Pos.CENTER);
scene2 = new Scene(grid2, 600, 550);
scene2.getStylesheets().add("viper.css");
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene1);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
" viper.css"在相同的项目文件夹上,如下所示:
.root{
-fx-background-color: #ff3333;
}
这个程序运行良好,但css文件不工作,两个场景的背景颜色不变。在运行该程序时,netbeans说" resource' viper.css'没有找到'。有谁能建议我如何克服这个错误?
答案 0 :(得分:0)
尝试这样的事情:
scene1.getStylesheets().add(getClass.getResource("viper.css").toExternalForm());
答案 1 :(得分:0)
您必须检查viper.css文件的路径。如果你这样访问它,那么你应该将主文件和CSS文件放在同一个文件夹中。