Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to select highlighted text in jtextarea

I have highlighted some text in the JTextArea, but i am unable to select the highlight manually. How could i do this?

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

When i am trying to remove the highlight that is selected by the user, the selection start and end are being shown as one and the same and therefore the selected text (textArea.getSelectedText()) is null.

I want to remove the highlight that is selected by the user.

When i select it using the keyboard, it has to get selected. Does it? And one more thing is that the highlight should not be removed when the text is selected.

Any solution is appreciated.

like image 280
JavaTechnical Avatar asked Jun 29 '13 06:06

JavaTechnical


1 Answers

Grrr I found an easier solution, rather use SimpleAttributeSet of JTextPane StyledDocument.

The magic happens at: StyleConstants.setBackground(sas, Color.RED); could also be setForeground(..).

Than if we select text, it applies the internal highlighter which we see covering our highlighted text (Image 2) - which was done at document level, thus not interfering with user selection highlighter which the JTextPane uses by default - completely.

Check here:

When app starts:

enter image description here

after I have selected text:

enter image description here

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();
    }
}
like image 172
12 revs Avatar answered Nov 14 '22 22:11

12 revs