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.
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:
after I have selected text:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With