gpt4 book ai didi

java - JFrame 组件的这种奇怪的延迟是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:09 24 4
gpt4 key购买 nike

编辑:虽然我在今天之前从未使用过(甚至不知道)SwingUtilities.InvokeLater(),但实现它并没有解决问题。 JFrame 的可见性和 JLabel 的外观之间存在 1 秒的延迟,这一点在以下更新的代码中仍然存在。

public class DelayTest {

public static void main(String [] args) {
new DelayTest();
}

public DelayTest() {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
long start = System.currentTimeMillis();
JFrame frame = new JFrame("Demo");
Container content = frame.getContentPane();

//sizing
Dimension dimm = new Dimension(500, 200);
frame.setPreferredSize(dimm);
frame.setResizable(false);

//content
content.add(new JLabel("Hello, Delayed World"));
System.out.println("Added Label at: " +
(System.currentTimeMillis() - start) + " Milliseconds");

//end
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println("Finished execution at: " +
(System.currentTimeMillis() - start) + " Milliseconds");
}
});
}
}

到目前为止,我已执行以下操作来尝试解决该错误:

  • 更新了我的计算机 (Mac OS X 10.11.6)
  • 更新了 Java(Java 版本“1.8.0_111”)
  • 删除并重新安装 Eclipse (Java Neon.2)
  • 导出jar,只是为了看看Eclipse之外是否存在问题
  • 使用 SwingUtilities.InvokeLater() 进行测试,如上所示(希望我正确使用了它)

在整个过程中我重新启动了几次,但似乎没有任何解决办法。我希望您可以帮助我找到代码中导致标签延迟的错误(我认为该错误不存在),或者验证我的代码是否可以在您的计算机上运行。

最佳答案

事实证明,通过为 content 容器指定 LayoutManager ,我的问题立即得到了解决。我现在假设这是一个奇怪的 Java bug,也许只在 Mac 上。以下代码解决了我的问题:

public class DelayTest {

public static void main(String [] args) {
new DelayTest();
}

public DelayTest() {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//long start = System.currentTimeMillis();
JFrame frame = new JFrame("Demo");
Container content = frame.getContentPane();

//NEW CODE
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
//END NEW CODE

//sizing
Dimension dimm = new Dimension(500, 200);
frame.setPreferredSize(dimm);
frame.setResizable(false);

//content
content.add(new JLabel("Hello, Delayed World"));

//end
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

}
});
}
}

拥有一个不使用一个布局管理器或另一个布局管理器的 GUI 几乎完全没有意义,这解释了为什么我以前从未见过这个问题。

TL;DR:即使您只需要在窗口中显示一个组件,也始终使用 LayoutManager(显然还有 SwingUtilities.invokeLater())。

关于java - JFrame 组件的这种奇怪的延迟是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com