简体   繁体   中英

my gui is taking too much resources in run time

I have a JFrame which contains a single panel. In the panel I use the paintComponent method to resize its elements according the size of Jframe. The elements of the JPanel are an image as a background and 4 JLabel that cointains 4 ImageIcon and work like buttons. The method paintComponent of Jpanel is like below

public class MyPanel extends JPanel
{ 
    //Declarations
    private BufferedImage backGround;
   public MyPanel()
   {
      //Some code here
   }

   public void paintComponent(Graphics graphics)
    {
        super.paintComponent(graphics);
        Graphics2D graphics2d = (Graphics2D) graphics;

        if(backGround != null)
        {
            graphics2d.drawImage(backGround, 0, 0, getWidth(), getHeight(), this);
        }

        /* This code is repeated 4 times because I have 4 labels */
        label1.setSize(getWidth()/7 , getHeight()/10);
        label1.setLocation(getWidth()/2 - getWidth()/14 , getHeight()/3 );
        image1 = button1.getScaledInstance(label1.getWidth(), label1.getHeight(),
                Image.SCALE_SMOOTH);
        label1.setIcon(new ImageIcon(image1)); 
  }
}

The frame has just a simple method , add(myPanel) so I did not write it here. When I run the application , it takes me around 300 MB of ram and around 30% of CPU (Inter core i5-6200U) , which is quite unsual for me , expecially the amount of CPU. What is causing my application to take so much resources and is there any way I can reduce it ?

Whenever you repaint your component you change your labels' dimensions and create resources (the Image and the ImageIcon derived from it) and assign them as a new icon. These are changes to visible parts of your application and hence must cause repainting the components in question. Basically your paintComponent method

  1. causes a repaint every time it is called effectively creating an endless loop and
  2. is very heavyweight because it allocates expensive resources.

Both of these points are pretty bad ideas. Your paintComponent method should do just what the name suggests, ie painting the component. All actions that cause a repaint (changing icons or text, adding or removing components from the tree etc.) must not occur in it.

See also:

The API documentation on paintComponent(Graphics)

Painting in AWT and Swing

EDIT: When you want to resize components dependent on the size of other components create a ComponentListener and add it to the component you want to depend on by calling addComponentListener(ComponentListener) . The ComponentListener instance will then have its componentResized(ComponentEvent) method called whenever the size changes.

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