Java Swing How to - Change the JOptionPane Icon








Question

We would like to know how to change the JOptionPane Icon.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
/*w w w  .j a  v  a2  s. co m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {
  JPanel options = new JPanel(new GridLayout(0, 3));
  Object[] items;

  public Main() {
    options.add(createOptionPane("Plain Message", JOptionPane.PLAIN_MESSAGE));
    options.add(createOptionPane("Error Message", JOptionPane.ERROR_MESSAGE));
    options.add(createOptionPane("Information Message",
        JOptionPane.INFORMATION_MESSAGE));
    options
        .add(createOptionPane("Warning Message", JOptionPane.WARNING_MESSAGE));
    options.add(createOptionPane("Want to do something?",
        JOptionPane.QUESTION_MESSAGE));
    items = new Object[] { "First", "Second", "Third" };
    JComboBox choiceCombo = new JComboBox(items);
    options.add(new JOptionPane(choiceCombo, JOptionPane.QUESTION_MESSAGE,
        JOptionPane.OK_CANCEL_OPTION), "Question Message");
    JFrame frame = new JFrame("JOptionPane'Options");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(options, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }

  static JOptionPane createOptionPane(String message, int type) {
    JOptionPane pane = new JOptionPane(message, type);

    if (type == JOptionPane.QUESTION_MESSAGE) {

      pane.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
    }
    return pane;
  }

  public static void main(String[] args) {
    Main test = new Main();
  }
}