Java/Swing JFC/Dialog — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:39, 1 июня 2010

A frame that can easily support internal frame dialogs

  
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// DialogDesktop.java
//A frame that can easily support internal frame dialogs.
//
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DialogDesktop extends JFrame {
  public DialogDesktop(String title) {
    super(title);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final JDesktopPane desk = new JDesktopPane();
    setContentPane(desk);
    // Create our "real" application container; use any layout manager we
    // want.
    final JPanel p = new JPanel(new GridBagLayout());
    // Listen for desktop resize events so we can resize p. This will ensure
    // that
    // our container always fills the entire desktop.
    desk.addComponentListener(new ComponentAdapter() {
      public void componentResized(ComponentEvent ev) {
        Dimension deskSize = desk.getSize();
        p.setBounds(0, 0, deskSize.width, deskSize.height);
        p.validate();
      }
    });
    // Add our application panel to the desktop. Any layer below the
    // MODAL_LAYER
    // (where the dialogs will appear) is fine. We"ll just use the default
    // in
    // this example.
    desk.add(p);
    // Fill out our app with a few buttons that create dialogs
    JButton input = new JButton("Input");
    JButton confirm = new JButton("Confirm");
    JButton message = new JButton("Message");
    p.add(input);
    p.add(confirm);
    p.add(message);
    input.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        JOptionPane.showInternalInputDialog(desk, "Enter Name");
      }
    });
    confirm.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        JOptionPane.showInternalConfirmDialog(desk, "Is this OK?");
      }
    });
    message.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        JOptionPane.showInternalMessageDialog(desk, "The End");
      }
    });
  }
  // A simple test program
  public static void main(String[] args) {
    DialogDesktop td = new DialogDesktop("Desktop");
    td.setSize(350, 250);
    td.setVisible(true);
  }
}





An example of using the JOptionPane with a custom list of options in an

  
import javax.swing.JOptionPane;
public class ManyOptions {
  public static void main(String[] args) {
    JOptionPane.showInputDialog(null, "Please choose a name", "Example 1",
        JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Amanda",
            "Colin", "Don", "Fred", "Gordon", "Janet", "Jay",
            "Joe", "Judie", "Kerstin", "Lotus", "Maciek", "Mark",
            "Mike", "Mulhern", "Oliver", "Peter", "Quaxo", "Rita",
            "Sandro", "Tim", "Will" }, "Joe");
  }
}





Class to Prompt the User for an ID and Password

  
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Insets;
/**
 * Example from Chapter 3
 * 
 * Simple object to prompt for user id/password.
 * 
 * @author Jeff Heaton
 * @version 1.0
 */
public class SecurePrompt extends javax.swing.JDialog {
  public SecurePrompt(Frame parent) {
    super(parent, true);
    //{{INIT_CONTROLS
    setTitle("Security");
    getContentPane().setLayout(null);
    setSize(403, 129);
    setVisible(false);
    JLabel1.setText("User ID:");
    getContentPane().add(JLabel1);
    JLabel1.setBounds(12, 12, 48, 24);
    JLabel2.setText("Password:");
    getContentPane().add(JLabel2);
    JLabel2.setBounds(12, 48, 72, 24);
    _uid.setText("jheaton");
    getContentPane().add(_uid);
    _uid.setBounds(72, 12, 324, 24);
    _ok.setText("OK");
    getContentPane().add(_ok);
    _ok.setBounds(60, 84, 84, 24);
    getContentPane().add(_pwd);
    _pwd.setBounds(72, 48, 324, 24);
    _cancel.setText("Cancel");
    getContentPane().add(_cancel);
    _cancel.setBounds(264, 84, 84, 24);
    //}}
    //{{REGISTER_LISTENERS
    SymAction lSymAction = new SymAction();
    _ok.addActionListener(lSymAction);
    _cancel.addActionListener(lSymAction);
    //}}
  }
  public void setVisible(boolean b) {
    if (b)
      setLocation(50, 50);
    super.setVisible(b);
  }
  public void addNotify() {
    // Record the size of the window prior to calling parents addNotify.
    Dimension size = getSize();
    super.addNotify();
    if (frameSizeAdjusted)
      return;
    frameSizeAdjusted = true;
    // Adjust size of frame according to the insets
    Insets insets = getInsets();
    setSize(insets.left + insets.right + size.width, insets.top
        + insets.bottom + size.height);
  }
  // Used by addNotify
  boolean frameSizeAdjusted = false;
  //{{DECLARE_CONTROLS
  javax.swing.JLabel JLabel1 = new javax.swing.JLabel();
  javax.swing.JLabel JLabel2 = new javax.swing.JLabel();
  /**
   * The user ID entered.
   */
  javax.swing.JTextField _uid = new javax.swing.JTextField();
  /**
   */
  javax.swing.JButton _ok = new javax.swing.JButton();
  /**
   * The password is entered.
   */
  javax.swing.JPasswordField _pwd = new javax.swing.JPasswordField();
  javax.swing.JButton _cancel = new javax.swing.JButton();
  //}}
  class SymAction implements java.awt.event.ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent event) {
      Object object = event.getSource();
      if (object == _ok)
        Ok_actionPerformed(event);
      else if (object == _cancel)
        Cancel_actionPerformed(event);
    }
  }
  /**
   * Called when ok is clicked.
   * 
   * @param event
   */
  void Ok_actionPerformed(java.awt.event.ActionEvent event) {
    setVisible(false);
  }
  /**
   * Called when cancel is clicked.
   * 
   * @param event
   */
  void Cancel_actionPerformed(java.awt.event.ActionEvent event) {
    _uid.setText("");
    _pwd.setText("");
    setVisible(false);
  }
}





Confirmation dialog

  
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class OptionDialog {
  public static void main(String argv[]) {
    if (JOptionPane.showConfirmDialog(new JFrame(),
        "Do you want to quit this application ?", "Title",
        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
      System.exit(0);
  }
}





Create Color Sample Popup

  
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class CreateColorSamplePopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Create Popup Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    final JButton button = new JButton("Pick to Change Background");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color initialBackground = button.getBackground();
        final JColorChooser colorChooser = new JColorChooser(
            initialBackground);
        //        colorChooser.setPreviewPanel(new JPanel());
        final JLabel previewLabel = new JLabel("I Love Swing",
            JLabel.CENTER);
        previewLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC,
            48));
        colorChooser.setPreviewPanel(previewLabel);
        // Bug workaround
        colorChooser.updateUI();
        // For okay button selection, change button background to
        // selected color
        ActionListener okActionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            Color newColor = colorChooser.getColor();
            if (newColor.equals(button.getForeground())) {
              System.out.println("Color change rejected");
            } else {
              button.setBackground(colorChooser.getColor());
            }
          }
        };
        // For cancel button selection, change button background to red
        ActionListener cancelActionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            button.setBackground(Color.red);
          }
        };
        final JDialog dialog = JColorChooser.createDialog(null,
            "Change Button Background", true, colorChooser,
            okActionListener, cancelActionListener);
        // Wait until current event dispatching completes before showing
        // dialog
        Runnable showDialog = new Runnable() {
          public void run() {
            dialog.show();
          }
        };
        SwingUtilities.invokeLater(showDialog);
      }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}





Create simple about dialog

  
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SimpleAboutDialog extends JDialog {
  public SimpleAboutDialog(JFrame parent) {
    super(parent, "About Dialog", true);
    Box b = Box.createVerticalBox();
    b.add(Box.createGlue());
    b.add(new JLabel("Java source code, product and article"));
    b.add(new JLabel("By Java source and support"));
    b.add(new JLabel("At www.jexp.ru"));
    b.add(Box.createGlue());
    getContentPane().add(b, "Center");
    JPanel p2 = new JPanel();
    JButton ok = new JButton("Ok");
    p2.add(ok);
    getContentPane().add(p2, "South");
    ok.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        setVisible(false);
      }
    });
    setSize(250, 150);
  }
  public static void main(String[] args) {
    JDialog f = new SimpleAboutDialog(new JFrame());
    f.show();
  }
}





Creating and using Dialog Boxes

  
// : c14:Dialogs.java
// Creating and using Dialog Boxes.
// <applet code=Dialogs width=125 height=75></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
class MyDialog extends JDialog {
  public MyDialog(JFrame parent) {
    super(parent, "My dialog", true);
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(new JLabel("Here is my dialog"));
    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        dispose(); // Closes the dialog
      }
    });
    cp.add(ok);
    setSize(150, 125);
  }
}
public class Dialogs extends JApplet {
  private JButton b1 = new JButton("Dialog Box");
  private MyDialog dlg = new MyDialog(null);
  public void init() {
    b1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        dlg.show();
      }
    });
    getContentPane().add(b1);
  }
  public static void main(String[] args) {
    run(new Dialogs(), 125, 75);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~





Default button for dialog: press Enter to activate

  
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
public class DefaultButton extends JPanel {
  public DefaultButton() {
  }
  public static void main(String[] a) {
    JDialog f = new JDialog();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JButton btOK = new JButton("Press Enter to click me, I am the default.");
    btOK.setToolTipText("Save and exit");
    f.getRootPane().setDefaultButton(btOK);
    JPanel p = new JPanel();
    p.add(btOK);
    p.add(new JButton("I am NOT the default."));
    f.getContentPane().add(p);
    f.pack();
    f.setSize(new Dimension(300, 200));
    f.show();
  }
}





Dialog boxes and creating your own components

  
// : c14:TicTacToe.java
// Dialog boxes and creating your own components.
// <applet code=TicTacToe width=200 height=100></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TicTacToe extends JApplet {
  private JTextField rows = new JTextField("3"), cols = new JTextField("3");
  private static final int BLANK = 0, XX = 1, OO = 2;
  class ToeDialog extends JDialog {
    private int turn = XX; // Start with x"s turn
    ToeDialog(int cellsWide, int cellsHigh) {
      setTitle("The game itself");
      Container cp = getContentPane();
      cp.setLayout(new GridLayout(cellsWide, cellsHigh));
      for (int i = 0; i < cellsWide * cellsHigh; i++)
        cp.add(new ToeButton());
      setSize(cellsWide * 50, cellsHigh * 50);
      setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    class ToeButton extends JPanel {
      private int state = BLANK;
      public ToeButton() {
        addMouseListener(new ML());
      }
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int x1 = 0, y1 = 0, x2 = getSize().width - 1, y2 = getSize().height - 1;
        g.drawRect(x1, y1, x2, y2);
        x1 = x2 / 4;
        y1 = y2 / 4;
        int wide = x2 / 2, high = y2 / 2;
        if (state == XX) {
          g.drawLine(x1, y1, x1 + wide, y1 + high);
          g.drawLine(x1, y1 + high, x1 + wide, y1);
        }
        if (state == OO)
          g.drawOval(x1, y1, x1 + wide / 2, y1 + high / 2);
      }
      class ML extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
          if (state == BLANK) {
            state = turn;
            turn = (turn == XX ? OO : XX);
          } else
            state = (state == XX ? OO : XX);
          repaint();
        }
      }
    }
  }
  class BL implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JDialog d = new ToeDialog(Integer.parseInt(rows.getText()), Integer
          .parseInt(cols.getText()));
      d.setVisible(true);
    }
  }
  public void init() {
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(2, 2));
    p.add(new JLabel("Rows", JLabel.CENTER));
    p.add(rows);
    p.add(new JLabel("Columns", JLabel.CENTER));
    p.add(cols);
    Container cp = getContentPane();
    cp.add(p, BorderLayout.NORTH);
    JButton b = new JButton("go");
    b.addActionListener(new BL());
    cp.add(b, BorderLayout.SOUTH);
  }
  public static void main(String[] args) {
    run(new TicTacToe(), 200, 100);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~





Dialog can be closed by pressing the escape key

   
//   TDialog
//   Copyright (C) by Andrea Carboni.
//   This file may be distributed under the terms of the LGPL license.
//

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/** This dialog can be closed by pressing the escape key
  */
public class TDialog extends JDialog
{
  private boolean bCancel;
  //---------------------------------------------------------------------------
  public TDialog(Frame f, String title, boolean modal)
  {
    super(f, title, modal);
    bCancel = false;
    addWindowListener(new WindowAdapter()
      {
        public void windowClosing(WindowEvent e)
        {
          bCancel = true;
        }
      }
    );
  }
  //---------------------------------------------------------------------------
  protected JRootPane createRootPane()
  {
    ActionListener al = new ActionListener()
    {
      public void actionPerformed(ActionEvent ae)
      {
        hide();
        bCancel = true;
      }
    };
    KeyStroke stroke   = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    JRootPane rootPane = super.createRootPane();
    rootPane.registerKeyboardAction(al, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
    return rootPane;
  }
  //---------------------------------------------------------------------------
  /** Packs the dialog, centers it on its parent, shows it and disposes it on exit
    */
  public void showDialog()
  {
    bCancel = false;
    pack();
    setLocationRelativeTo(getParent());
    show();
  }
  //---------------------------------------------------------------------------
  public void setCancelled()
  {
    bCancel = true;
  }
  //---------------------------------------------------------------------------
  public void clearCancelled()
  {
    bCancel = false;
  }
  //---------------------------------------------------------------------------
  public boolean isCancelled()
  {
    return bCancel;
  }
}





Dialog separator

  
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class DialogSeparator extends JLabel {
  public static final int OFFSET = 15;
  public DialogSeparator() {
  }
  public DialogSeparator(String text) {
    super(text);
  }
  public Dimension getPreferredSize() {
    return new Dimension(getParent().getWidth(), 20);
  }
  public Dimension getMinimumSize() {
    return getPreferredSize();
  }
  public Dimension getMaximumSize() {
    return getPreferredSize();
  }
  public void paint(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    Dimension d = getSize();
    int y = (d.height - 3) / 2;
    g.setColor(Color.white);
    g.drawLine(1, y, d.width - 1, y);
    y++;
    g.drawLine(0, y, 1, y);
    g.setColor(Color.gray);
    g.drawLine(d.width - 1, y, d.width, y);
    y++;
    g.drawLine(1, y, d.width - 1, y);
    String text = getText();
    if (text.length() == 0)
      return;
    g.setFont(getFont());
    FontMetrics fm = g.getFontMetrics();
    y = (d.height + fm.getAscent()) / 2;
    int fontWidth = fm.stringWidth(text);
    g.setColor(getBackground());
    g.fillRect(OFFSET - 5, 0, OFFSET + fontWidth, d.height);
    g.setColor(getForeground());
    g.drawString(text, OFFSET, y);
  }
  public static void main(String argv[]) {
    new FlightReservation();
  }
}
class FlightReservation extends JFrame {
  public FlightReservation() {
    super("Dialog ");
    Container c = getContentPane();
        c.setLayout(new FlowLayout());
    c.add(new DialogSeparator("Options"));
    ButtonGroup group = new ButtonGroup();
    JRadioButton r1 = new JRadioButton("First class");
    group.add(r1);
    c.add(r1);
    JRadioButton r2 = new JRadioButton("Business");
    group.add(r2);
    c.add(r2);
    JRadioButton r3 = new JRadioButton("Coach");
    group.add(r3);
    c.add(r3);
    c.add(new DialogSeparator());
    JButton b3 = new JButton("Exit");
    c.add(b3);
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    setSize(300,200);
    setVisible(true);
  }
}





Dialog which displays indeterminate progress

   
/*
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the license, or (at your option) any later version.
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
/**
    Dialog which displays indeterminate progress.
    @author 
    @version $Revision: 1.1 $ $Date: 2003/08/18 07:46:43 $
*/
public class ProgressDialog extends JDialog {
    private static final int PROGRESS_BAR_WIDTH = 200;
    private Runnable runnable;
    private JProgressBar progressBar;
    private JLabel lblMessage;
    /**
     * Constructor.
     * @param parent the parent frame.
     * @param runnable the <tt>Runnable</tt> to be started on <tt>setVisible</tt>.
     * @param message the initial status message.
     */
    public ProgressDialog(JFrame parent, Runnable runnable, String message) {
        super(parent);
        init(runnable, message);
    }
    /**
     * Constructor.
     * @param parent the parent dialog.
     * @param runnable the <tt>Runnable</tt> to be started on <tt>setVisible</tt>.
     * @param message the initial status message.
     */
    public ProgressDialog(JDialog parent, Runnable runnable, String message) {
        super(parent);
        init(runnable, message);
    }
    /**
     * Set the current status message.
     * @param message the message.
     */
    public void setMessage(String message) {
        lblMessage.setText(message);
    }
    /**
     * Set the  <tt>Runnable</tt> to be started on <tt>setVisible</tt>.
     * @param runnable the <tt>Runnable</tt>.
     */
    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }
    public void setVisible(boolean visible) {
        if (visible) {
            progressBar.setIndeterminate(true);
        } else {
            progressBar.setIndeterminate(false);
        }
        super.setVisible(visible);
    }
    private void init(Runnable runnable, String message) {
        setupControls();
        setupComponent();
        setupEventHandlers();
        setMessage(message);
        setRunnable(runnable);
    }
    private void setupControls() {
        progressBar = new JProgressBar();
        Dimension preferredSize = progressBar.getPreferredSize();
        preferredSize.width = PROGRESS_BAR_WIDTH;
        progressBar.setPreferredSize(preferredSize);
        lblMessage = new JLabel(" ");
    }
    private void setupComponent() {
        JPanel contentPane = (JPanel)getContentPane();
        contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 0;
        gc.gridy = GridBagConstraints.RELATIVE;
        gc.anchor = GridBagConstraints.NORTHWEST;
        contentPane.add(lblMessage, gc);
        gc.weightx = 1;
        gc.fill = GridBagConstraints.HORIZONTAL;
        contentPane.add(progressBar, gc);
        setTitle("");
        setModal(true);
        pack();
    }
    private void setupEventHandlers() {
        addComponentListener(new ComponentAdapter() {
            public void componentShown(ComponentEvent event) {
                final Thread task = new Thread(runnable);
                task.start();
                new Thread() {
                    public void run() {
                        try {
                            task.join();
                        } catch (InterruptedException e) {
                        }
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                setVisible(false);
                            }
                        });
                    }
                }.start();
            }
        });
    }

}





Dialog with Escape Key

  
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
public class FrameKey {
  public static void main(String args[]) {
    final JFrame frame = new JFrame("Frame Key");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Action actionListener = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        JDialog dialog = new EscapeDialog(frame, "Hey");
        JButton button = new JButton("Okay");
        ActionListener innerActionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Dialog Button Selected");
          }
        };
        button.addActionListener(innerActionListener);
        dialog.getContentPane().add(button, BorderLayout.SOUTH);
        dialog.setSize(200, 200);
        dialog.show();
      }
    };
    JPanel content = (JPanel) frame.getContentPane();
    KeyStroke stroke = KeyStroke.getKeyStroke("M");
    InputMap inputMap = content
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(stroke, "OPEN");
    content.getActionMap().put("OPEN", actionListener);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class EscapeDialog extends JDialog {
  public EscapeDialog() {
    this((Frame) null, false);
  }
  public EscapeDialog(Frame owner) {
    this(owner, false);
  }
  public EscapeDialog(Frame owner, boolean modal) {
    this(owner, null, modal);
  }
  public EscapeDialog(Frame owner, String title) {
    this(owner, title, false);
  }
  public EscapeDialog(Frame owner, String title, boolean modal) {
    super(owner, title, modal);
  }
  public EscapeDialog(Dialog owner) {
    this(owner, false);
  }
  public EscapeDialog(Dialog owner, boolean modal) {
    this(owner, null, modal);
  }
  public EscapeDialog(Dialog owner, String title) {
    this(owner, title, false);
  }
  public EscapeDialog(Dialog owner, String title, boolean modal) {
    super(owner, title, modal);
  }
  protected JRootPane createRootPane() {
    JRootPane rootPane = new JRootPane();
    KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
    Action actionListener = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        setVisible(false);
      }
    };
    InputMap inputMap = rootPane
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(stroke, "ESCAPE");
    rootPane.getActionMap().put("ESCAPE", actionListener);
    return rootPane;
  }
}





Error message dialog

  

import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ErrorDialog {
  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}





Escape Key close Dialog

  
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EscapeDialog extends JDialog {
  public EscapeDialog() {
    this((Frame)null, false);
  }
  public EscapeDialog(Frame owner) {
    this(owner, false);
  }
  public EscapeDialog(Frame owner, boolean modal) {
    this(owner, null, modal);
  }
  public EscapeDialog(Frame owner, String title) {
    this(owner, title, false);     
  }
  public EscapeDialog(Frame owner, String title, boolean modal) {
    super(owner, title, modal);
  }
  public EscapeDialog(Dialog owner) {
    this(owner, false);
  }
  public EscapeDialog(Dialog owner, boolean modal) {
    this(owner, null, modal);
  }
  public EscapeDialog(Dialog owner, String title) {
    this(owner, title, false);     
  }
  public EscapeDialog(Dialog owner, String title, boolean modal) {
    super(owner, title, modal);
  }
  protected JRootPane createRootPane() {
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        setVisible(false);
      }
    };
    JRootPane rootPane = new JRootPane();
    KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
    return rootPane;
  }
}





  
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class InputDialog {
  public static void main(String argv[]) {
    String input = (String) JOptionPane.showInputDialog(
        new JFrame(),
        "Please enter your favorite Shakespeare play",
        "Title", JOptionPane.INFORMATION_MESSAGE,
        new ImageIcon("jexpLogo.GIF"), null, "Romeo and Juliet");
    System.out.println("User"s input: " + input);
  }
}





  
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ComboBoxDialog {
  public static void main(String argv[]) {
    String[] plays = new String[] { "Hamlet", "King Lear",
        "Otello", "Romeo and Juliet" };
    String input = (String) JOptionPane.showInputDialog(
        new JFrame(),
        "Please select your favorite Shakespeare play",
        "Title", JOptionPane.INFORMATION_MESSAGE,
        new ImageIcon("jexpLogo.GIF"), plays, "Romeo and Juliet");
    System.out.println("User"s input: " + input);
  }
}





Message dialog

  
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MessageDialog {
  public static void main(String argv[]) {
    String message = "William Shakespeare was born\n"
        + "on April 23, 1564 in\n" + "Stratford-on-Avon near London.";
    JOptionPane pane = new JOptionPane(message);
    JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
    dialog.show();
  }
}





Message Dialog demo

  
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MessagePopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Message Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Pop it");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component) actionEvent.getSource();
        /*
         * // String msg = "this is a really long message this is a
         * really long message this is a really long message this is a
         * really long message this is a really long message this is a
         * really long message this is a really long message"; String
         * msg = " <html>this is a really long message <br> this is a
         * really long message this is a really long message this is a
         * really long message this is a really long message this is a
         * really long message this is a really long message";
         * JOptionPane.showMessageDialog(source, msg); JOptionPane
         * optionPane = OptionPaneUtils.getNarrowOptionPane(72);
         * optionPane.setMessage(msg);
         * optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
         * JDialog dialog = optionPane.createDialog(source, "Width 72");
         * dialog.show(); int selection =
         * OptionPaneUtils.getSelection(optionPane);
         * JOptionPane.showMessageDialog(source, msg); String
         * multiLineMsg[] = {"Hello", "World"};
         * JOptionPane.showMessageDialog(source, multiLineMsg);
         * 
         * Object complexMsg[] = {"Above Message", new
         * DiamondIcon(Color.red), new JButton ("Hello"), new JSlider(),
         * new DiamondIcon(Color.blue), "Below Message"};
         * JOptionPane.showInputDialog(source, complexMsg); JOptionPane
         * optionPane = new JOptionPane(); JSlider slider =
         * OptionPaneUtils.getSlider(optionPane);
         * optionPane.setMessage(new Object[] {"Select a value: " ,
         * slider});
         * optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
         * optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
         * JDialog dialog = optionPane.createDialog(source, "My
         * Slider"); dialog.show(); System.out.println ("Input: " +
         * optionPane.getInputValue());
         */
        JOptionPane optionPane = new JOptionPane();
        optionPane.setMessage("I got an icon and a text label");
        optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
        Icon icon = new DiamondIcon(Color.blue);
        JButton jButton = OptionPaneUtils.getButton(optionPane, "OK",
            icon);
        optionPane.setOptions(new Object[] { jButton });
        JDialog dialog = optionPane.createDialog(source,
            "Icon/Text Button");
        dialog.show();
      }
    };
    button.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
class DiamondIcon implements Icon {
  private Color color;
  private boolean selected;
  private int width;
  private int height;
  private Polygon poly;
  private static final int DEFAULT_WIDTH = 10;
  private static final int DEFAULT_HEIGHT = 10;
  public DiamondIcon(Color color) {
    this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected) {
    this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected, int width, int height) {
    this.color = color;
    this.selected = selected;
    this.width = width;
    this.height = height;
    initPolygon();
  }
  private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width / 2;
    int halfHeight = height / 2;
    poly.addPoint(0, halfHeight);
    poly.addPoint(halfWidth, 0);
    poly.addPoint(width, halfHeight);
    poly.addPoint(halfWidth, height);
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.translate(x, y);
    if (selected) {
      g.fillPolygon(poly);
    } else {
      g.drawPolygon(poly);
    }
    g.translate(-x, -y);
  }
}
final class OptionPaneUtils {
  private OptionPaneUtils() {
  }
  public static JOptionPane getNarrowOptionPane(int maxCharactersPerLineCount) {
    // Our inner class definition
    class NarrowOptionPane extends JOptionPane {
      int maxCharactersPerLineCount;
      NarrowOptionPane(int maxCharactersPerLineCount) {
        this.maxCharactersPerLineCount = maxCharactersPerLineCount;
      }
      public int getMaxCharactersPerLineCount() {
        return maxCharactersPerLineCount;
      }
    }
    return new NarrowOptionPane(maxCharactersPerLineCount);
  }
  public static JButton getButton(final JOptionPane optionPane, String text,
      Icon icon) {
    final JButton button = new JButton(text, icon);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        // Return current text label, instead of argument to method
        optionPane.setValue(button.getText());
      }
    };
    button.addActionListener(actionListener);
    return button;
  }
  public static JSlider getSlider(final JOptionPane optionPane) {
    JSlider slider = new JSlider();
    slider.setMajorTickSpacing(10);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changeEvent) {
        JSlider theSlider = (JSlider) changeEvent.getSource();
        if (!theSlider.getValueIsAdjusting()) {
          optionPane.setInputValue(new Integer(theSlider.getValue()));
        }
      }
    };
    slider.addChangeListener(changeListener);
    return slider;
  }
  public static int getSelection(JOptionPane optionPane) {
    // Default return value, signals nothing selected
    int returnValue = JOptionPane.CLOSED_OPTION;
    // Get selected Value
    Object selectedValue = optionPane.getValue();
    System.out.println(selectedValue);
    // If none, then nothing selected
    if (selectedValue != null) {
      Object options[] = optionPane.getOptions();
      if (options == null) {
        // default buttons, no array specified
        if (selectedValue instanceof Integer) {
          returnValue = ((Integer) selectedValue).intValue();
        }
      } else {
        // Array of option buttons specified
        for (int i = 0, n = options.length; i < n; i++) {
          if (options[i].equals(selectedValue)) {
            returnValue = i;
            break; // out of for loop
          }
        }
      }
    }
    return returnValue;
  }
}





Modal Message Dialog

   
/*
This file is part of BORG.
    BORG is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    BORG is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with BORG; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Copyright 2003 by Mike Berger
*/
/*
 * helpscrn.java
 *
 * Created on October 5, 2003, 8:55 AM
 */

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;


public class ModalMessage extends JDialog {
 
    public ModalMessage(String s, boolean enabled) {
        initComponents();    
        jTextArea.setText(s);
        okButton.setEnabled(enabled);
        setModal(true);       
    }
    public void setEnabled(boolean e)
    {
      okButton.setEnabled(e);
    }
    public void setText(String s)
    {
      jTextArea.setText(s);
    }
    
    public void appendText(String s)
    {
      String t = jTextArea.getText();
      t += "\n" + s;
      jTextArea.setText(t);
    }
    
    private void initComponents()//GEN-BEGIN:initComponents
    {
      //this.setUndecorated(true);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setTitle("BORG");
        this.setSize(165, 300);
        this.setContentPane(getJPanel());
        
        pack();
        
        Dimension screenSize =
            Toolkit.getDefaultToolkit().getScreenSize();
          Dimension labelSize = jScrollPane.getPreferredSize();
          setLocation(screenSize.width/2 - (labelSize.width/2),
                      screenSize.height/2 - (labelSize.height/2));
    }
    
    
    private JPanel jPanel = null;
  private JScrollPane jScrollPane = null;
  private JTextArea jTextArea = null;
  
  /**
   * This method initializes jPanel 
   *  
   * @return javax.swing.JPanel 
   */
  private JPanel getJPanel() {
    if (jPanel == null) {
      GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
      gridBagConstraints1.gridx = 0;  // Generated
      gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;  // Generated
      gridBagConstraints1.gridy = 1;  // Generated
      GridBagConstraints gridBagConstraints = new GridBagConstraints();
      gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;  // Generated
      gridBagConstraints.gridy = 0;  // Generated
      gridBagConstraints.weightx = 1.0;  // Generated
      gridBagConstraints.weighty = 1.0;  // Generated
      gridBagConstraints.insets = new java.awt.Insets(4,4,4,4);  // Generated
      gridBagConstraints.gridx = 0;  // Generated
      jPanel = new JPanel();
      jPanel.setLayout(new GridBagLayout());  // Generated
      jPanel.add(getJScrollPane(), gridBagConstraints);  // Generated
      jPanel.add(getButtonPanel(), gridBagConstraints1);
    }
    return jPanel;
  }

  /**
   * This method initializes jScrollPane  
   *  
   * @return javax.swing.JScrollPane  
   */
  private JScrollPane getJScrollPane() {
    if (jScrollPane == null) {
      jScrollPane = new JScrollPane();
      jScrollPane.setPreferredSize(new java.awt.Dimension(600,200));  // Generated
      jScrollPane.setViewportView(getJTextArea());  // Generated
    }
    return jScrollPane;
  }

  /**
   * This method initializes jTextArea  
   *  
   * @return javax.swing.JTextArea  
   */
  private JTextArea getJTextArea() {
    if (jTextArea == null) {
      jTextArea = new JTextArea();
      jTextArea.setEditable(false);  // Generated
      jTextArea.setLineWrap(true);  // Generated
    }
    return jTextArea;
  }
  /**
   * This method initializes buttonPanel  
   *  
   * @return javax.swing.JPanel 
   */
  private JPanel buttonPanel = null;
  private JPanel getButtonPanel() {
    if (buttonPanel == null) {
      buttonPanel = new JPanel();
      buttonPanel.add(getOkButton(), null);  // Generated
      
    }
    return buttonPanel;
  }

  /**
   * This method initializes okButton 
   *  
   * @return javax.swing.JButton  
   */
  private JButton okButton = null;
  private JButton getOkButton() {
    if (okButton == null) {
      okButton = new JButton();
      okButton.setText("OK");
      okButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
          doOk();
        }
      });
    }
    return okButton;
  }
  private void doOk()
  {
    this.dispose();
  }

  public static void main( String args[])
    {
    final ModalMessage mm = new ModalMessage("duh\nduh\nduh", false);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
          mm.setVisible(true);        
      }
    });
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
          mm.appendText("another line");
          mm.setEnabled(true);        
      }
    });
      
    }
}  //  @jve:decl-index=0:visual-constraint="10,10"





No button dialog

  
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class NoButtonPopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("NoButton Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Ask");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component) actionEvent.getSource();
        int response = JOptionPane.showOptionDialog(source, "",
            "Empty?", JOptionPane.DEFAULT_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, new Object[] {},
            null);
        System.out.println("Response: " + response);
      }
    };
    button.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





See the differences between various types of option panes

  
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// OptPaneComparison.java
//A quick utility class to help you see the differences between various
//types of option panes, both via internal frames and using standalone
//popups.
//
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
public class OptPaneComparison extends JFrame {
  protected JOptionPane optPane;
  public static void main(String[] args) {
    JFrame f = new OptPaneComparison("Enter your name");
    f.setVisible(true);
  }
  public OptPaneComparison(final String message) {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final int msgType = JOptionPane.QUESTION_MESSAGE;
    final int optType = JOptionPane.OK_CANCEL_OPTION;
    final String title = message;
    setSize(350, 200);
    // Create a desktop for internal frames
    final JDesktopPane desk = new JDesktopPane();
    setContentPane(desk);
    // Add a simple menu bar
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    JMenu menu = new JMenu("Dialog");
    JMenu imenu = new JMenu("Internal");
    mb.add(menu);
    mb.add(imenu);
    final JMenuItem construct = new JMenuItem("Constructor");
    final JMenuItem stat = new JMenuItem("Static Method");
    final JMenuItem iconstruct = new JMenuItem("Constructor");
    final JMenuItem istat = new JMenuItem("Static Method");
    menu.add(construct);
    menu.add(stat);
    imenu.add(iconstruct);
    imenu.add(istat);
    // Create our JOptionPane. We"re asking for input, so we call
    // setWantsInput.
    // Note that we cannot specify this via constructor parameters.
    optPane = new JOptionPane(message, msgType, optType);
    optPane.setWantsInput(true);
    // Add a listener for each menu item that will display the appropriate
    // dialog/internal frame
    construct.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        // Create and display the dialog
        JDialog d = optPane.createDialog(desk, title);
        d.setVisible(true);
        respond(getOptionPaneValue());
      }
    });
    stat.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        String s = JOptionPane.showInputDialog(desk, message, title,
            msgType);
        respond(s);
      }
    });
    iconstruct.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        // Create and display the dialog
        JInternalFrame f = optPane.createInternalFrame(desk, title);
        f.setVisible(true);
        // Listen for the frame to close before getting the value from
        // it.
        f.addPropertyChangeListener(new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent ev) {
            if ((ev.getPropertyName()
                .equals(JInternalFrame.IS_CLOSED_PROPERTY))
                && (ev.getNewValue() == Boolean.TRUE)) {
              respond(getOptionPaneValue());
            }
          }
        });
      }
    });
    istat.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        String s = JOptionPane.showInternalInputDialog(desk, message,
            title, msgType);
        respond(s);
      }
    });
  }
  // This method gets the selected value from the option pane and resets the
  // value to null so we can use it again.
  protected String getOptionPaneValue() {
    // Get the result . . .
    Object o = optPane.getInputValue();
    String s = "<Unknown>";
    if (o != null)
      s = (String) o;
    Object val = optPane.getValue(); // which button?
    // Check for cancel button or closed option
    if (val != null) {
      if (val instanceof Integer) {
        int intVal = ((Integer) val).intValue();
        if ((intVal == JOptionPane.CANCEL_OPTION)
            || (intVal == JOptionPane.CLOSED_OPTION))
          s = "<Cancel>";
      }
    }
    // A little trick to clean the text field. It is only updated if
    // the initial value gets changed. To do this, we"ll set it to a
    // dummy value ("X") and then clear it.
    optPane.setValue("");
    optPane.setInitialValue("X");
    optPane.setInitialValue("");
    return s;
  }
  protected void respond(String s) {
    if (s == null)
      System.out.println("Never mind.");
    else
      System.out.println("You entered: " + s);
  }
}





Simple dialog for asking a yes no question

  
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class AskingQuestionDialog {
  public static void main(String argv[]) {
    JOptionPane pane = new JOptionPane(
        "To be or not to be ?\nThat is the question.");
    Object[] options = new String[] { "To be", "Not to be" };
    pane.setOptions(options);
    JDialog dialog = pane.createDialog(new JFrame(), "Dilaog");
    dialog.show();
    Object obj = pane.getValue(); 
    int result = -1;
    for (int k = 0; k < options.length; k++)
      if (options[k].equals(obj))
        result = k;
    System.out.println("User"s choice: " + result);
  }
}





Simple Save Dialog demo

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
 * Simple Save Dialog demo.
 * @version $Id: SaveDialog.java,v 1.4 2000/11/25 17:54:19 ian Exp $
 */
public class SaveDialog extends JFrame {
  boolean unsavedChanges = false;
  Button quitButton;
  /** "main program" method - construct and show */
  public static void main(String[] av) {
    // create a SaveDialog object, tell it to show up
    new SaveDialog().setVisible(true);
  }
  /** Construct the object including its GUI */
  public SaveDialog() {
    super("SaveDialog");
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(new Label("Press this button to see the Quit dialog: "));
    cp.add(quitButton = new Button("Quit"));
    quitButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("In Exit Button"s action handler");
        if (okToQuit()) {
          setVisible(false);
          dispose();
          System.exit(0);
        }
      }
    });
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        setVisible(false);
        dispose();
        System.exit(0);
      }
    });
    pack();
  }
  boolean okToQuit() {
    String[] choices = {
      "Yes, Save and Quit", "No, Quit without saving", "CANCEL"
    };
    int result = JOptionPane.showOptionDialog(this,
      "You have unsaved changes. Save before quitting?", "Warning",
      JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, 
      null, choices, choices[0]);
      // Use of "null" as the Icon argument is contentious... the
      // document says you can pass null, but it does seem to
      // generate a lot of blather if you do, something about
      // a NullPointerException :-) ...
    if (result >= 0)
      System.out.println("You clicked " + choices[result]);
    switch(result) {
    case -1:
      System.out.println("You killed my die-alog - it died");
      return false;
    case 0:  // save and quit
      System.out.println("Saving...");
      // mainApp.doSave();
      return true;
    case 1:  // just quit
      return true;
    case 2:  // cancel
      return false;
    default:
      throw new IllegalArgumentException("Unexpected return " + result);
    }
  }
}





Vote Dialog

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class VoteDialog extends JPanel {
  JLabel label;
  JFrame frame;
  String simpleDialogDesc = "The candidates";
  public VoteDialog(JFrame frame) {
    this.frame = frame;
    JLabel title;
    // Create the components.
    JPanel choicePanel = createSimpleDialogBox();
    System.out.println("passed createSimpleDialogBox");
    title = new JLabel("Click the \"Vote\" button"
        + " once you have selected a candidate.", JLabel.CENTER);
    label = new JLabel("Vote now!", JLabel.CENTER);
    label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    choicePanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 5, 20));
    // Set the layout.
    setLayout(new BorderLayout());
    add(title, BorderLayout.NORTH);
    add(label, BorderLayout.SOUTH);
    add(choicePanel, BorderLayout.CENTER);
  }
  void setLabel(String newText) {
    label.setText(newText);
  }
  private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();
    JButton voteButton = null;
    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";
    radioButtons[0] = new JRadioButton(
        "<html>Candidate 1: <font color=red>Sparky the Dog</font></html>");
    radioButtons[0].setActionCommand(defaultMessageCommand);
    radioButtons[1] = new JRadioButton(
        "<html>Candidate 2: <font color=green>Shady Sadie</font></html>");
    radioButtons[1].setActionCommand(yesNoCommand);
    radioButtons[2] = new JRadioButton(
        "<html>Candidate 3: <font color=blue>R.I.P. McDaniels</font></html>");
    radioButtons[2].setActionCommand(yeahNahCommand);
    radioButtons[3] = new JRadioButton(
        "<html>Candidate 4: <font color=maroon>Duke the Java<font size=-2><sup>TM</sup></font size> Platform Mascot</font></html>");
    radioButtons[3].setActionCommand(yncCommand);
    for (int i = 0; i < numButtons; i++) {
      group.add(radioButtons[i]);
    }
    // Select the first button by default.
    radioButtons[0].setSelected(true);
    voteButton = new JButton("Vote");
    voteButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String command = group.getSelection().getActionCommand();
        // ok dialog
        if (command == defaultMessageCommand) {
          JOptionPane.showMessageDialog(frame,
              "This candidate is a dog. Invalid vote.");
          // yes/no dialog
        } else if (command == yesNoCommand) {
          int n = JOptionPane
              .showConfirmDialog(
                  frame,
                  "This candidate is a convicted felon. \nDo you still want to vote for her?",
                  "A Follow-up Question",
                  JOptionPane.YES_NO_OPTION);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("OK. Keep an eye on your wallet.");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("Whew! Good choice.");
          } else {
            setLabel("It is your civic duty to cast your vote.");
          }
          // yes/no (with customized wording)
        } else if (command == yeahNahCommand) {
          Object[] options = { "Yes, please", "No, thanks" };
          int n = JOptionPane
              .showOptionDialog(
                  frame,
                  "This candidate is deceased. \nDo you still want to vote for him?",
                  "A Follow-up Question",
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE, null,
                  options, options[0]);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("I hope you don"t expect much from your candidate.");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("Whew! Good choice.");
          } else {
            setLabel("It is your civic duty to cast your vote.");
          }
          // yes/no/cancel (with customized wording)
        } else if (command == yncCommand) {
          Object[] options = { "Yes!", "No, I"ll pass",
              "Well, if I must" };
          int n = JOptionPane.showOptionDialog(frame,
              "Duke is a cartoon mascot. \nDo you  "
                  + "still want to cast your vote?",
              "A Follow-up Question",
              JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE, null, options,
              options[2]);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("Excellent choice.");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("Whatever you say. It"s your vote.");
          } else if (n == JOptionPane.CANCEL_OPTION) {
            setLabel("Well, I"m certainly not going to make you vote.");
          } else {
            setLabel("It is your civic duty to cast your vote.");
          }
        }
        return;
      }
    });
    System.out.println("calling createPane");
    return createPane(simpleDialogDesc + ":", radioButtons, voteButton);
  }
  private JPanel createPane(String description, JRadioButton[] radioButtons,
      JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    JLabel label = new JLabel(description);
    box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
    box.add(label);
    for (int i = 0; i < numChoices; i++) {
      box.add(radioButtons[i]);
    }
    JPanel pane = new JPanel();
    pane.setLayout(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    System.out.println("returning pane");
    return pane;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("VoteDialog");
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(1, 1));
    contentPane.add(new VoteDialog(frame));
    // Exit when the window is closed.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}