spacitron
spacitron

Reputation: 459

Can't make repaint() work

My class looks like this.

import java.awt.*;
import javax.swing.*;

public class Painter extends JPanel {
    int x=200;
    int y=200;
    int newX;
    int newY;

    Painter(){
           setPreferredSize(new Dimension(400,400));
    }

    public void moveSquare(int newX, int newY){
           if(newY != y|| newX != x){
                repaint(x,y, 10, 10);
                y = newY;
                x = newX;
                repaint(x,y, 10, 10);
           }        
    }

    public void paintComponent(Graphics g){
           super.paintComponent(g);
           g.setColor(Color.BLACK);
           g.fillRect(x, y, 10, 10);
    }
}

The methods are called from another class. The values for x and y do change the way they should. However the square does not move. Have I done something wrong here?

EDIT Yes, I am calling "super". I just deleted it accidentally when I copied and edited the code here. Now edited it back in.

Upvotes: 2

Views: 145

Answers (2)

obataku
obataku

Reputation: 29636

Calling repaint(x, y, w, h) only sets a select region as dirty; Graphics sets a clip around this boundary, and thus you will only see changes occur there. Using repaint() without any arguments will mark the entire area as dirty :-)

According to an Oracle article on AWT paint (found here),

When AWT invokes this method, the Graphics object parameter is pre-configured with the appropriate state for drawing on this particular component:

  • The Graphics object's color is set to the component's foreground property.
  • The Graphics object's font is set to the component's font property.
  • The Graphics object's translation is set such that the coordinate (0,0) represents the upper left corner of the component.
  • The Graphics object's clip rectangle is set to the area of the component that is in need of repainting.

To test this, try printing out g.getClip :-)

I'll give you a hint...

java.awt.Rectangle[x=0,y=0,width=10,height=10]
java.awt.Rectangle[x=0,y=0,width=10,height=10]
java.awt.Rectangle[x=0,y=0,width=10,height=10]

Here's a fixed moveSquare...

public void moveSquare(int newX, int newY){
  if (newY != y|| newX != x) {
    y = newY;
    x = newX;
    repaint();
  }        
}

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

You need to call super.paintComponent(g) rather than paintComponent(g)

in

public void paintComponent(Graphics g) 

otherwise you will loop indefinitely.

Upvotes: 4

Related Questions