I have a large sized JPanel within a JScrollPane, and in this JPanel need to render LOTS of stuff. To speed up rendering I am using the Clip Rect (specified by the graphics object method getClipBounds()) to render only the things needed. I noticed the width of the returned rectangle seems somewhat unpredictable during a scrolling drag event (eg when a user drags the scroll bar). Here's a short snippet demonstrating the behavior - run, and start a repaint by resizing the window or dragging the scroll bar and notice the difference in printed out values. A similar behavior occurs when I animate the scrolling with a Timer
import javax.swing.*; import java.awt.*; public class ScrollDemo extends JFrame{ public ScrollDemo(){ super(); ScrollPanel scPanel = new ScrollPanel(); scPanel.setPreferredSize(new Dimension(5000,200)); JScrollPane scroller = new JScrollPane(scPanel); scroller.setPreferredSize(new Dimension(500,200)); getContentPane().add(scroller); pack(); setVisible(true); } private class ScrollPanel extends JPanel{ /** * Paints the component and prints out the values of the * Clip Rect width every time it paints. */ @Override public void paintComponent(Graphics g){ super.paintComponent(g); Rectangle rect = g.getClipBounds(); System.out.println(rect.width); } } public static void main(String[] args){ new ScrollDemo(); } }
It would be ideal if the width of the clip bounds actually gave the values I expected, but its not and I'm curious as to why and if there is a workaround to the issue.