You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX添加CSS后场景切换报错、无CSS可正常运行问题求助

JavaFX场景切换加CSS报错问题解决方案

核心错误1:控制器类场景初始化顺序错误

你在SceneController的两个场景切换方法中,先调用了未初始化的scene对象的方法,之后才创建Scene实例,导致触发空指针异常,这是报错的直接原因。
原错误逻辑顺序:

  1. 加载FXML获取parent
  2. 获取Stage
  3. 读取CSS路径
  4. 调用scene.getStylesheets().add(css) → 此时scene还未赋值,为null,直接报错
  5. 才执行scene = new Scene(parent)创建场景

修正后的SceneController代码:

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SceneController {

    private Stage stage;
    private Scene scene;
    private Parent parent;

    public void switchToApp(ActionEvent event) throws IOException {
        parent = FXMLLoader.load(getClass().getResource("App.fxml"));
        stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        // 先创建Scene实例,再添加样式表
        scene = new Scene(parent);
        String css = this.getClass().getResource("application.css").toExternalForm();
        scene.getStylesheets().add(css);
        stage.setScene(scene);
        stage.show();
    }

    public void switchToApp2(ActionEvent event) throws IOException {
        parent = FXMLLoader.load(getClass().getResource("App2.fxml"));
        stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        // 先创建Scene实例,再添加样式表
        scene = new Scene(parent);
        String css = this.getClass().getResource("application.css").toExternalForm();
        scene.getStylesheets().add(css);
        stage.setScene(scene);
        stage.show();
    }
}

核心错误2:CSS文件存在JavaFX不支持的属性

JavaFX CSS规范中没有-fx-outline属性,你写的这个是标准网页CSS的属性,放在JavaFX里会触发样式解析错误。同时颜色值可以去掉引号避免不必要的解析异常。

修正后的application.css代码:

.root{
    -fx-background-color: red;
}
#Sc1{
    -fx-alignment: center;
}
#Sc2{
    -fx-alignment: center;
    -fx-text-fill: GREEN;
}

.label{
    -fx-font-size: 20;
    -fx-font-family: "Lucida Console";
    -fx-text-fill: white;
    -fx-alignment: center;
}

#titleLebel{
    -fx-font-size: 60;
}

如果你需要去掉按钮的默认边框,可以添加-fx-background-insets: 0;或者-fx-border-width: 0;属性替代不存在的-fx-outline。

修改完以上两处代码后,程序即可正常加载CSS并切换场景。


内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:45:00