Ski
Ski

Reputation: 111

Painting a black square

I'm trying to repaint a black square across the panel, and when it reaches 400 pixel it goes to the next row, but the problem is, the first block of black square does not start at x equals to 0. It starts at x equals to 1 for some reason. The rest of the rows starts at 0. I don't know what I'm doing wrong. Please help.

package events;

import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class Paint extends JPanel {

int x = 0;
int y = 0;

static Paint g = new Paint();

public void paintComponent(Graphics g) {

    int r1 = Use.rand(0, 255); //My own Use.rand method which returns a random number
    int g1 = Use.rand(0, 255);
    int b1 = Use.rand(0, 255);
    Color color = new Color(0, 0, 0);
    g.setColor(color);

    if (x == 400) {
        x = 0;
        y += 50;
    }
    int i1 = x;
    int i2 = y;
    int i3 = 50;
    int i4 = 50;
    g.fill3DRect(i1, i2, i3, i4, true);
    x++;

    repaint();

    try {
        Thread.sleep(10);
    } catch (InterruptedException ex) {
        Logger.getLogger(Paint.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

Upvotes: 0

Views: 608

Answers (1)

VGR
VGR

Reputation: 44404

  1. You must call super.paintComponent(g) at the beginning of your paintComponent method.
  2. Remove the call to repaint() and remove the sleep. Neither of those should ever be called in a paint method under any circumstances.
  3. You don't get to control when a component is painted. The system controls it. Paint requests can happen for a number of reasons, and often your code will be painting just part of the component (in which case, the Graphics object's clip may be set before your method is called). Since you may be doing a partial paint, changing the values used for painting may only take effect in part of the component; the effect will look like garbage. You cannot rely on the invocation of paintComponent to trigger your changing of your values. Consider doing that in a Timer instead, and calling repaint() in the Timer task.

You will probably find the custom painting tutorial and the Painting in AWT and Swing article informative.

Upvotes: 2

Related Questions