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

如何在SWT/Eclipse RCP应用中检测暗黑主题模式?

判断SWT/RCP应用是否处于暗黑主题显示模式

现有方案的局限

  • 使用org.eclipse.swt.widgets.Display.isSystemDarkTheme():仅能判断操作系统的暗黑偏好设置,无法反映应用自身的主题选择——即使系统开启暗黑模式,应用仍可能手动切换到亮色主题,导致判断失效。
  • 检测SWT.COLOR_LIST_BACKGROUND等颜色的HSB亮度:能准确判断当前界面明暗,但需要手动转换颜色格式、计算亮度,步骤繁琐。

更可靠的实现方式

方法1:检查当前应用主题ID

多数RCP应用会使用Eclipse内置主题或自定义主题,可通过主题ID直接判断是否为暗黑主题:

import org.eclipse.e4.ui.css.swt.theme.ITheme;
import org.eclipse.e4.ui.css.swt.theme.IThemeManager;
import org.eclipse.swt.widgets.Display;
import org.osgi.framework.FrameworkUtil;

public static boolean isDarkThemeActive() {
    // 获取主题管理器
    IThemeManager themeManager = FrameworkUtil.getBundle(Display.class)
            .getBundleContext()
            .getServiceReference(IThemeManager.class)
            .getBundle()
            .getBundleContext()
            .getService(IThemeManager.class);
    
    if (themeManager != null) {
        ITheme currentTheme = themeManager.getCurrentTheme();
        // 匹配常见暗黑主题ID,可根据应用自定义主题补充
        String[] darkThemeIds = {"org.eclipse.ui.theme.dark", "com.example.custom.dark.theme"};
        for (String id : darkThemeIds) {
            if (id.equals(currentTheme.getId())) {
                return true;
            }
        }
    }
    //  fallback到颜色亮度检测
    return isDarkByColorBrightness();
}

方法2:优化版颜色亮度检测

简化颜色转换逻辑,直接通过Display获取系统颜色的RGB值计算亮度(符合WCAG亮度标准):

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

public static boolean isDarkByColorBrightness() {
    Display display = Display.getDefault();
    Color bgColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
    RGB rgb = bgColor.getRGB();
    
    // 计算相对亮度
    double luminance = (0.2126 * rgb.red + 0.7152 * rgb.green + 0.0722 * rgb.blue) / 255;
    // 亮度低于0.5判定为暗黑主题
    return luminance < 0.5;
}

注意事项

  • 自定义主题需补充对应的暗黑主题ID到检测列表中;
  • 若应用支持动态切换主题,需在主题变更事件中重新执行判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:50:45