【问题标题】:my gui is taking too much resources in run time我的 gui 在运行时占用了太多资源
【发布时间】:2017-07-22 09:13:33
【问题描述】:

我有一个包含单个面板的 JFrame。 在面板中,我使用paintComponent 方法根据Jframe 的大小调整其元素的大小。 JPanel 的元素是作为背景的图像和包含 4 个 ImageIcon 并像按钮一样工作的 4 个 JLabel。 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)); 
  }
}

frame只有一个简单的方法add(myPanel)所以这里就不写了。 当我运行应用程序时,我需要大约 300 MB 的内存和大约 30% 的 CPU(Inter core i5-6200U),这对我来说非常不寻常,尤其是 CPU 的数量。是什么导致我的应用程序占用这么多资源,有什么办法可以减少它?

【问题讨论】:

  • 背景是什么?未在任何地方声明。
  • 我已经评论了声明的部分,这不是问题的重点
  • what are label1,ìmage1, button1? How are they in relation with the JPanel? Remind that paintComponent` 每次需要 painting 时都会被调用,并且您正在重新创建每个这些资源绘画(然后可能在许多无用的情况下)。更喜欢仅在这些情况下捕获调整大小事件并创建资源。
  • “在面板中,我使用paintComponent 方法根据Jframe 的大小调整其元素的大小” - 这就是布局管理器的用途

标签: java swing paintcomponent


【解决方案1】:

每当您重新绘制组件时,您都会更改标签的尺寸并创建资源(从它派生的 Image 和 ImageIcon)并将它们分配为新图标。这些是对应用程序可见部分的更改,因此必须重新绘制相关组件。基本上你的paintComponent方法

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

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

另见:

The API documentation on paintComponent(Graphics)

Painting in AWT and Swing

编辑:当您想根据其他组件的大小调整组件的大小时,请创建一个 ComponentListener 并通过调用 addComponentListener(ComponentListener) 将其添加到您要依赖的组件中。然后,只要大小发生变化,就会调用 ComponentListener 实例的 componentResized(ComponentEvent) 方法。

【讨论】:

  • 我理解那部分,但问题是,如果我不将它们放在paintComponent方法中,我还能如何根据框架的大小调整组件的大小
  • Zurmaa,你的解决方案很好,我现在刚试过,谢谢:)
猜你喜欢
  • 2020-07-22
  • 1970-01-01
  • 2011-11-21
  • 2010-09-14
  • 2014-09-20
  • 2022-11-23
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多