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

RichTextFX的StyleClassedTextArea指定范围文本高亮不生效问题求助

问题原因

  • 你混淆了StyleClassedTextArea和InlineCssTextArea的API用法:StyleClassedTextArea的setStyle(int start, int end, Collection<String> styleClasses)方法接收的参数是CSS样式类名集合,不是直接的内联CSS样式字符串,你传入内联样式自然不会生效。
  • 你用的-fx-highlight-fill是文本被选中时的高亮背景色属性,要设置普通状态下的文本颜色,应该使用-fx-fill属性。
  • 你原来的范围参数1016只能截取到`WARNI`,少了最后一个字符`G`,需要调整为1017才能完整选中WARNING单词。

实现方案

下面提供两种可行的实现方式:

方式1:改用InlineCssTextArea直接写内联样式

如果不想单独定义CSS类,直接用支持内联样式的InlineCssTextArea组件即可,修改后代码如下:

public class GuiMain extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        // 改用支持内联样式的InlineCssTextArea
        InlineCssTextArea textArea = new InlineCssTextArea();
        String exampleString = "This is a WARNING for an INFO! Please stay tuned";
        textArea.appendText(exampleString);
        // 直接传入内联样式,-fx-fill设置文本颜色,-fx-font-weight设置字重
        textArea.setStyle(10, 17, "-fx-font-weight: bold; -fx-fill: #B22224;");
        textArea.setEditable(false);

        Scene scene2 = new Scene(new StackPane(textArea), 600, 400);
        primaryStage.setScene(scene2);
        primaryStage.setTitle("");
        primaryStage.setMaximized(false);
        primaryStage.show();
    }
}

方式2:继续使用StyleClassedTextArea,绑定CSS类

首先先定义CSS样式文件,内容如下:

.warning-text {
    -fx-font-weight: bold;
    -fx-fill: #B22224;
}

再修改Java代码,将CSS样式表加入场景,给指定范围设置样式类:

public class GuiMain extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        StyleClassedTextArea textArea = new StyleClassedTextArea();
        String exampleString = "This is a WARNING for an INFO! Please stay tuned";
        textArea.appendText(exampleString);
        // 传入样式类名,不是内联样式
        textArea.setStyleClass(10, 17, "warning-text");
        textArea.setEditable(false);

        Scene scene2 = new Scene(new StackPane(textArea), 600, 400);
        // 加载刚才定义的CSS样式表,替换为你自己的样式文件路径
        scene2.getStylesheets().add("style.css");
        primaryStage.setScene(scene2);
        primaryStage.setTitle("");
        primaryStage.setMaximized(false);
        primaryStage.show();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:12:01