Reputation: 147
I have this program that draw a circle with every click, my problem is that it erase the circle when I click somewhere else. How can I make the program keep the circle without erasing the previous one ? I also want to create a button that erase all circles, is there is a method that erase everything ?
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");
}
}
}
Upvotes: 2
Views: 205
Reputation: 3454
you have a list of circles, that look unused to me - whenever you click you add a circle but you only draw a circle where you click...
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);
}
}
use this approach to add circles to your screen - if you want to remove them, make a button or any other event and call xxx.clear()
which cleans the list (don't forget to repaint()
after clearing the list...
Upvotes: 3