2014-10-09 85 views
2

我有這個程序,畫一個圓圈每點擊,我的問題是,它消除了一圈,當我點擊別的地方。我怎樣才能使程序保持圈而不擦除前一個?我也想創建一個按鈕,刪除所有圈子裏,有沒有被抹去這一切的方法?圖形對象和刪除這些

import javax.swing.JPanel; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.util.ArrayList; 
import java.util.Random; 

public class CircleObj extends JPanel { 
    private int rColor; 
    private int gColor; 
    private int bColor; 
    private int radius; 
    private Random rand = new Random(); 
    private int xStart; 
    private int yStart; 
    ArrayList <Circle> xxx ; 

    public CircleObj() { 
    xxx = new ArrayList<Circle>(); 

    addMouseListener(new MouseAdapter() { 

     public void mouseClicked (MouseEvent e) { 

     xStart = e.getX(); 
     yStart = e.getY(); 
     rColor = rand.nextInt(256); 
     gColor = rand.nextInt(256); 
     bColor = rand.nextInt(256); 
     radius = rand.nextInt(100); 
     xxx.add(new Circle(xStart, yStart,rColor, gColor, bColor, radius)); 
     System.out.println(xxx); 
     repaint(); 
     } 
    }); // end addMouseListener 

    } 

    public void paintComponent (Graphics g) { 
    super.paintComponent(g); 
    g.setColor(new Color(rColor, gColor, bColor)); 
    g.fillOval(xStart, yStart, radius, radius); 

    } 

    class Circle { 
     private int x; 
     private int y; 
     private int rad; 
     private int rcol; 
     private int gcol; 
     private int bcol; 

     public Circle (int xValue, int yValue,int redValue, int greenValue, int blueValue, int radValue) { 

      x = xValue; 
      y = yValue; 
      rad = radValue; 
      rcol = redValue; 
      gcol = greenValue; 
      bcol = blueValue; 
      } 


     public String toString(){ 

     return String.format("X value is: " + x + "\nY value is: " + y + "\nRadius value is: " +rad + 
        "\nRed value is: "+ rcol+ "\nGreen value is: "+ gcol + "\nBlue value is: "+bcol+ "\n\n"); 

     } 

    } 

} 
+0

另一種方法是繪製每個新元素在一個'JLabel'顯示的'BufferedImage'。每個添e圖像被更新,重新繪製標籤。 – 2014-10-09 08:25:35

回答

3

你有圓的清單,看起來不習慣我 - 只要你點擊你添加了一圈,但你只畫在那裏你點擊一個圓圈...

public void paintComponent (Graphics g) { 
    super.paintComponent(g); 
    //g.setColor(new Color(rColor, gColor, bColor)); 
    //g.fillOval(xStart, yStart, radius, radius); 
    for (Circle circle: xxx){ 
     g.setColor(new Color(circle.rcol, circle.gcol, circle.bcol)); 
     g.fillOval(circle.x, circle.y, circle.rad, circle.rad); 
    } 
} 

使用這種方法在你的屏幕上添加圓圈 - 如果你想刪除它們,做一個按鈕或任何其他事件,並呼籲xxx.clear()清理列表(清除清單後不要忘記repaint() ...

+0

非常感謝你 – iali87 2014-10-09 05:15:16

+0

可以接受的答案,如果它是有幫助的^^ – 2014-10-09 05:15:48

+0

雅知道...我想你的建議,它的工作:)謝謝 – iali87 2014-10-09 05:19:18