5

我在 JTextArea 中突出显示了一些文本,但我无法手动选择突出显示。我怎么能这样做?

jTextArea.getHighlighter().addHighlight(0,5);
jTextArea.getHighlighter().removeHighlight(jTextArea.getSelectionStart(),jTextArea.getSelectionEnd());

当我试图删除用户选择的突出显示时,选择开始和结束显示为一个并且相同,因此所选文本(textArea.getSelectedText())为空。

我想删除用户选择的突出显示。

当我使用键盘选择它时,它必须被选中。可以?还有一件事是选择文本时不应该删除突出显示。

任何解决方案表示赞赏。

4

1 回答 1

7

Grrr 我找到了一个更简单的解决方案,而不是使用SimpleAttributeSet.JTextPane StyledDocument

魔术发生在:StyleConstants.setBackground(sas, Color.RED);也可能是setForeground(..)

如果我们选择文本,它会应用我们看到的覆盖突出显示的文本(图 2)的内部荧光笔- 这是在文档级别完成的,因此不会干扰JTextPane默认使用的用户选择荧光笔 - 完全。

在这里检查:

当应用程序启动时:

在此处输入图像描述

在我选择了文本之后:

在此处输入图像描述

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class HighlightTest {

    String[] words = new String[]{"world", "cruel"};
    int[] wordsStartPos = new int[]{6, 21};
    String text = "Hello world, Goodbye cruel world";

    public HighlightTest() {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                JTextPane jta = new JTextPane();

                jta.setText(text);

                SimpleAttributeSet sas = new SimpleAttributeSet();
                StyleConstants.setBackground(sas, Color.RED);
                StyledDocument doc = jta.getStyledDocument();

                for (int i = 0; i < wordsStartPos.length; i++) {
                    doc.setCharacterAttributes(wordsStartPos[i], words[i].length(), sas, false);
                }
                frame.add(jta);

                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public static void main(String[] args) {
        new HighlightTest();
    }
}
于 2013-06-29T07:43:56.247 回答