更改javafx中TextField中单词的颜色

BaR*_*boD 1 java javafx

我有一个 TextField(JavaFX),其文本颜色为黑色,但如果文本中包含警告一词,它就会出现,并且只会将警告一词的颜色更改为红色。

Jam*_*s_D 5

JavaFX 文本输入控件不支持文本不同部分的多种样式。一种方法是使用提供该功能的第三方库。RichTextFX 库包含一些执行此操作的样式化文本区域类。以下是使用此库进行与您所描述的类似的操作的简短示例:

import javafx.application.Application;
import javafx.event.Event;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.fxmisc.richtext.StyleClassedTextArea;
import org.fxmisc.wellbehaved.event.EventPattern;
import org.fxmisc.wellbehaved.event.InputMap;
import org.fxmisc.wellbehaved.event.Nodes;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) {
        StyleClassedTextArea textArea = new StyleClassedTextArea();
        Pattern pattern = Pattern.compile("warning");
        textArea.textProperty().addListener((obs, oldText, text) -> {
            textArea.clearStyle(0, textArea.getLength());
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                textArea.setStyleClass(matcher.start(), matcher.end(), "warning");
            }
        });
        textArea.replaceText("This text area will highlight the word warning in any text");
        BorderPane root = new BorderPane(textArea);
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
Run Code Online (Sandbox Code Playgroud)

样式.css:

.warning {
    -fx-fill:red;
}
Run Code Online (Sandbox Code Playgroud)

pom.xml以下是提供 RichTextFX 库的部分内容:

    <repositories>
        <repository>
            <id>sonatype</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>20.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.fxmisc.richtext</groupId>
            <artifactId>richtextfx</artifactId>
            <version>0.11.1</version>
        </dependency>

    <!-- ... -->
    </dependencies>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述