一次显示多个 MessageDialog

show multiple MessageDialog at a time

我正在尝试制作一个程序,一次显示 3 个 MessageDialog 框。我想如果你把 JOPtionPane.showMessageDialog 放在 actionListner class 中,swing timer,它会每秒显示一个新的 MessageDialog 框。

这是我想出的代码:

package pracatice;

import java.awt.event.*;

import javax.swing.*;

public class practice extends JFrame 
{
    public static int num = 0;
    public static TimerClass tc = new TimerClass();
    public static Timer timer = new Timer(1000, tc);
    public JPanel panel = new JPanel();
    public JButton btn = new JButton("press");

    public practice()
   {
        setSize(100,100);
        setTitle("Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setPanel();
        setVisible(true);   
  }
     public void setPanel()
     {
        btn.addActionListener(new listener());
        panel.add(btn);

        add(panel);
    }

    public class listener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            num = 0;
            System.out.println("starting timer");
            timer.start();
        }
    }

      public static class TimerClass implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Adding 1 to num");
            num++;
            JOptionPane.showMessageDialog(null,"Test");
           if(num == 3)
           {
                System.out.println("stopping the timer");
                timer.stop();
            }
       }
 }  

 public static void main(String[] args)
 {
    practice p = new practice();
    System.out.println("created an instance of practice");
 }

}

它有效,但不是我想要的方式。不是每秒显示一个新框,而是在您按上一个框的确定后 1 秒显示一个新框。

所以当我按下 "press" 时,它会等待 1 秒并生成盒子。当我按下 "ok" 时,它会等待 1 秒并生成另一个,依此类推。知道如何让 3 个盒子一个接一个地生成吗?

创建对话框的方法 (JOptionPane.show...) return 直到用户以某种方式关闭对话框。鉴于 Swing 是单线程的,在此之前不会发生其他 Swing 进程。如果您希望同时打开三个对话框,请使用 non-modal 对话框。

当使用 JOptionPane 的 showX 方法时,您正在创建模态(阻塞且一次一个)对话,如文档所述。 您可以通过手动创建而不是使用 showX 方法直接使用 JOptionPane。

手动创建一个新的并将其设置为非模态:

optionPane = new JOptionPane(...);
dialog = optionPane.createDialog(null, "the title");
dialog.setModal(false);
dialog.show();