add and remove ellipse2D from instance of JPanel object

Hello.

I have a instance of a JPanel class where i draw an elipse. What i'm trying to do is to add and remove more ellipses from the JPanel object from outside the class.

Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.geom.Line2D.Double;
import java.util.concurrent.*;

public class DrawBugElement extends JPanel{
	int posX = 0;
	int posY = 0;
	
	public DrawBugElement (int posX, int posY){
		this.posX = posX;
		this.posY = posY;
	}
	
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		Ellipse2D bug = new Ellipse2D.Double(this.posX, this.posY, Main.scale, Main.scale);
		g2.fill(bug);
	}
	public void setPos(int posX, int posY){
		this.posX = posX;
		this.posY = posY;
		repaint();
	}
	
}

Open in new window


And here is the code where i would like to add more ellipses from (The constructor of a much bigger class). See the comment:
public Bug(Chromosome chromosome, int posX, int posY){
		this.chromosome = chromosome;
		this.posX = posX;
		this.posY = posY;
                bugElement gridElement = new DrawBugElement ();
		bugElement .posX = this.posX;
		bugElement .posY = this.posY;
                //Here i would like to do something like:
                //gridElement.add(new Ellipse2D.Double(50, 50, 50, 50));
		Main.mainFrame.add(bugElement );
	}

Open in new window


I cant figure out how to do this?
HaugenwebdesignAsked:
Who is Participating?
 
CEHJCommented:
You could do something like

a. give Bug a method
public draw (Graphics g);

Open in new window

b. In DrawBugElement:

private List<Bug> bugs;
...
public void addBug(Bug b) {
   if(bugs == null) {
      bugs = new ArrayList<Bug>(); // lazy init
   }
   bugs.add(b);
}
public void paintComponent(Graphics g){
   super.paintComponent(g);
   for(Bug b : bugs) {
      b.draw(g);
   }
}
...

Open in new window

0
 
DhaestCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.