Search code examples
javaswinggraphics2d

Drawing an unknown number of shapes


The program is supposed to draw circles at the points where the user clicks. At the moment, it only draws 5 circles. I would like to know, how to modify this piece of code so that it can draw circles without restrictions. Consider a scenario where i do not know about the number of circles i am supposed to draw. Here goes my code:

public class DrawingBoard {

public static void main(String[] args){

    new LookAndFeel();

}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

}

class LookAndFeel extends JPanel{

JFrame f;
int n = 0;
double points[][] = new double[6][5];
EventManager EMobj = new EventManager();

public LookAndFeel(){
    f = new JFrame("Drawing Board");
    f.setBounds(0,0,1920,1080);
    f.add(this);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    f.setResizable(false);
    addMouseListener(EMobj);

}

public void paintComponent(Graphics g){

    g.setColor(Color.RED);

    if(n >= 1)
        g.fillOval((int)points[0][0], (int)points[1][0], 80, 80);
    if(n >= 2)
        g.fillOval((int)points[1][1], (int)points[2][1], 80, 80);
    if(n >= 3)
        g.fillOval((int)points[2][2], (int)points[3][2], 80, 80);
    if(n >= 4)
        g.fillOval((int)points[3][3], (int)points[4][3], 80, 80);
    if(n >= 5)
        g.fillOval((int)points[4][4], (int)points[5][4], 80, 80);       
    if(n==5)
        removeMouseListener(EMobj);
}

class EventManager extends MouseAdapter{


    public void mouseClicked(MouseEvent e){

        points[n][n] = e.getX();
        points[n+1][n] = e.getY();
        n++;
        repaint();

    }
}

}


Solution

  • Check out Custom Painting Approaches

    It shows the two common ways to do this:

    1. Keep an ArrayList of Objects to paint and then iterate through the List in the paintComponent() method.

    2. Paint directly to a BufferedImage and then just display the BufferedImage.