1.问题
在写一个放大缩小图片的小应用,我发现在缩小后,会有原来的图片残留。
下面是我继承jpanel
类绘制的图片
因为我担心内存溢出问题,所以重写了绘制的方法
public class ZPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private Image image;
private Image copyImage;
private int imgWidth;
private int imgHeight;
public Image getCopyImage() {
return copyImage;
}
public int getImgWidth() {
return imgWidth;
}
public void setImgWidth(int imgWidth) {
this.imgWidth = imgWidth;
}
public int getImgHeight() {
return imgHeight;
}
public Image getImage() {
return image;
}
public void setImgHeight(int imgHeight) {
this.imgHeight = imgHeight;
}
public ZPanel() {
}
public void setImagePath(String imgPath) {
try {
// 该方法会将图像加载到内存,从而拿到图像的详细信息。
image = ImageIO.read(new FileInputStream(imgPath));
if (copyImage == null){
copyImage = ImageIO.read(new FileInputStream(imgPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
setImgWidth(image.getWidth(this));
setImgHeight(image.getHeight(this));
}
public void setImage(BufferedImage bufferedImage) {
image = bufferedImage;
setImgWidth(image.getWidth(this));
setImgHeight(image.getHeight(this));
}
@Override
public void paintComponent(Graphics g1) {
int x = 0;
int y = 0;
Graphics g = (Graphics) g1;
if (null == image) {
return;
}
g.drawImage(image, x, y, image.getWidth(this), image.getHeight(this),
this);
g = null;
}
}
因为这是直接画在画板上的,所以,removeAll()
,等清除组件的方法通通没用
下面是残留的效果
2.尝试解决
果然是java快淘汰的玩意,许多博客都停留在起码7年前,很多都是10年前的,当初c站的实力毋容置疑
Graphics g; //画板很容易拿到
g.clearRect(0,0,4000,4000);
通过使用当前绘图表面的背景色进行填充来清除指定的矩形
实际上jpael是类似画图的工具,既然有画笔自然有橡皮,这个方法相当于是橡皮的作用,对改区域进行背景色填充,实现消除画板图片
public void paintComponent(Graphics g1) {
int x = 0;
int y = 0;
Graphics g = (Graphics) g1;
if (null == image) {
return;
}
g.clearRect(0,0,4000,4000);
g.drawImage(image, x, y, image.getWidth(this), image.getHeight(this),
this);
g = null;
}