我在一本书中看到了这个例子,并且工作正常,但唯一的问题是背景不会在第一次调用绘画时变黑,当 clearCounter 变为 == 5,然后在绘画时再次清除屏幕启动,然后背景变为黑色。
public class apletprg extends JApplet implements ActionListener
{
int clearCounter;
Timer t;
public void init(){
setBackground(Color.black);
clearCounter = 0;
Timer t = new Timer(1000, this);
t.start();
}
public void paint(Graphics g)
{
setBackground(Color.black);
clearCounter++;
Graphics2D g2 = (Graphics2D) g;
if (clearCounter == 5){
g2.clearRect(0, 0, 500, 400);
clearCounter=0;
}
for (int i = 1; i <= 40; i++) {
Color c = chooseColor();
g2.setColor(c);
Font f = chooseFont();
g2.setFont(f);
drawJava(g2);
}
}
public void actionPerformed(ActionEvent ae){
repaint();
}
public Color chooseColor(){
int r= (int) (Math.random() * 255);
int g= (int) (Math.random() * 255);
int b= (int) (Math.random() * 255);
Color c = new Color(r,g,b);
return c;
}
public Font chooseFont(){
int fontChoice = (int) (Math.random() * 4) + 1;
Font f = null;
switch (fontChoice) {
case 1: f = new Font("Serif", Font.BOLD + Font.ITALIC, 20);break;
case 2: f = new Font("SansSerif", Font.PLAIN, 17);break;
case 3: f = new Font("Monospaced", Font.ITALIC, 23);break;
case 4: f = new Font("Dialog", Font.ITALIC, 30);break;
}
return f;
}
public void drawJava(Graphics2D g2){
int x = (int) (Math.random() * 500);
int y = (int) (Math.random() * 400);
g2.drawString("Adnan", x, y);
}
}
我知道 Init () 在开始时只调用一次,但为什么不能在开始时改变背景?