Java Swing How to - Install Custom Buttons for JOptionPane








Question

We would like to know how to install Custom Buttons for JOptionPane.

Answer

import java.awt.Component;
import java.awt.Container;
/*from www.j a  va2  s . co m*/
import javax.swing.AbstractButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    String[] options = { "Button 1", "Button 2", "Button 3" };

    JOptionPane myOptionPane = new JOptionPane("Heres a test message",
        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options,
        options[2]);
    JDialog myDialog = myOptionPane.createDialog(null, "My Test");
    myDialog.setModal(true);

    inactivateOption(myDialog, options[1]);

    myDialog.setVisible(true);
    Object result = myOptionPane.getValue();
    System.out.println("result: " + result);

  }

  private static void inactivateOption(Container container, String text) {
    Component[] comps = container.getComponents();
    for (Component comp : comps) {
      if (comp instanceof AbstractButton) {
        AbstractButton btn = (AbstractButton) comp;
        if (btn.getActionCommand().equals(text)) {
          btn.setEnabled(false);
          return;
        }
      } else if (comp instanceof Container) {
        inactivateOption((Container) comp, text);
      }
    }

  }
}