我的gui在运行时占用了太多资源

Joa*_*epi 2 java swing paintcomponent

我有一个包含单个面板的JFrame.在面板中,我使用paintComponent方法根据Jframe的大小调整其元素的大小.JPanel的元素是一个图像作为背景和4 JLabel,它结合了4个ImageIcon并像按钮一样工作.Jpanel的paintComponent方法如下所示

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)); 
  }
}
Run Code Online (Sandbox Code Playgroud)

框架只有一个简单的方法,添加(myPanel),所以我没有在这里写.当我运行应用程序时,它需要大约300 MB的RAM和大约30%的CPU(Inter core i5-6200U),这对我来说非常不合适,特别是CPU的数量.是什么导致我的应用程序占用了这么多资源,有什么办法可以减少它吗?

Bjö*_*aar 5

每当重新绘制组件时,都会更改标签的尺寸并创建资源(图像和从中派生的ImageIcon)并将其指定为新图标.这些是对应用程序可见部分的更改,因此必须重新绘制有问题的组件.基本上是你的paintComponent方法

  1. 每次被调用时都会导致重绘,从而有效地创建无限循环
  2. 是非常重量级的,因为它分配昂贵的资源.

这两点都是非常糟糕的想法.您的paintComponent方法应该只是名称所暗示的,即绘制组件.所有导致重绘的操作(更改图标或文本,在树中添加或删除组件等)都不得在其中发生.

也可以看看:

关于paintComponent(Graphics)的API文档

在AWT和Swing中绘画

编辑:当您想要根据其他组件的大小调整组件大小时,创建一个ComponentListener并通过调用addComponentListener(ComponentListener)将其添加到您想要依赖的组件.然后,ComponentListener实例将在大小更改时调用其componentResized(ComponentEvent)方法.