Java:显示10秒的消息对话框并删除?

时间:2011-06-30 05:05:41

标签: java swing

您好我想要JOptionPane.showMessageDialog(null, "Appication already running");

10秒然后删除它。我可以用dothat吗?

5 个答案:

答案 0 :(得分:8)

您可以手动创建JOptionPane,无需静态方法:

JOptionPane pane = new JOptionPane("Your message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(parent, "Title");

然后您可以显示对话框并启动计时器以在十秒钟后隐藏它。

答案 1 :(得分:7)

我尝试了这些答案并遇到了显示对话框是阻塞调用的问题,因此计时器无法正常工作。以下解决了这个问题。

      JOptionPane opt = new JOptionPane("Application already running", JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{}); // no buttons
  final JDialog dlg = opt.createDialog("Error");
  new Thread(new Runnable()
        {
          public void run()
          {
            try
            {
              Thread.sleep(10000);
              dlg.dispose();

            }
            catch ( Throwable th )
            {
              tracea("setValidComboIndex(): error :\n"
                  + cThrowable.getStackTrace(th));
            }
          }
        }).start();
  dlg.setVisible(true);

答案 2 :(得分:2)

我的Java有点生疏但你应该能够使用标准的Timer类:

import java.util.Timer;

int timeout_ms = 10000;//10 * 1000
Timer timer = new Timer();
timer.schedule(new CloseDialogTask(), timeout_ms);

//implement your CloseDialogTask:

class CloseDialogTask extends TimerTask {
  public void run() {
    //close dialog code goes here
  }
}

答案 3 :(得分:1)

// =====================
// yes = 0, no = 1, cancel = 2 
// timer = uninitializedValue, [x] = null  

public static void DialogBox() {

    JOptionPane MsgBox = new JOptionPane("Continue?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
    JDialog dlg = MsgBox.createDialog("Select Yes or No");
    dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dlg.addComponentListener(new ComponentAdapter() {
      @Override
      // =====================
      public void componentShown(ComponentEvent e) {
      // =====================
        super.componentShown(e);
        Timer t; t = new Timer(7000, new ActionListener() {
          @Override
          // =====================
          public void actionPerformed(ActionEvent e) {
          // =====================
            dlg.setVisible(false);
          }
        });
        t.setRepeats(false);
        t.start();
      }
    });
    dlg.setVisible(true);
    Object n = MsgBox.getValue();
    System.out.println(n);
    System.out.println("Finished");
    dlg.dispose();
    }
}  

答案 4 :(得分:0)

制作像JOptionPane这样的小框架,在线程中显示并在10秒后处理