0

I have a program that has multiple layers, in the bottom layer I have a JPanel that I have put a background image on. On top of this I have a JLayeredPane that has some draggable components. My problem is that when the user have uploaded a background image the draggable components are really lagging, my guess is that it's because of that swing is repainting the background image al the time when dragging. My question is if its anyway to make sure the image is not repainting all the time? My code where I paint the image looks like this:

if (this.getLoadedBackgroundImage() != null) {
        try {
            BufferedImage bufferedImage = ImageIO.read(this.getLoadedBackgroundImage());
            Image bImage = bufferedImage.getScaledInstance(this.getWidth() - 5 - jPanel6.getWidth() -5, this.getHeight() - jPanel2.getHeight() - jPanel3.getHeight() - tabPanel.getHeight(), Image.SCALE_FAST);
            graphics2d.drawImage(bImage, 5, jPanel2.getHeight() + tabPanel.getHeight()+5, null);
        } catch (IOException ex) {
            Logger.getLogger(MainViewLayeredPane.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

1 Answers1

1

Don't load or resize the image the paintComponent method, these are expensive operations, instead, pre-cache it and only paint the cached version

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • But if the size of the window is changed i need to calculate a new size for the image right? Or should I do that somewhere else on an windowChangeEvent or something like that then? – Ida Gustafsson Jul 25 '17 at 08:45
  • So? When the size of the window changes, calculate the new size, resize the image from the original and repaint - [For example](https://stackoverflow.com/questions/24318051/width-and-height-of-a-jpanel-are-0-specific-situation/24318121#24318121) – MadProgrammer Jul 25 '17 at 08:48