Search code examples
javaswingdrawingpaintcomponentrepaint

How to draw a square when a button is pressed in java


I am writing a java program where you input a length and you input a width of a rectangle and it outputs the perimeter and area. But now, I want to draw the figure as well. But I don't know how to draw it when the button is pressed. Should it look like this?:

public void paintComponent(Graphics g) {
    paintComponent(g);
    g.setColor(Color.blue);
    g.drawRect(10, 10, 80, 30);      
}

public void actionPerformed(ActionEvent e) {
    paintComponent();
}

Because when I do that it gives me an error saying:

method paintComponent in class Rectangles cannot be applied to given types;
required: Graphics
found: no arguments

So I don't really know what to do.


Solution

  • No, you shouldn't call paintComponent directly. That method will be called automatically anyway, so the square would be drawn before you click.

    You could use a boolean flag to indicate that you clicked the button and call repaint() to post a repaint request:

    boolean clicked = false;
    
    public void paintComponent(Graphics g) {
        if (clicked) {
            g.setColor(Color.blue);
            g.drawRect(10, 10, 80, 30);
        }
    }
    
    public void actionPerformed(ActionEvent e){
        clicked = true;
        repaint();
    }
    

    Moreover, never let a method call itself with exactly the same parameters. This snipped

    public void paintComponent(Graphics g) {
        paintComponent(g);
    

    will call the same function infinitely often (or until the stack is full).

    I think you saw the following somewhere:

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
    

    That is ok, it will call the paint method of the super class. It probably doesn't do anything, so leaving it out shouldn't harm (but neither does keeping it).