2012-03-23 31 views
1

我有一個在關閉我的應用程序時顯示的選項窗格(windowClosing())。 我有退出,最小化或取消的選項。取消選項窗格

如何在不關閉整個應用程序的情況下關閉選擇「取消」的選項窗格?

Object[]options = {"Minimize", "Exit","Cancel"}; 

     int selection = JOptionPane.showOptionDialog(
      null, "Please select option", "Options", 0, 
      JOptionPane.INFORMATION_MESSAGE, null, options, options[1]); 
     System.out.println(selection); 

     switch(selection) 
     { 
      case 2: 
      { 
       // do something 
      } 
     } 
+0

請發佈你正在做的事情的全部代碼,當調用JOptionPane時,等等。 – Marcelo 2012-03-23 11:42:52

回答

3

你可以叫你yourFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);方法windowClosing()裏面,如果用戶選擇 「取消」 ....

+1

我明白了......謝謝,對不起 – Arianule 2012-03-23 11:44:31

+1

你可以選擇這個作爲正確答案。 – 2012-03-23 11:48:56

+1

+1,我只是意識到,我理解錯誤的意義上的問題:-) – 2012-03-23 11:53:53

2
If (selection == JOptionPane.CANCEL_OPTION) 
{ 
    // DO your stuff related to cancel click event. 
} 
1

Oracle documentation給出了一個提示:

 final JDialog dialog = new JDialog(frame, 
            "Click a button", 
            true); 
     dialog.setContentPane(optionPane); 
     dialog.setDefaultCloseOperation(
      JDialog.DO_NOTHING_ON_CLOSE); 
     dialog.addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent we) { 
       setLabel("Thwarted user attempt to close window."); 
      } 
     }); 
     optionPane.addPropertyChangeListener(
      new PropertyChangeListener() { 
       public void propertyChange(PropertyChangeEvent e) { 
        String prop = e.getPropertyName(); 

        if (dialog.isVisible() 
        && (e.getSource() == optionPane) 
        && (prop.equals(JOptionPane.VALUE_PROPERTY))) { 
         //If you were going to check something 
         //before closing the window, you'd do 
         //it here. 
         dialog.setVisible(false); 
        } 
       } 
      }); 
     dialog.pack(); 
     dialog.setVisible(true); 

     int value = ((Integer)optionPane.getValue()).intValue(); 
     if (value == JOptionPane.YES_OPTION) { 
      setLabel("Good."); 
     } else if (value == JOptionPane.NO_OPTION) { 
      setLabel("Try using the window decorations " 
        + "to close the non-auto-closing dialog. " 
        + "You can't!"); 
     } 

您必須刪除默認關閉操作並添加您自己的監聽器,然後使用setVisible(false)關閉它。