package com.aiclient.service; import javafx.scene.Scene; import java.util.Objects; public class ThemeService { private static final String LIGHT_THEME = "/css/light-theme.css"; private static final String DARK_THEME = "/css/dark-theme.css"; private static final String BASE_STYLE = "/css/style.css"; private Scene scene; public boolean isDarkTheme = false; public void setScene(Scene scene) { if (scene == null) return; this.scene = scene; applyBaseStyle(); applyTheme(isDarkTheme); } private void applyBaseStyle() { if (scene == null) return; String baseStyle = Objects.requireNonNull(getClass().getResource(BASE_STYLE)).toExternalForm(); if (!scene.getStylesheets().contains(baseStyle)) { scene.getStylesheets().add(baseStyle); } } public void toggleTheme() { if (scene == null) return; isDarkTheme = !isDarkTheme; applyTheme(isDarkTheme); } private void applyTheme(boolean dark) { if (scene == null) return; // 移除现有主题 scene.getStylesheets().removeIf(style -> style.endsWith("light-theme.css") || style.endsWith("dark-theme.css") ); // 应用新主题 String theme = dark ? DARK_THEME : LIGHT_THEME; String themeStyle = Objects.requireNonNull(getClass().getResource(theme)).toExternalForm(); scene.getStylesheets().add(themeStyle); } public boolean isDarkTheme() { return isDarkTheme; } }