Java return from a ShowOptionDialog from an inner JPanel

China☆狼群 提交于 2019-12-06 02:41:36

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();
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!