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()方法之后,背景图也被重绘,从而遮挡了上次绘制的准星.
我的问题是如何让背景图不重绘,只重绘准星.

解决方案 »

  1.   

    repaint不是还有一个方法吗,用x,y为参数,重绘局部区域
      

  2.   

    我刚好发了一贴,内容详见:
    http://topic.csdn.net/u/20090809/02/40e3e02e-f9c0-4cdc-a972-ce415e4f4d75.html?48105记住:用JFrame 做父类, 画法paint(Graphics g)中 的第一句代码 super.paint(g);的作用是抹去上一幁的图画。不要这句话,则不会抹去以往的图画。
    请试用此法。
      

  3.   

    当然, 绘制你的背景图片的代码也应放到 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!