2015-04-04 94 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教程中的部分以獲取更多信息。