Java从内部JPanel从ShowOptionDialog返回 [英] Java return from a ShowOptionDialog from an inner JPanel
问题描述
我用过
JOptionPane.showOptionDialog(null,
new MyPanel(),
"Import",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, new Object[]{}, null);
因为我不希望OptionDialog提供默认的按钮,而是在MyPanel extends JPanel
内部创建了按钮,所以现在的问题是如何从ActionEvent
触发的MyPanel
内部关闭OptionDialog?我不在乎返回值,只要该对话框消失即可.而且我意识到这可能不是最好的设计,但是我已经为此进行了很多次的尝试,因此,我希望采用一种结构更改尽可能少的修复程序.谢谢!
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!
推荐答案
使用JDialog
/javax/swing/JOptionPane.html#createDialog%28java.lang.String%29"rel =" nofollow> JOptionPane.createDialog(字符串标题):
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);
现在在actionPerformed(ActionEvent ae)
方法中,只需编写:
Now inside the actionPerformed(ActionEvent ae)
method, simply write :
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();
}
});
}
}
这篇关于Java从内部JPanel从ShowOptionDialog返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!