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

配置Eclipse SourceViewer实现Java代码语法着色失败求助

Java SourceViewer语法着色失效的修复方案

以下是针对代码问题的具体修复步骤:

  • 调整配置与文档设置的顺序
    当前代码先设置文档再配置查看器,会导致配置中的语法规则无法绑定到已加载的文档。修改顺序为先配置查看器,再设置文档:

    ScopedPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, ID);
    JavaTextTools tools = new JavaTextTools(store);
    
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new GridLayout(1, false));
    
    viewer = new SourceViewer(composite, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
    viewer.getTextWidget().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    viewer.setEditable(true);
    viewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
    
    // 先配置查看器
    viewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING));
    
    Document document = new Document();
    tools.setupJavaDocumentPartitioner(document);
    // 再设置文档
    viewer.setDocument(document);
    
  • 确保分区器正确激活
    显式触发文档分区器的连接,保证语法分区规则生效:

    Document document = new Document();
    IDocumentPartitioner partitioner = tools.getDocumentPartitioner();
    document.setDocumentPartitioner(partitioner);
    partitioner.connect(document); // 激活分区器
    viewer.setDocument(document);
    
  • 验证偏好存储ID的正确性
    确保ID指向Eclipse Java编辑器的官方偏好ID,否则无法读取默认的语法颜色配置:

    private static final String ID = "org.eclipse.jdt.ui";
    
  • 清理与初始化颜色管理器
    若颜色管理器未正确加载颜色定义,可强制初始化:

    tools.getColorManager().dispose();
    tools = new JavaTextTools(store);
    tools.getColorManager().defineColors(store);
    

注意:在组件销毁时,务必调用tools.getColorManager().dispose()释放颜色资源,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:35:24