java joptionpane,几秒后自动关闭

sne*_*iar 2 java swing popup joptionpane

制作弹出窗口几秒钟后自动关闭所需的帮助.JOptionpane消息通常需要输入才能关闭,所以有没有其他方法来处理java中的自动关闭弹出窗口.请帮忙.提前致谢.

Use*_*er0 8

如果选项窗格可以是无模式的,这可能是一种方法:

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.JOptionPane;
import javax.swing.Timer;

public class AutoCloseJOption {

    private static final int TIME_VISIBLE = 3000;

    public static void main(String[] args) {

        final JFrame frame1 = new JFrame("My App");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setSize(100, 100);
        frame1.setLocation(100, 100);

        JButton button = new JButton("My Button");
        frame1.getContentPane().add(button);

        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane pane = new JOptionPane("Message", JOptionPane.INFORMATION_MESSAGE);
                JDialog dialog = pane.createDialog(null, "Title");
                dialog.setModal(false);
                dialog.setVisible(true);

                new Timer(TIME_VISIBLE, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                    }
                }).start();
            }
        });

        frame1.setVisible(true);

    }
}
Run Code Online (Sandbox Code Playgroud)

对于此示例,按下按钮,将显示一个选项对话框三秒钟.

  • 是的,你是对的.我更新了示例以使用javax.swing.Timer (2认同)