在JFrame上显示JDialog(“请等待”)

6

我有一个JFrame,这个JFrame里面有一个JButton

我想要在JButton中先显示JDialog(显示“请等待”),然后再执行其他代码,最后关闭JDialog

但是当显示JDialog时,停止执行JButton上的其他代码。

4个回答

7

在一个 Thread 上启动其他处理(例如在 SwingWorker 中),并在开始时调用 modalDialog.setVisible(true)。在任务结束时调用 setVisible(false)


6
我建议创建一个简单的JDialog,在代码运行后进行处理。您可以使用以下代码创建JDialog:
JDialog dialog = new JDialog();
JLabel label = new JLabel("Please wait...");
dialog.setLocationRelativeTo(null);
dialog.setTitle("Please Wait...");
dialog.add(label);
dialog.pack();

然后像这样实现:

dialog.setVisible(true); // show the dialog on the screen

        // Do something here

dialog.setVisible(false); // set visibility to false when the code has run

在我看来,这是最好的答案。如果不需要,为什么要增加线程的额外复杂性呢? - Steve Smith
这很简单,但在某些情况下可能无法正常工作... javax.swing 创建或绘制框架需要很长时间。因此,如果 JVM 不等待 swing 完成其工作,则您的消息可能不可见。线程可能会继续执行 //在此处执行某些操作 - Roshana Pitigala

2
也许jdialog处于模态模式,尝试更改jdialog的modal属性:yordialog.setModal(false)

1

它停止了,因为您正在使用“MAIN-Thread”,该线程用于执行代码并显示JDialog。

要解决此问题,您应该查看类似于SwingWorker的东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接