user3764602 user3764602 -4 years ago 141
Java Question

Adding circles with different locations

I want to add circle on my

JFrame
every time that I click on a button the code should add another circle on frame but as I use the
repaint()
method it always draw one circle.

public void paint(Graphics g){
super.paintComponents(g);

Graphics2D g2= (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Ellipse2D.Double circle = new Ellipse2D.Double();
circle.width=50;
circle.height=50;
circle.x=getX();
circle.y=getY();
g2.draw(circle);
}

public static void main(String args[]){
new PaintComponents();
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bt){
String s=JOptionPane.showInputDialog("enter a number");
if(getX()==0){
setX(100);
setY(200);
repaint();
}
else {
setX(200);
setY(200);
repaint();
}
}
}


Here is the code. I want to add many circles. What should I do?

In this question my goal is to make a BST tree graphically by circles and line but I don't know how to add circles. I should show the Nodes in Jframe as circles step by step I mean that every time I add a node with an object it should make circle in the right location. How can I do this?

Answer Source
  1. Don't override paint and then call super.paintComponent, override the paintComponent method instead and then call super.paintComponent
  2. Graphics is a shared resource, it used by all the components been painted within a given paint cycle. Be careful when making changes to it, like setting the rendering hints, as these changes will effect all components painted after this one. You should be restoring the Graphics context back to it's previous state as much as possible before the paint method exists, better yet, create a copy of the Graphics context using Graphics#create, but don't forget to dispose of the copy before the paint method exists
  3. Don't override the paint method of top level containers, instead, start by creating a custom component which extends from something like JPanel and follow step 1...
  4. Don't modify the x/y position of the component (setX/setY), these are doing what you think they should
  5. Create a List of some kind. Into the list, add each instance of Ellipse2D. When paintComponent is called, run through the list and paint each instance of Ellipse2D. You won't be able to control the color, but you will get the circles to paint.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download