[英]How can I stop an image from flickering/dislocating when a JFrame is resized?
I have a JFrame. 我有一个JFrame。 Within that JFrame I have a JLayeredPane layed out with an OverlayLayout that contains multiple Jpanels. 在该JFrame中,我有一个JLayeredPane布局,其中的OverlayLayout包含多个Jpanel。 in one of those JPanels I have a BufferedImage. 在那些JPanel之一中,我有一个BufferedImage。 When the JFrame is resized, the image quickly dissapears and dislocates, then it jumps back again, dislocates again, back again, and so on. 调整JFrame的大小后,图像会快速消失并移位,然后再次跳回,再次移位,再次返回,依此类推。
I have tried a lot of things to stop the image from flickering, but I don't know what the cause of the problem exactly is. 我已经尝试了很多方法来防止图像闪烁,但是我不知道到底是什么原因造成的。
The Jpanel that holds the image contains the following code to render the image: 保存图像的Jpanel包含以下代码以呈现图像:
protected void paintComponent (Graphics g) {
super.paintComponent(g);
g.drawImage(myBufferedImage, 0, 0, 200, 200, null);
}
In trying to reconstruct and simplify the problem, I got a working version of what I wanted. 在尝试重建和简化问题时,我得到了想要的工作版本。 I still don't know what the problem is with my other code though. 我仍然不知道其他代码有什么问题。 This is the code that works: 这是有效的代码:
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);
}
}
}
Try adding below line of code in constructor: 尝试在构造函数中添加以下代码行:
public FlickerDemo()
{
// No flickering during resize
System.setProperty("sun.awt.noerasebackground", "true");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.