【发布时间】: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 theJPanel? Remind thatpaintComponent` 每次需要painting时都会被调用,并且您正在重新创建每个这些资源绘画(然后可能在许多无用的情况下)。更喜欢仅在这些情况下捕获调整大小事件并创建资源。 -
“在面板中,我使用paintComponent 方法根据Jframe 的大小调整其元素的大小” - 这就是布局管理器的用途
标签: java swing paintcomponent