Reputation: 111
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
Reputation: 44404
super.paintComponent(g)
at the beginning of your paintComponent method.repaint()
and remove the sleep. Neither of those should ever be called in a paint method under any circumstances.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