0
我创建了一个JFrame并绘制矩形1x1的大小,每个矩形都是来自随机生成器的RGB值的随机颜色。当我运行代码时,框架绘制所有的矩形,但几秒钟后,框架中的矩形会改变。Java JFrame绘制像素大小矩形
Rectangle类:
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");
}
}
“说完抽奖” 被打印两次。
的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扔,看看它调用矩形类两次,它是,但我不知道为什么!谁能帮忙?
您可能会发现多次调用“paintComponent(Graphics)”。尝试将矩形渲染为图像并将其显示在标签中。 –