簡體   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