我试图在面板上重新绘制一个黑色正方形,当它达到400像素时会转到下一行,但问题是,第一个黑色正方形块不会从x开始等于0由于某种原因,它从x等于1开始。其余的行从0开始。我不知道我做错了什么。请帮忙。
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);
}
}
}
答案 0 :(得分:2)
super.paintComponent(g)
。repaint()
的呼叫并删除睡眠。在任何情况下都不应该用油漆方法调用它们。paintComponent
的调用来触发您的值的更改。请考虑在Timer中执行此操作,并在Timer任务中调用repaint()
。您可能会发现custom painting tutorial和Painting in AWT and Swing文章信息丰富。