java - 显示 JWindow 一段时间

标签 java multithreading swing concurrency jwindow

我想在 JWindow 中显示一条消息一段时间,所以我尝试使用 while() 和 sleep() 函数,但它不起作用。这是应该调用 JWindow (MessageWindow) 的函数。有没有其他方法可以让这个窗口显示2秒?

private void showJWindow() {
    boolean flag = true;
    final MessageWindow window = new MessageWindow( playerName, playerInAction );
    window.setVisible( true );

    try {
        synchronized( window ) {
            while( flag ) {
                window.wait( 3000 );
                flag = false;
                window.setVisible( false );
            }
        }

    } catch( InterruptedException ie ) {
        Thread.currentThread().interrupt();
    }
}

最佳答案

这是一个使用 Swing 计时器的简短示例。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestGUI {
    public TestGUI() {
        final JFrame frame = new JFrame("Test");
        JButton press = new JButton("Press Me");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(press);
        press.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                final JDialog dialog = new JDialog();
                dialog.add(new JLabel("Here for 2 seconds"));
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                Timer timer = new Timer(2000, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        dialog.dispose();
                    }
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestGUI();
            }
        });
    }
}

关于java - 显示 JWindow 一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22894094/

相关文章:

java - Swing 可以告诉我是否有 Activity 的工具提示吗?

java - Swing - 列表在 PaintComponent 方法内不起作用的问题

Java MouseListener transient

java - 在屏幕上打印重复循环

java - 如何让JPanel填满整个JFrame?

Python threading.Condition.notify_all() 不触发下一个线程

java - 如何在非事件派发线程中间提示确认对话框

java - Hibernate 与 struts2 集成 - session 为空

java - 将 Collection 与 ReplyingKafkaTemplate 结合使用时,相关 ID 会丢失

malloc 失败会导致死锁或竞争条件吗?