2012-03-25 42 views

回答

21

您可以通過獲取任何組件的WindowAncestor來獲取對JOptionPane的引用,然後在返回的窗口上調用dispose()setVisible(false)。該窗口可以通過使用SwingUtilities.getWindowAncestor(component)

來獲得。例如:

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

import javax.swing.*; 

public class CloseOptionPane { 

    @SuppressWarnings("serial") 
    private static void createAndShowGui() { 
     final JLabel label = new JLabel(); 
     int timerDelay = 1000; 
     new Timer(timerDelay , new ActionListener() { 
     int timeLeft = 5; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      if (timeLeft > 0) { 
       label.setText("Closing in " + timeLeft + " seconds"); 
       timeLeft--; 
      } else { 
       ((Timer)e.getSource()).stop(); 
       Window win = SwingUtilities.getWindowAncestor(label); 
       win.setVisible(false); 
      } 
     } 
     }){{setInitialDelay(0);}}.start(); 

     JOptionPane.showMessageDialog(null, label); 

    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+1

沒有什麼比完美更.... – 2012-03-25 14:22:17

+1

有人可以從這個扣分,大聲笑,我不這麼認爲+1這個精心設計的例子:-) – 2012-03-25 14:23:03

+1

謝謝。但關鍵是在顯示JOptionPane之前調用所有必要的代碼。 – 2012-03-25 14:24:58

相關問題