0

I'm making a chat room with a JTextPane with html function. Users are able to input html tag to show image on the screen. But I'm having a problem to keep the scrollbar at bottom. I already try to do

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        vertical.setValue(vertical.getMaximum());
    }
});

but the scrollbar scroll down then scroll up again. It seems like the picture finish loading after the function been called. I also tried:

ClientScreen._chatMsgPane.setCaretPosition(_chatMsgPane.getDocument().getLength());

but the result are the same. Is there's any event will trigger after all image finish loading? Or is there any other way to fix this?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Ashley Shen
  • 115
  • 4
  • 12
  • btw I also tried to call Thread.sleep(450); after setText(); but it work strangely. The screen will become messy if I type quickly and every time when I send message the scrollbar will scroll up and scroll down. I mean it work but not well. – Ashley Shen Jun 09 '13 at 20:41
  • 2
    Please edit your question to include an [sscce](http://sscce.org/) that exhibits the problem you describe; you can access posted images via `URL`, as shown [here](http://stackoverflow.com/a/10862262/230513), to reproduce latency. – trashgod Jun 09 '13 at 21:04

2 Answers2

0

I've never tried this on a JTextPane that is loading an image but Smart Scrolling might work for you.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

JComponent has a method named scrollRectToVisible which is designed to do this:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        int end = chatMsgPane.getDocument().getLength();
        try {
            chatMsgPane.scrollRectToVisible(chatMsgPane.modelToView(end));
        } catch (BadLocationException e) {
            throw new RuntimeException(e); // Should never get here.
        }
    }
});

I'm not entirely sure how you are addng the image to the JTextPane, but if you are loading it yourself, you can load it in a different thread with ImageIO.read and then scroll to bottom when the read is finished; or, if you want to show the image progressively, you can obtain an ImageReader from ImageIO, and pass your own listener to its addIIOReadProgressListener method.

VGR
  • 40,506
  • 4
  • 48
  • 63