我想知道使 JOptionPane 样式的普通消息框在显示一定秒数后消失的最佳方法是什么。
我正在考虑从主 GUI 线程启动一个单独的线程(使用计时器)来执行此操作,以便主 GUI 可以继续处理其他事件等。但是我实际上如何制作消息框这个单独的线程消失并正确终止线程。谢谢。
编辑:这就是我按照下面发布的解决方案得出的结论
package util;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
public class DisappearingMessage implements ActionListener
{
private final int ONE_SECOND = 1000;
private Timer timer;
private JFrame frame;
private JLabel msgLabel;
public DisappearingMessage (String str, int seconds)
{
frame = new JFrame ("Test Message");
msgLabel = new JLabel (str, SwingConstants.CENTER);
msgLabel.setPreferredSize(new Dimension(600, 400));
timer = new Timer (this.ONE_SECOND * seconds, this);
// only need to fire up once to make the message box disappear
timer.setRepeats(false);
}
/**
* Start the timer
*/
public void start ()
{
// make the message box appear and start the timer
frame.getContentPane().add(msgLabel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer.start();
}
/**
* Handling the event fired by the timer
*/
public void actionPerformed (ActionEvent event)
{
// stop the timer and kill the message box
timer.stop();
frame.dispose();
}
public static void main (String[] args)
{
DisappearingMessage dm = new DisappearingMessage("Test", 5);
dm.start();
}
}
现在的问题是,由于我打算在用户和主 GUI 之间的整个交互过程中创建此类的多个实例,我想知道 dispose() 方法是否每次都能正确清理所有内容。否则,我最终可能会在内存中积累大量冗余对象。谢谢。
最佳答案
我认为在您的情况下,您不能使用任何 JOptionPane
静态方法 (showX...
)。您必须改为创建一个 JOptionPane
实例,然后从中创建一个 JDialog
并自己显示该 JDialog
。一旦你有了 JDialog
,你就可以强制它的可见性。
// Replace JOptionPane.showXxxx(args) with new JOptionPane(args)
JOptionPane pane = new JOptionPane(...);
final JDialog dialog = pane.createDialog("title");
Timer timer = new Timer(DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
// or maybe you'll need dialog.dispose() instead?
}
});
timer.setRepeats(false);
timer.start();
dialog.setVisible(true);
我还没有尝试过,所以我不能保证它有效,但我认为它应该有效 ;-)
当然,这里的 Timer
是 javax.swing.Timer
,正如其他人已经提到的,因此您确定操作将在 EDT 中运行并且您赢了在创建或终止您自己的 Thread
时遇到任何问题。
关于java - 在 Java 中创建一个几秒钟后消失的普通消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966005/