public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
ImageIcon img = new ImageIcon("images/20303.png");
img.paintIcon(this, g, 0, 0);
g2.setColor(Color.red);
g2.drawRect(ax - 3, ay - 3, 6, 6);
g2.setColor(Color.green);
g2.drawLine(ax - 10, ay, ax + 10, ay);
g2.drawLine(ax, ay - 10, ax, ay + 10);
g2.setColor(Color.blue);
g2.drawString("当前坐标:" + ax + "|" + ay, 400, 500);
this.repaint();
}
我先在一个JPanel中添加一张背景图,即 20303.png,对该面板添加了鼠标移动点击等事件的监听,ax,ay为获取到的鼠标当前坐标,期望达到的效果是当鼠标点击时在面板上绘制出一个准星,但是当调用repaint()方法之后,背景图也被重绘,从而遮挡了上次绘制的准星.
我的问题是如何让背景图不重绘,只重绘准星.
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
ImageIcon img = new ImageIcon("images/20303.png");
img.paintIcon(this, g, 0, 0);
g2.setColor(Color.red);
g2.drawRect(ax - 3, ay - 3, 6, 6);
g2.setColor(Color.green);
g2.drawLine(ax - 10, ay, ax + 10, ay);
g2.drawLine(ax, ay - 10, ax, ay + 10);
g2.setColor(Color.blue);
g2.drawString("当前坐标:" + ax + "|" + ay, 400, 500);
this.repaint();
}
我先在一个JPanel中添加一张背景图,即 20303.png,对该面板添加了鼠标移动点击等事件的监听,ax,ay为获取到的鼠标当前坐标,期望达到的效果是当鼠标点击时在面板上绘制出一个准星,但是当调用repaint()方法之后,背景图也被重绘,从而遮挡了上次绘制的准星.
我的问题是如何让背景图不重绘,只重绘准星.
http://topic.csdn.net/u/20090809/02/40e3e02e-f9c0-4cdc-a972-ce415e4f4d75.html?48105记住:用JFrame 做父类, 画法paint(Graphics g)中 的第一句代码 super.paint(g);的作用是抹去上一幁的图画。不要这句话,则不会抹去以往的图画。
请试用此法。
Cf course, the core for painting your images should be in the same code block as the super.pain(g) so that both may be excicuted once only.
That is :If (deletePrevious) {
super.paint(g);
g.drawImage(img, 0,0,this);
…
}祝你成功!Every success!