Reputation: 1413
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?
Upvotes: 0
Views: 84
Reputation: 324118
Take a look at Custom Painting Approaches which shows the two common ways to do this:
List
of objects to paint and then iterate through the List in your paintComponent()
method.The link contains working examples of each approach.
Upvotes: 1
Reputation: 376
The thing is paintComponent doesn't work for top level containers such as JFrame call super.paint(); or instead you could just make a panel and add it to the frame and just override paintcomponent as you know it rest of the implementation is okkk to me
Upvotes: 0
Reputation: 347214
paint
and then call super.paintComponent
, override the paintComponent
method instead and then call super.paintComponent
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 existspaint
method of top level containers, instead, start by creating a custom component which extends from something like JPanel
and follow step 1...setX/setY
), these are doing what you think they shouldList
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.Upvotes: 3