我正在用javafx试验css的使用。我的项目非常简单,有两个场景,两个按钮。按钮在场景之间切换。包含主类的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说"找不到资源'viper.css'。有人能建议我如何克服这个错误吗?
您必须检查viper.css文件的路径。若你们是这样访问它,那个么你们应该把主文件和CSS文件都放在同一个文件夹里。
试试这样的东西:
scene1.getStylesheets().add(getClass.getResource("viper.css").toExternalForm());