0

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
DLJ
  • 333
  • 2
  • 6
  • 19

1 Answers1

4

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).

Vincent van der Weele
  • 12,927
  • 1
  • 33
  • 61
  • Thanks but when I do that, it gives me a `java.lang.StackOverflowError`. I don't know why. – DLJ Jul 16 '13 at 09:48
  • @DLJ I didn't make it explicit, but I removed the call to `paintComponent(g);` from `paintComponent`. You should do the same :) (or have it as `super.paintComponent(g)`) – Vincent van der Weele Jul 16 '13 at 09:49
  • @DLJ : Try to override [getPreferredSize()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getPreferredSize()) and make it return some valid `Dimension` object, just like you overriding `paintComponent(...)` method, e.g. [this answer](http://stackoverflow.com/a/17573406/1057230) – nIcE cOw Jul 16 '13 at 13:40