gpt4 book ai didi

java - 在 Runnable 对象中启动和处理 JFrame,howto

转载 作者:行者123 更新时间:2023-11-30 09:05:34 24 4
gpt4 key购买 nike

处理在 Runnable 对象中创建的框架的正确方法是什么?

当在 LoadingRunnable 完成其构造函数之前调用 endDialog 时,下面的代码返回一个空指针异常。endDialog如何在构造函数结束后执行?

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class LoadingRunnable implements Runnable
{
private JFrame jFrame;

@Override
public void run()
{
jFrame = new JFrame("Window");
JPanel jPanel = new JPanel();
JLabel label = new JLabel("Loading...");
jPanel.add(label);
jFrame.setContentPane(jPanel);
jFrame.pack();
jFrame.setVisible(true);
}

public void endDialog()
{
jFrame.setVisible(false);
jFrame.dispose();
}

public static void main(String args[])
{
LoadingRunnable l = new LoadingRunnable();
SwingUtilities.invokeLater(l);
//work done here
l.endDialog();
}
};

最佳答案

这里有一个并发问题因为SwingUtilities.invokeLater()Event Dispatch Thread 中安排您的可运行类执行在您的 main 线程流仍在运行时异步执行,从而导致 NPE。

正确的处理框架的方法是通过事件,就像Swing被设计用来使用一样。例如,通过单击“X”(关闭)按钮或发送 WindowEvent :

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

您可能也想看看这个问题:Optional way to close a dialog window

此外

如果您只想在应用程序启动期间显示一些内容,那么您可以使用 SplashScreen API 而不是 JFrame。参见 How to Create a Splash Screen了解更多详情。

enter image description here

基于您的 previous question而这个新的,我建议你阅读整个 Concurrency in Swing了解 Swing 中常见的并发问题以及如何处理这些问题的教程。

关于java - 在 Runnable 对象中启动和处理 JFrame,howto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24805194/

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