简体   繁体   中英

Stop JScrollPane from redraw JPanel

I have a JPanel with a JScrollPane sorounding it, the problem is that when i use the JScrollPane the JPanels redraw methode get called. I want to disable that because my JPanel redraw by its self at the right time.

I want it so it just updateds the getClipBounds() for the paint methode but withoud calling the paint methode.

You can't do that - since the viewport displays different parts of the contained JPanel, depending on the position of the scrollbar, the areas that have to be repainted might in fact be newly revealed and might not have been painted before.

Since JScrollPane doesn't know how the contained Component is implemented and whether it repaints its entire area or only the area that needs repainting, it forces the contained Component to redraw itself upon scrolling.

However, you can instead render the content you want to show to a bitmap, and then paint the bitmap in the paintComponent(Graphics) method. Thus, you effectively buffer your painted content and can initiate an update to the buffered bitmap whenever it suits you.

In order to paint onto a bitmap, you can do this:

BufferedImage buffer; // this is an instance variable

private void updateBuffer(){
   // Assuming this happens in a subclass of JPanel, where you can access
   // getWidth() and getHeight()
   buffer=new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
   Graphics g=buffer.getGraphics();
   // Draw into the graphic context g...
   g.dispose();
}

Then, in your JPanel, you override the paintComponent method:

public void paintComponent(Graphics g){
    g.drawImage(buffer, 0, 0, this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM