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

如何在JavaFX TextField中将特定单词“warning”改为红色

JavaFX TextField 实现特定单词颜色高亮

要实现TextField中仅"warning"单词变红,由于原生TextField不支持富文本格式,推荐两种方案:

方案一:使用RichTextFX库(简单高效)

RichTextFX是专门用于JavaFX的富文本编辑库,能轻松实现部分文本样式修改。

1. 添加依赖

Maven项目在pom.xml中加入:

<dependency>
    <groupId>org.fxmisc.richtext</groupId>
    <artifactId>richtextfx</artifactId>
    <version>0.10.6</version> <!-- 可替换为最新版本 -->
</dependency>

2. 代码实现

import org.fxmisc.richtext.StyleClassedTextArea;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class WarningHighlightApp extends Application {
    @Override
    public void start(Stage stage) {
        // 替换原生TextField为StyleClassedTextArea
        StyleClassedTextArea textArea = new StyleClassedTextArea();
        textArea.setWrapText(true);
        textArea.setStyle("-fx-text-fill: black;"); // 默认文本黑色

        // 监听文本变化,自动高亮"warning"
        textArea.textProperty().addListener((obs, oldText, newText) -> {
            textArea.clearStyle(0, textArea.getLength()); // 清除旧样式
            int index = newText.indexOf("warning");
            while (index != -1) {
                int endIndex = index + "warning".length();
                textArea.setStyle(index, endIndex, "warning-highlight");
                index = newText.indexOf("warning", endIndex);
            }
        });

        VBox root = new VBox(textArea);
        Scene scene = new Scene(root, 400, 300);
        // 加载CSS样式
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
        
        stage.setTitle("Warning Highlight Demo");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

3. CSS样式文件(styles.css)

.warning-highlight {
    -fx-fill: red;
}

方案二:自定义实现(无第三方依赖)

如果不想引入外部库,可以用TextField接收输入,TextFlow显示格式化后的文本:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

public class CustomHighlightDemo extends Application {
    @Override
    public void start(Stage stage) {
        TextField inputField = new TextField();
        TextFlow displayFlow = new TextFlow();
        // 让TextFlow外观接近TextField
        displayFlow.setStyle("-fx-padding: 2px; -fx-border-color: gray; -fx-border-width: 1px;");

        // 同步输入与格式化显示
        inputField.textProperty().addListener((obs, oldText, newText) -> {
            displayFlow.getChildren().clear();
            // 分割文本,保留"warning"作为独立片段
            String[] parts = newText.split("(?=warning)|(?<=warning)");
            for (String part : parts) {
                Text textNode = new Text(part);
                if (part.equals("warning")) {
                    textNode.setStyle("-fx-fill: red;");
                } else {
                    textNode.setStyle("-fx-fill: black;");
                }
                displayFlow.getChildren().add(textNode);
            }
        });

        VBox root = new VBox(inputField, displayFlow);
        Scene scene = new Scene(root, 400, 100);
        
        stage.setTitle("Custom Highlight Demo");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

注:方案二的TextFlow默认不可编辑,若要实现直接编辑需额外处理鼠标和键盘事件,复杂度较高,推荐方案一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:07:50