有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 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();
        }
    }  
    
  2. # 2 楼答案

    我尝试了这些答案,遇到了这样一个问题:显示对话框是一个阻塞调用,因此计时器无法工作。下面是关于这个问题的讨论

          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);
    
  3. # 3 楼答案

    我的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
      }
    }
    
  4. # 4 楼答案

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

  5. # 5 楼答案

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

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

    然后,你可以显示对话框,并启动计时器,在10秒钟后隐藏它