我正在创建一个 JFrame 并绘制大小为 1x1 的矩形,每个矩形都是来自随机生成器的 RGB 值的随机颜色。当我运行代码时,框架会绘制所有矩形,但几秒钟后,框架中的矩形会发生变化。
矩形类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.*;
public class RandomRect extends JComponent
{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g)
{
Random rand = new Random();
Graphics2D g2 = (Graphics2D) g;
for(int y=1; y<601; y++)
{
for(int x=1; x<1201; x++)
{
float red = rand.nextFloat();
float green = rand.nextFloat();
float blue = rand.nextFloat();
Color randomColor = new Color(red, green, blue);
Rectangle box = new Rectangle(x, y, 1, 1);
g2.setColor(randomColor);
g2.fill(box);
}
}
System.out.println("Finished draw");
}
}
“Finished draw”正在打印两次。
RectViewer 类:
import java.awt.Color;
import javax.swing.*;
public class RectViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame ();
frame.setSize(1200,600);
frame.setTitle("Using the Rectangle Class");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.white);
RandomRect rect = new RandomRect();
frame.add(rect);
frame.setVisible(true);
}
}
我扔了一个 println 看它是否调用了矩形类两次,但我不知道为什么!任何人都可以帮忙吗?