2015-04-04 93 views
1

three circlesjava drawOval重复圆圈

当重画圆圈时,窗口未被清除;新的圈子会被添加到现有的内容中。

目标是创建三个圆圈,每个颜色一个。

线程调用绘制具有不同半径的圆的移动函数。

public void run() { 
    try { 
      while(true){ 
       box.removeAll(); 
       move(); 
       box.removeAll(); 
       sleep(500); 
      } 
    } catch (InterruptedException e) { 
    } 
} 

public synchronized void move() { 
    Graphics g = box.getGraphics(); 
    g.setXORMode(box.getBackground()); 

    x1= one.x + ofset; 
    y1= one.y + ofset; 

    System.out.println("My Point ("+ x1 + " , " + y1 +")"); 

    g.setColor(Color.green); 
    g.drawOval(pointA.x-(int)distance1, pointA.y-(int)distance1, (int)distance1*2, (int)distance1*2); 

    g.setColor(Color.blue); 
    g.drawOval(pointB.x-(int)distance2, pointB.y-(int)distance2, (int)distance2*2, (int)distance2*2); 

    g.setColor(Color.red); 
    g.drawOval(pointC.x-(int)distance3, pointC.y-(int)distance3, (int)distance3*2, (int)distance3*2); 

    g.dispose(); 
} 
+0

什么是“盒子”?你正在使用哪个GUI?你的问题缺乏背景。 – RealSkeptic 2015-04-04 17:03:40

回答

2

首先,不建议您采用这种方法。但是,如果您只想要一个快速且脏的修补程序,则必须在绘制圆之前清除面板。

Graphics g = box.getGraphics(); 
g.clearRect(0, 0, box.getWidth(), box.getHeight()); // this should do it 
g.setXORMode(box.getBackground()); 
+0

谢谢你。那一条线改变了一切 – Murad 2015-04-08 14:11:34

+0

很高兴能有所帮助。但我真的建议遵循camickr的建议:只需在你的方法中更新你的值,并在'paintComponent'中完成所有的绘图。 – 2015-04-08 14:14:16

0
Graphics g = box.getGraphics(); 

号不使用的getGraphics()。任何使用该Graphics对象完成的绘制只是临时的,并且随时会被删除Swing确定组件需要重新绘制。

对于风俗画重写JPanel的的getPreferredSize()方法:

@Override 
protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); // clears the background 

    // add your custom painting here 
} 

另外,不要忘记你的覆盖面板的getPreferredSize()方法。请阅读有关Custom Painting的Swing教程中的部分以获取更多信息。