I have written the following example to give something runnable of a problem I am having. When you press the button the controlWhichImage switches to 2. The problem is that when
Use img
obj since its already instantiated but not createdImage
obj, createdImage
contains null
since its just declared but not instantiated. If you use createdImage
obj means if you perform any operation upon createdImage
obj then you will get NullPointerException
.
Graphics g2 = this.img.getGraphics();
---------
Of course! You have to go and paint the image at the outskirts. Please use this
g.drawImage(this.createdImage, 0, 0, this.createdImage.getWidth(),this.createdImage.getHeight(),null);
The problem is that getGraphics
(or better named createGraphics
) is called outside the if
statement, also for 2, hence both causing a resource leak (as no g2.dispose
is called), and also a clean slate.
if (controlWhichImage == 1) {
Graphics g2 = createdImage.getGraphics();
g2.drawImage(img,0,0,img.getWidth(),img.getHeight(),null);
g2.dispose();
}
Also do things like loading the image outside the paint code.
See this question if you want to know how to copy an BufferedImage: How to copy BufferedImage