我用过
JOptionPane.showOptionDialog(null, new MyPanel(), "Import", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
因为我不想要OptionDialog提供的默认按钮而我在MyPanel extends JPanel
内部创建了我的按钮所以现在我的问题是如何从MyPanel
内部关闭该OptionDialog ActionEvent
?只要该对话框消失,我不关心返回值。我意识到这可能不是最好的设计,但我已经做了很多次这样的事情,所以我更喜欢一个修复,尽可能少地改变结构。谢谢!
答案 0 :(得分:3)
使用JOptionPane.createDialog(String title)
将JOptionPane
转换为JDialog
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();
}
});
}
}