Java Swing How to - Create JOptionPane from an inner JPanel








Question

We would like to know how to create JOptionPane from an inner JPanel.

Answer

import java.net.URL;
/* ww w .  j  a  va2s .c o m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {
  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://www.java2s.com/style/download.png")));
    } catch (Exception mue) {
      mue.printStackTrace();
    }
    label.setIcon(image);

    JButton button = new JButton("EXIT");
    button.addActionListener(e -> dialog.dispose());

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

    return panel;
  }

  public static void main(String[] args) {
    new Main().displayGUI();

  }
}