java - 切换JFrame但闪屏

标签 java jframe

如何在不闪屏的情况下在 1 个 JFrame 之间切换到另一个 JFrame?切换代码是什么?我用这段代码来切换...

JFrame2 ref = new JFrame2();
ref.setVisible(true);
this.setVisible(false)

是的,它运行并切换到 JFrame2,但问题是切换到 JFrame 2 时屏幕闪烁。

最佳答案

我建议您制作自定义 JPanel 并更新它,而不是使用新的 JFrame

将 swing 组件拆分并分组到 JPanels 中,然后调用

panel.revalidate();

panel.repaint();

您可能还想设置

panel.setDoubleBuffered(true); // for smooth transition.

参见Oracle's doc了解更多信息。

这是一个简单的例子。

public static void main(String[] args) throws IOException {

    JFrame f = new JFrame("Frame");
    f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    f.setSize(300, 300);
    
    File file = new File("src/stackoverflow/index.png");
    customPanel pane = new customPanel();
    pane.setDoubleBuffered(true);
    pane.setImage(ImageIO.read(file));
    f.add(pane);
    f.setVisible(true);
    
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    file = new File("src/stackoverflow/index1.png");
    pane.setImage(ImageIO.read(file));
    pane.repaint();
}

static class customPanel extends JPanel{
    BufferedImage image;
    
    public void setImage(BufferedImage image) {
        this.image = image;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

关于java - 切换JFrame但闪屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124892/

相关文章:

java - 如何在Frame中添加JPanel

java - 仅当调用构造函数时才显示框架

Java JNA-Jar应用程序在32位Windows系统中挂起

java - 动态添加类型到 jaxb 上下文

java - 将 setVisible() 函数放在函数的开头是否与我将它放在该函数的末尾有所不同?

java - 带有连接的查询结果在转换为 POJO 列表时会丢失顺序

java - 如何以流式传输方式迭代巨大 XML 中的节点?

java - 将静态方法与 JFrame 结合使用

java - 如何反转 'java.util.stack'变量内容

java - 手动降级 9.0.83 Google Play 服务以避免 DynamiteModule : Failed to load module descriptor