2013-07-22 28 views
3

我用Java的回報來自內部的JPanel

 
JOptionPane.showOptionDialog(null, 
     new MyPanel(), 
     "Import", 
     JOptionPane.DEFAULT_OPTION, 
     JOptionPane.PLAIN_MESSAGE, 
     null, new Object[]{}, null); 

,因爲我不想被OptionDialog提供的默認按鈕和我創造了我的MyPanel extends JPanel內按鈕所以我的問題是,現在怎麼可以從MyPanel內部關閉那個OptionDialog,由ActionEvent開啓?只要對話消失,我不在乎返回值。而且我意識到這可能不是最好的設計,但我一直在爲此工作很多次,所以我更喜歡修復,儘可能減少結構變化。謝謝!

+0

只是想澄清,你不喜歡按鈕,因爲o f L&F?因爲我假設你知道我們可以傳入我們自己的按鈕文本? – user2507946

+0

@ user2507946是的,我知道。單擊時默認按鈕將關閉對話框。我不想那樣。 – YankeeWhiskey

回答

3

轉換JOptionPaneJDialog,使用JOptionPane.createDialog(String title)

JOptionPane optionPane = new JOptionPane(getPanel(), 
         JOptionPane.PLAIN_MESSAGE, 
         JOptionPane.DEFAULT_OPTION, 
         null, 
         new Object[]{}, null); 
dialog = optionPane.createDialog("import"); 
dialog.setVisible(true); 

現在actionPerformed(ActionEvent ae)方法中,簡單地寫:

dialog.dispose(); 

看一看這個工作例如:

import java.awt.*; 
import java.awt.event.*; 
import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.URL; 
import javax.swing.*; 
import javax.imageio.ImageIO; 

public class JOptionPaneExample 
{ 
    private JDialog dialog; 

    private void displayGUI() 
    { 
     JOptionPane optionPane = new JOptionPane(getPanel(), 
         JOptionPane.PLAIN_MESSAGE, 
         JOptionPane.DEFAULT_OPTION, 
         null, 
         new Object[]{}, null); 
     dialog = optionPane.createDialog("import"); 
     dialog.setVisible(true); 
    } 

    private JPanel getPanel() 
    { 
     JPanel panel = new JPanel(); 
     JLabel label = new JLabel("Java Technology Dive Log"); 
     ImageIcon image = null; 
     try 
     { 
      image = new ImageIcon(ImageIO.read(
        new URL("http://i.imgur.com/6mbHZRU.png"))); 
     } 
     catch(MalformedURLException mue) 
     { 
      mue.printStackTrace(); 
     } 
     catch(IOException ioe) 
     { 
      ioe.printStackTrace(); 
     } 
     label.setIcon(image); 

     JButton button = new JButton("EXIT"); 
     button.addActionListener(new ActionListener() 
     { 
      @Override 
      public void actionPerformed(ActionEvent ae) 
      { 
       dialog.dispose(); 
      } 
     }); 

     panel.add(label); 
     panel.add(button); 

     return panel; 
    } 
    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new JOptionPaneExample().displayGUI(); 
      } 
     }); 
    } 
} 
+0

@YankeeWhisky:請注意,我已經改變了一些選項,從你的'JOptionPane'在這裏和那裏,儘管它們仍然存在。 –