问题
I used
JOptionPane.showOptionDialog(null, new MyPanel(), "Import", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
because I don't want the default buttons provided by the OptionDialog and I created my buttons inside the MyPanel extends JPanel
So my problem is now how can I close that OptionDialog from inside the MyPanel
fired by an ActionEvent
? I don't care the return value, as long as that dialog disappears. And I realize this might not be the best design but I've been working on this for a lot of times so I'd prefer a fix that involves as little change in the structure as possible. Thanks!
回答1:
Convert JOptionPane
to a JDialog
, using 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);
Now inside the actionPerformed(ActionEvent ae)
method, simply write :
dialog.dispose();
Have a look at this working example :
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();
}
});
}
}
来源:https://stackoverflow.com/questions/17782933/java-return-from-a-showoptiondialog-from-an-inner-jpanel