我正在寻找让用户在JPanel上设置新背景图片的有效方法。我有一个为自定义面板类创建的方法,但我不太确定它的效率。这是方法:
public void setBackgroundImage(String imagePath){
try{
File imageFile = new File(imagePath);
image = ImageIO.read(imageFile);
JLabel backgroundImage = new JLabel(new ImageIcon(image));
backgroundImage.setBounds(0, 0, 800, 600); // temporarily here
add(backgroundImage);
}
catch(IOException e){
e.printStackTrace();
}
}
我想问的第一件事是,这个方法是否会在每次执行时在内存中创建越来越多的垃圾?如果是这样,我能做些什么来阻止这种情况吗?
我想有一点我还不了解对象创建。对象是否被破坏,就像局部变量在方法的末尾一样?