views:

189

answers:

3

A JTextPane lets you embed JComponents and images. When you select a section of the document the text is highlighted but the embedded items are not. You can have the embedded components notified by way of a CaretListener after the event, but I was wondering if there was a way to have them highlighted during mouse selections?

A: 

YOu could use a MouseMotionListener and handle the mouseDragged event. You would then need to use the viewToModel() method to know which part of the model was being selected.

camickr
A: 

Well I did something similar, long long back. In my cases the embedded components were smileys in a chat editor. What you do is that when a selection happens, you get the mark and the dot(e.getMark, e.getDot). If the smiley lies between the mark and the dot, then it is supposed to be highlighted, so you set a field in the smiley component telling to be highlighted, and put a repaint request. Finally, in the paint(g) method of the smiley component you just paint it as highlighted.

Suraj Chandran
"You can have the embedded components notified by way of a CaretListener after the event, but I was wondering if there was a way to have them highlighted during mouse selections"
Matt R
A: 

Install a custom Highlighter into the JTextPane, which can inform the embedded components when they need to be highlighted 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 ... */ 
    }
}
Matt R