Java JFrame重新绘制图像闪烁

Java JFrame重新绘制图像闪烁,java,swing,jframe,awt,Java,Swing,Jframe,Awt,我对super.paintComponents(g)命令有问题;更新JFrame时。我遇到的问题是,我加载的图像在代码运行时闪烁。我很确定代码是双缓冲的,并且没有在网上找到任何有用的资源来解决这个问题。这是我的第一个问题,所以请容忍任何格式错误 以下是我的全部代码(以下是代码片段): 您可能只想看到以下内容: 我的绘画方法: @Override public void paint(Graphics g) { super.paintComponents(g); for (int i

我对super.paintComponents(g)命令有问题;更新JFrame时。我遇到的问题是,我加载的图像在代码运行时闪烁。我很确定代码是双缓冲的,并且没有在网上找到任何有用的资源来解决这个问题。这是我的第一个问题,所以请容忍任何格式错误

以下是我的全部代码(以下是代码片段):

您可能只想看到以下内容:

我的绘画方法:

@Override
public void paint(Graphics g) {
    super.paintComponents(g);
    for (int i = 0; i < images.size(); i++) {
        g.drawImage(images.get(i).img, images.get(i).xpos, images.get(i).ypos, null);
    }
}
(我添加了Thread.sleep,因为它似乎降低了闪烁发生的速率)

下面是正在发生的事情的gif图(我刚刚使用了第一个谷歌结果对图像进行了“测试”):


我感谢任何帮助和一般建议,以改善我的代码。谢谢。

不要覆盖顶级容器的
paint
,例如
JFrame
没有双缓冲区,而是使用
JPanel
并覆盖其
paintComponent
方法<默认情况下,code>JPanel是双缓冲的

然后,将面板添加到所需的容器中

在进行任何自定义绘制之前,不要忘记调用它的
super
方法(
super.paintComponent

请仔细查看和了解有关Swing中绘画工作方式的更多详细信息

这只是您不应该(从
JFrame
扩展)覆盖顶级容器的
paint
的原因之一,请查看


更多信息

“我如何在中间设置?”很好的演示。重新。错误的命令。一幅画能描绘千言万语@安德烈·霍姆普森有时是简单的事情;)谢谢你快速准确的回答,这对我帮助很大。我真的很感激。“你可能只想看到……”。
public class Images {

String name;
BufferedImage img;
int xpos;
int ypos;

public Images (String Name) throws IOException{
    name = Name;
    xpos = 40;
    ypos = 90;
    System.out.println(name);
    System.out.println("PATH: " + GAME.class.getResource(name));
    URL file = getClass().getClassLoader().getResource(name);
    img = ImageIO.read(file);
}
}
@Override
public void paint(Graphics g) {
    super.paintComponents(g);
    for (int i = 0; i < images.size(); i++) {
        g.drawImage(images.get(i).img, images.get(i).xpos, images.get(i).ypos, null);
    }
}
Images test = new Images("unnamed.png");
    images.add(test);
    while (true) {
        if (lastKeyPressed == "LEFT") {
            test.xpos -= 5;
            lastKeyPressed = null;
        } else if (lastKeyPressed == "RIGHT") {
            test.xpos += 5;
            lastKeyPressed = null;
        } else if (lastKeyPressed == "UP") {
            test.ypos -= 5;
            lastKeyPressed = null;
        } else if (lastKeyPressed == "DOWN") {
            test.ypos += 5;
            lastKeyPressed = null;
        }
        frame.repaint();
        Thread.sleep(100);
    }