繁体   English   中英

调整JFrame的大小时如何防止图像闪烁/移位?

[英]How can I stop an image from flickering/dislocating when a JFrame is resized?

我有一个JFrame。 在该JFrame中,我有一个JLayeredPane布局,其中的OverlayLayout包含多个Jpanel。 在那些JPanel之一中,我有一个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);
        }

    }

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM