paint only paints one obj
I'm just starting Java Swing and I want to create circles so I have a class that draws only circles and a constructor to set size and starting point, then in main, I create a new JFrame and add this obj. It's working, but when I try to add more circle objs to my JFrame, it doesn't show up. I know it's trivial...
Code :
import javax.swing.*;
import java.awt.*;
public class Circle extends JPanel
{
private int starting_x;
private int starting_y;
private int width;
private int height;
public Circle(int x, int y,int w, int h)
{
this.starting_x = x;
this.starting_y = y;
this.width = w;
this.height = h;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillOval(start_x-1, start_y-1, width+2, height+2);
}
}
Code :
//main in another file
import javax.swing.*;
public class Runner
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.add( new Circle(100,100,34,34) );//this shows
f.add( new Circle(300,305,34,34) );//this doesn't show though
f.setVisible(true);
f.setSize(1000,1000);
}
}
Re: paint only paints one obj
You don't want to have multiple JPanels drawing single things at a time- you want to have a single JPanel drawing multiple things at a time.
Think of a JPanel as a canvas. What you're doing is hanging up a canvas, drawing a circle on it, then hanging up another canvas right on top of the first one and drawing a circle on it- see why you can only see one circle at a time?
(Technically I think that might be backwards- you might only be seeing the first thing you add, but the idea is the same.)