如何在javafx Textarea中高亮显示一个文本?

问题描述 投票:0回答:1

我正在用JavaFX构建一个记事本项目。目前,我已经添加了一个查找和替换的功能,我将在文本框中输入一个单词,在另一个文本框中输入可替换的单词,然后替换它们。我在一个文本框中输入一个单词,然后在另一个文本框中输入可替换的单词,然后替换它们。但我想添加一个功能,如果我在搜索框中输入一个单词,那么在记事本的textarea中的单词将被高亮显示。我使用的是JavaFX。我找了很多关于如何添加高亮显示的方法。但是大部分都是用java swing。对于JavaFX,我不知道如何添加高亮显示。

public void find_and_highlight(ActionEvent e)
{
    String text=A1.getText();
    String findtext=find.getText();
    int text_ln=A1.getText().length();
    int word_ln=find.getText().length();
    for(int i=0;i<text_ln-word_ln;i++)
    {
        String sub=text.substring(i,i+word_ln);
        if(sub.equals(findtext))
        {
            // what to do here
        }
    }

} 

因此,在上面的代码中,该功能被激活时,我写了一些文本在 "查找文本 "字符串,并按下按钮。字符串 "text "包含了textarea中的文本。如果找到了搜索词,我想高亮显示从index i到index i+ word_ln的文本,所以基本上我想。

highlight(i, i + word_len);

希望能得到帮助:)

java javafx project highlight notepad
1个回答
0
投票

我认为没有直接的方法,但你可以尝试以下方法 JFXHighlighterJFoenix. 下面是一个例子。

JFXHighlighter highlighter = new JFXHighlighter();
highlighter.setPaint(Color.YELLOW);

TextArea textArea = new TextArea("This is my text");
Button highlightButton = new Button("Highlight");
VBox parent = new VBox(textArea, highlightButton);

highlightButton.setOnAction(event -> {
    highlighter.highlight(parent, "text");
    event.consume();
});

输出。

enter image description here

注意:当文本中的 TextArea 变更。您可以通过在下面指定一个变更监听器来实现。textProperty().

Java 8的Maven依赖性。

<!-- https://mvnrepository.com/artifact/com.jfoenix/jfoenix -->
<dependency>
    <groupId>com.jfoenix</groupId>
    <artifactId>jfoenix</artifactId>
    <version>8.0.9</version>
</dependency>

Maven依赖性适用于Java 9+。

<!-- https://mvnrepository.com/artifact/com.jfoenix/jfoenix -->
<dependency>
    <groupId>com.jfoenix</groupId>
    <artifactId>jfoenix</artifactId>
    <version>9.0.9</version>
</dependency>
© www.soinside.com 2019 - 2024. All rights reserved.