java 在java中突出显示文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6530105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:12:53  来源:igfitidea点击:

Highlighting Text in java

javaswingindexinghighlightingjtextarea

提问by Nuwan

We are developing a plagiarism detection framework. In there i have to highlight the possible plagiarized phrases in the document. The document gets preprocessed with stop word removal, stemming and number removal first. So the highlighting gets difficult with the preprocessed token As and example:

我们正在开发一个剽窃检测框架。在那里我必须突出显示文档中可能的抄袭短语。文档首先通过停用词去除、词干提取和数字去除进行预处理。因此,使用预处理的令牌 As 和示例,突出显示变得困难:

Orginal Text: "Extreme programming is one approach of agile software development which emphasizes on frequent releases in short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming(for code review, unit testing). Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized. "

原文:“极限编程是敏捷软件开发的一种方法,它强调在称为时间盒的短开发周期中频繁发布。这通过拥有多个短开发周期而不是一个长开发周期来减少变更成本.极限编程包括成对编程(用于代码、单元测试)。此外,它还避免实现当前时间框中未包含的功能,因此可以最大限度地减少进度蠕变。”

phrase want to highlight: Extreme programming includes pair-wise programming

短语要强调: 极限编程包括成对编程

preprocessed token : Extrem program pair-wise program

预处理令牌:极值程序成对程序

Is there anyway I can highlight the preprocessed token in the original document????

无论如何我可以突出显示原始文档中的预处理令牌????

Thanx

谢谢

回答by MockerTim

You'd better use JTextPaneor JEditorPane, instead of JTextArea.

您最好使用JTextPaneJEdi​​torPane,而不是JTextArea

A text area is a "plain" text component, which means taht although it can display text in any font, all of the text is in the same font.

文本区域是一个“纯”文本组件,这意味着虽然它可以显示任何字体的文本,但所有文本都是相同的字体。

So, JTextAreais not a convenient component to make any text formatting.

所以,JTextArea不是一个方便的组件来制作任何文本格式。

On the contrary, using JTextPaneor JEditorPane, it's quite easy to change style (highlight) of any part of loaded text.

相反,使用JTextPaneJEditorPane,可以很容易地更改加载文本任何部分的样式(突出显示)。

See How to Use Editor Panes and Text Panesfor details.

有关详细信息,请参阅如何使用编辑器窗格和文本窗格

Update:

更新:

The following code highlights the desired part of your text. It's not exectly what you want. It simply finds the exact phrase in the text.

以下代码突出显示了文本的所需部分。这不完全是你想要的。它只是在文本中找到确切的短语。

But I hope that if you apply your algorithms, you can easily modify it to fit your needs.

但我希望如果你应用你的算法,你可以轻松地修改它以满足你的需要。

import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class LineHighlightPainter {

    String revisedText = "Extreme programming is one approach "
            + "of agile software development which emphasizes on frequent"
            + " releases in short development cycles which are called "
            + "time boxes. This result in reducing the costs spend for "
            + "changes, by having multiple short development cycles, "
            + "rather than one long one. Extreme programming includes "
            + "pair-wise programming (for code review, unit testing). "
            + "Also it avoids implementing features which are not included "
            + "in the current time box, so the schedule creep can be minimized. ";
    String token = "Extreme programming includes pair-wise programming";

    public static void main(String args[]) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    new LineHighlightPainter().createAndShowGUI();
                }
            });
        } catch (InterruptedException ex) {
            // ignore
        } catch (InvocationTargetException ex) {
            // ignore
        }
    }

    public void createAndShowGUI() {
        JFrame frame = new JFrame("LineHighlightPainter demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextArea area = new JTextArea(9, 45);
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        area.setText(revisedText);

        // Highlighting part of the text in the instance of JTextArea
        // based on token.
        highlight(area, token);

        frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    // Creates highlights around all occurrences of pattern in textComp
    public void highlight(JTextComponent textComp, String pattern) {
        // First remove all old highlights
        removeHighlights(textComp);

        try {
            Highlighter hilite = textComp.getHighlighter();
            Document doc = textComp.getDocument();
            String text = doc.getText(0, doc.getLength());

            int pos = 0;
            // Search for pattern
            while ((pos = text.indexOf(pattern, pos)) >= 0) {
                // Create highlighter using private painter and apply around pattern
                hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
                pos += pattern.length();
            }

        } catch (BadLocationException e) {
        }
    }

    // Removes only our private highlights
    public void removeHighlights(JTextComponent textComp) {
        Highlighter hilite = textComp.getHighlighter();
        Highlighter.Highlight[] hilites = hilite.getHighlights();

        for (int i = 0; i < hilites.length; i++) {
            if (hilites[i].getPainter() instanceof MyHighlightPainter) {
                hilite.removeHighlight(hilites[i]);
            }
        }
    }
    // An instance of the private subclass of the default highlight painter
    Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

    // A private subclass of the default highlight painter
    class MyHighlightPainter
            extends DefaultHighlighter.DefaultHighlightPainter {

        public MyHighlightPainter(Color color) {
            super(color);
        }
    }
}

This example is based on Highlighting Words in a JTextComponent.

此示例基于JTextComponent 中的突出显示单词

回答by Andreas Dolk

From a technical point of view: You can either choose or develop a markup languageand add annotations or tags to the original document. Or you want to create a second file that records all potential plagiarisms.

从技术角度来看:您可以选择或开发一种标记语言,并在原始文档中添加注释或标签。或者您想创建第二个文件来记录所有潜在的剽窃行为。

With markup, your text could look like this:

使用标记,您的文本可能如下所示:

[...] rather than one long one. <plag ref="1234">Extreme programming 
includes pair-wise programming</plag> (for code review, unit testing). [...]

(with refreferencing to some metadata record that describes the original)

(使用ref引用一些描述原始数据的元数据记录)

回答by Jochen Bedersdorfer

You could use java.text.AttributedString to annotate the preprocessed tokens in the original document. Then apply TextAttributes to the relevant ones (which whould take effect in the original document.

您可以使用 java.text.AttributedString 注释原始文档中的预处理标记。然后将 TextAttributes 应用到相关的(在原始文档中生效。