如何在调整JFrame大小时停止图像闪烁/错位?

时间:2015-06-07 19:07:04

标签: java paintcomponent drawimage

我有一个JFrame。在那个JFrame中,我有一个JLayeredPane,其中包含一个包含多个Jpanel的OverlayLayout。在其中一个JPanels中,我有一个BufferedImage。调整JFrame的大小后,图像会快速消失并移位,然后再次跳回,再次移位,再次移回,等等。

我已经尝试了很多东西来阻止图像闪烁,但我不知道问题的根本原因是什么。

保存图像的Jpanel包含以下代码来渲染图像:

protected void paintComponent (Graphics g) {
    super.paintComponent(g);
    g.drawImage(myBufferedImage, 0, 0, 200, 200, null);
}  

在尝试重建和简化问题时,我得到了我想要的工作版本。我仍然不知道我的其他代码有什么问题。 这是有效的代码:

import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Main {

    public Main() {
        // Create the JFrame:
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(600, 400);
        window.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        // Create the pane to hold layers:
        JLayeredPane layers = new JLayeredPane();
        layers.setLayout(new OverlayLayout(layers));
        // Add two layers:
        layers.add(new MyGraphics());
        layers.add(new MyImage());
        //
        window.add(layers);
        window.setVisible(true);
    }

    public static void main(String[] args) {
        Main app = new Main();
    }


    public class MyImage extends JPanel {

        public BufferedImage source;

        public MyImage () {
            this.setPreferredSize(new Dimension(180,180));
            this.setLocation(0,0);
            try {
                this.source = ImageIO.read(new File("image.jpg"));
            } catch (IOException ie) {
                ie.printStackTrace();
            }
        }       

        protected void paintComponent (Graphics g) {
            super.paintComponent(g);
            g.drawImage(this.source, 0, 0, 180, 180, null);
        }

    }

    public class MyGraphics extends JPanel {

        public MyGraphics () {
            this.setOpaque(false);
            this.setPreferredSize(new Dimension(180,180));
            this.setLocation(0,0);
        }

        protected void paintComponent (Graphics g) {
            super.paintComponent(g);
            g.drawLine(0, 0, 180, 180);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

尝试在构造函数中添加以下代码行:

public FlickerDemo()
   {
      // No flickering during resize
      System.setProperty("sun.awt.noerasebackground", "true");
   }
相关问题