Java Swing How to - Center JOptionPane icon








Question

We would like to know how to center JOptionPane icon.

Answer

//from w w w.  j a  v a 2 s . c o  m
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) throws Exception {
    ImageIcon icon = new ImageIcon(new URL(
        "http://www.java2s.com/style/download.png"));
    JLabel iconLabel = new JLabel(icon);
    JPanel iconPanel = new JPanel(new GridBagLayout());
    iconPanel.add(iconLabel);

    JPanel textPanel = new JPanel(new GridLayout(0, 1));
    for (int i = 0; i < 15; i++) {
      textPanel.add(new JLabel("Hello"));
    }

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(textPanel);
    mainPanel.add(iconPanel, BorderLayout.WEST);
    JOptionPane.showMessageDialog(null, mainPanel, "Center Image Dialog",
        JOptionPane.PLAIN_MESSAGE);
  }
}