gpt4 book ai didi

java - JPanel 的图形在左侧闪烁

转载 作者:行者123 更新时间:2023-12-02 05:01:26 25 4
gpt4 key购买 nike

我有一个java程序,它应该做一些非常简单的事情。它包含 JPanel ,其中repaint()每秒调用 30 次。这个JPanel覆盖 paintComponent()方法,在这个覆盖的方法中,我采用 BufferedImage并将其绘制到 JPanel。

这个BufferedImage由一个黑色图像组成,内部有一个较小的蓝色矩形。可以显示,但问题是屏幕左侧(50-80 像素左右)闪烁。在应该是蓝色矩形的最左侧部分,某些像素有时会显示为黑色,就好像有一些黑色覆盖层从屏幕左侧延伸覆盖它一样,每帧都会闪烁一点。

我不认为仅仅绘制一个矩形会如此耗时,以至于会导致类似这样的图形错误;是吗?我不明白为什么会发生这种情况,所以你们中有人知道什么会导致 BufferedImage 左侧出现黑色“闪烁”吗?或Graphics2D

“可运行示例(请添加导入)”:

public class Panel extends JPanel{
public int width, height;
public long lastTime;
public BufferedImage canvas;
public Panel(int a, int b){
width = a;
height = b;
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
lastTime = System.currentTimeMillis();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.drawImage(canvas, 0, 0, this);
}
public void drawRect(int startX, int startY, int w, int h, int color){
for(int i=0; i<w; i++){
for(int j=0; j<h; j++){
canvas.setRGB(i + startX, j + startY, color);
}
}
}
public void render(){
drawRect(0, 0, width, height, 0x000000);
drawRect(10, 10, width - 20, height - 20, 0x0000ff);
}
public void update(){
int delta = (int)(System.currentTimeMillis() - lastTime);
if(delta >= 1000 / 30){
render();
lastTime = System.currentTimeMillis();
}
}

//in a different class, contains main()

public class Main{
public static Panel pan;
public static void main(String[] args){
JFrame frame = new JFrame();
Container c = frame.getContentPane();
c.setPreferredSize(500, 500);
pan = new Panel(500, 500);
frame.add(pan);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new runThread().run();
}
class runThread extends Thread{
public void run(){
while(true){
pan.update();
}

}
}
}

最佳答案

由于您的程序在多种方面同步不正确,因此结果是不确定的。 Swing GUI 对象必须event dispatch thread 上构造和操作。 ;在所有受支持的平台上,这是必需的。正如 How to Use Swing Timers 中所讨论的,这个example以 50 Hz 运行,无闪烁。

I have a 15-class program…

在较大的程序中,您可以使用引用的方法之一搜索 EDT 违规情况 here 。另请查看建议的动画技术 here .

关于java - JPanel 的图形在左侧闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28257902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com