/* Hello I am working on this program that requires me to draw circles on a Jpanel using the PaintComponent method.
So far my circles show up, but I need to keep track of them, so I've decided to use an Arraylist to add them. With every mouse click, a new circle appears, but my Arraylist only shows me the current circle object and not the previous object after a new click. I've already looked at similar questions on here, but nothing seems to work for me, next is my code so far*/
pane_main.add(myCircle,BorderLayout.CENTER);
myCircle.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
xstart= e.getX();
ystart = e.getY();
radius = (int) (Math.random()*100);
frame1.repaint();
}
public void mouseReleased(MouseEvent e){
xend = e.getX();
yend = e.getY();
if (xend < xstart) { int tmp = xstart; xstart = xend; xend = tmp; }
if (yend < ystart) { int tmp = ystart; ystart = yend; yend = tmp; }
Circle cr = new Circle(xcenter,ycenter,radius);
circleList.add(cr);//adding to list
}
});
myCircle.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent e){
if (Trackmouse){
int x = e.getX();
int y = e.getY();
printMsg("(" + x + ", " + y + ")");
}
}
});
frame1.setVisible(true);
}
//the class that has paint component
public class Circle extends JPanel {
public Circle(){
}
public Circle(int x,int y,int radius){
}
public int getCenterX(){
return xstart - radius;
}
public int getCenterY(){
return ystart - radius;
}
public int getRadius(){
return radius;
}
public void paintComponent(Graphics g) {
int red = (int)(256*Math.random());
int green = (int)(256*Math.random());
int blue = (int)(256*Math.random());
int width = this.getWidth();
int height = this.getHeight();
printMsg("H = " + height + ", w = " + width);
for (Circle circle: circleList){
int count = 1;
g.setColor(new Color(red, green, blue));
printMsg("Colors are: " + red + " - " + green + " - " + blue );
g.fillOval(getCenterX(),getCenterY(),getRadius() *2,getRadius() *2);
System.out.println("For circle object " + count + ": ");
System.out.println("Center coordinates are: (" + circle.getCenterX() + " ," + circle.getCenterY()+ " )");
System.out.println("Radius is: " + circle.getRadius());
++ count ;
}
}
}
}
/* H = 405, w = 584 Colors are: 17 - 96 - 230 For circle object 1: Center coordinates are: (202 ,94 ) Radius is: 25 H = 405, w = 584 Colors are: 78 - 137 - 123 For circle object 1: Center coordinates are: (97 ,289 ) Radius is: 5 Colors are: 78 - 137 - 123 For circle object 1: Center coordinates are: (97 ,289 ) Radius is: 5 Here is a sample output from running it, the first time the radius of the circle was 25, the second time the radius is 5 but it displays that result twice instead of the previous and current, any help or guidance would be greatly appreciated, thanks! */