Selecting Inline Elements in JTextPane
A JTextPane
allows embedding JComponents
and images . When you select a section of the document, the text is highlighted but inline elements are not. You can add inline components through CaretListener
after the event, but I was wondering if there is a way to highlight them during mouse selection?
source to share
Set the user Highlighter
in JTextPane
, which can inform the embedded components, they should be allocated or not:
textPane.setHighlighter( new CustomHighlighter() );
// ...
private final class CustomHighlighter extends DefaultHighlighter {
@Override
public Object addHighlight( int p0, int p1, HighlightPainter p ) throws BadLocationException {
Object tag = super.addHighlight(p0, p1, p);
/* notify embedded components ... */
return tag;
}
@Override
public void removeHighlight( Object tag ) {
super.removeHighlight(tag);
/* notify embedded components ... */
}
@Override
public void removeAllHighlights() {
super.removeAllHighlights();
/* notify embedded components ... */
}
@Override
public void changeHighlight( Object tag, int p0, int p1 ) throws BadLocationException {
super.changeHighlight(tag, p0, p1);
/* notify embedded components ... */
}
}
source to share
Ok, I did something similar, a long time ago. In my cases, the built-in components were emoticons in the chat editor. What you do is that when a selection happens, you get a label and a dot (e.getMark, e.getDot). If the emoji lies between the label and point, then it must be highlighted, so you set a field in the emoji component to indicate highlight and send a redraw request. Finally, in the paint (g) method of the emoticon component, you simply paint it as selection.
source to share