Java绘图到JPanel图形,使用字节数组,白色闪烁
因此,我尝试使用具有指定字节/颜色的字节数组更新JPanel 这是一个非常简单的版本。 当我启动程序时,它会变成白色半秒钟,然后变成正确的颜色,然后在1秒钟后,它会变回白色,我试图打印出当前的颜色,有时它会变为“0”。 我做错了什么
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static Random ran = new Random();
public static byte[] buffer;
public static int num = 0;
public static JFrame frame = new JFrame();
public static JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
num = 0;
byte[] current_buffer = buffer.clone();
for (int y = 0; y < panel.getHeight(); y++) {
for (int x = 0; x < panel.getWidth(); x++) {
g.setColor(new Color(current_buffer[num], current_buffer[num], current_buffer[num]));
g.fillRect(x, y, 1, 1);
num++;
}
}
}
};
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200, 800);
frame.setLocationRelativeTo(null);
frame.setContentPane(panel);
frame.setResizable(false);
frame.setVisible(true);
engine.run();
}
public static boolean running = true;
public static Thread engine = new Thread() {
@Override
public void run() {
buffer = new byte[panel.getWidth() * panel.getHeight()];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (byte) 34;
}
while (running) {
panel.repaint(10L);
}
}
};
}
# 1 楼答案
没有真正理解你的逻辑:
将相同的值分配给缓冲区
然后使用相同的值创建颜色对象
所以每个像素都是相同的颜色
由于缓冲区总是使用相同的值构建,因此颜色不会改变
还有,你为什么要使用
您只是在使用缓冲区中的值,而不是更新缓冲区中的值,因此我认为没有理由进行克隆
不要使用带有while循环的线程。对于动画,您应该使用
Swing Timer
。当计时器触发时,更新缓冲区中的值,然后调用repaint()我看不出那种行为
上述观点之所以有意义,是因为:
你希望它做什么