Java Tutorial/Swing/JDialog

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

Address Dialog

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class AddressDialog extends JDialog {
  JLabel label1 = new JLabel("Address");
  JLabel label2 = new JLabel("City");
  JLabel label3 = new JLabel("State");
  JLabel label4 = new JLabel("Zip Code");
  JTextField addressField = new JTextField();
  JTextField cityField = new JTextField();
  JTextField stateField = new JTextField();
  JTextField zipCodeField = new JTextField();
  String[] address = new String[4];
  public AddressDialog(Frame owner, boolean modal) {
    super(owner, modal);
    init();
  }
  private void init() {
    this.setTitle("Address Dialog");
    this.setLayout(new GridLayout(4, 2));
    this.add(label1);
    this.add(addressField);
    this.add(label2);
    this.add(cityField);
    this.add(label3);
    this.add(stateField);
    this.add(label4);
    this.add(zipCodeField);
  }
  public String[] getAddress() {
    address[0] = addressField.getText();
    address[1] = cityField.getText();
    address[2] = stateField.getText();
    address[3] = zipCodeField.getText();
    return address;
  }
}
public class JDialogTest extends JFrame {
  AddressDialog dialog = new AddressDialog(this, false);
  public JDialogTest(String title) {
    super(title);
    init();
  }
  public JDialogTest() {
    super();
    init();
  }
  private void init() {
    this.getContentPane().setLayout(new FlowLayout());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final AddressDialog dialog = new AddressDialog(this, false);
    JButton button = new JButton("Show Dialog");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        dialog.setSize(250, 120);
        dialog.setVisible(true);
      }
    });
    this.getContentPane().add(button);
  }
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JDialogTest frame = new JDialogTest();
    frame.pack();
    frame.setVisible(true);
  }
}





A dialog allow selection and a font and its associated info.

/*
 * Copyright (C) 2001-2004 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
 * A dialog allow selection and a font and its associated info.
 *
 * @author 
 */
public class FontChooser extends JDialog
{
  private final boolean _selectStyles;
  private JComboBox _fontNamesCmb;
  private final JComboBox _fontSizesCmb = new JComboBox(new String[]
                        { "8", "9", "10", "12", "14" });
  private final JCheckBox _boldChk = new JCheckBox("Bold");
  private final JCheckBox _italicChk = new JCheckBox("Italic");
  private final JLabel _previewLbl = new JLabel("PreviewText");
  private Font _font;
  private ActionListener _previewUpdater;
  /**
   * Default ctor.
   */
  public FontChooser()
  {
    this((Frame)null);
  }
  /**
   * ctor specifying whether styles can be selected.
   *
   * @param selectStyles  If <TT>true</TT> bold and italic checkboxes displayed.
   */
  public FontChooser(boolean selectStyles)
  {
    this((Frame)null, selectStyles);
  }
  /**
   * ctor specifying the parent frame.
   *
   * @param owner Parent frame.
   */
  public FontChooser(Frame owner)
  {
    super(owner, "Font Chooser", true);
    _selectStyles = true;
    createUserInterface();
  }
  /**
   * ctor specifying the parent frame and whether styles can be selected.
   *
   * @param owner     Parent frame.
   * @param selectStyles  If <TT>true</TT> bold and italic checkboxes displayed.
   */
  public FontChooser(Frame owner, boolean selectStyles)
  {
    super(owner, "Font Chooser", true);
    _selectStyles = selectStyles;
    createUserInterface();
  }
  /**
   * ctor specifying the parent dialog.
   *
   * @param owner Parent frame.
   */
  public FontChooser(Dialog owner)
  {
    super(owner, "Font Chooser", true);
    _selectStyles = true;
    createUserInterface();
  }
  /**
   * ctor specifying the parent dialog and whether styles can be selected.
   *
   * @param owner Parent frame.
   * @param selectStyles  If <TT>true</TT> bold and italic checkboxes displayed.
   */
  public FontChooser(Dialog owner, boolean selectStyles)
  {
    super(owner, "Font Chooser", true);
    _selectStyles = selectStyles;
    createUserInterface();
  }
  /**
   * Component is being added to its parent.
   */
  public void addNotify()
  {
    super.addNotify();
    if (_previewUpdater == null)
    {
      _previewUpdater = new PreviewLabelUpdater();
      _fontNamesCmb.addActionListener(_previewUpdater);
      _fontSizesCmb.addActionListener(_previewUpdater);
      _boldChk.addActionListener(_previewUpdater);
      _italicChk.addActionListener(_previewUpdater);
    }
  }
  /**
   * Component is being removed from its parent.
   */
  public void removeNotify()
  {
    super.removeNotify();
    if (_previewUpdater != null)
    {
      _fontNamesCmb.removeActionListener(_previewUpdater);
      _fontSizesCmb.removeActionListener(_previewUpdater);
      _boldChk.removeActionListener(_previewUpdater);
      _italicChk.removeActionListener(_previewUpdater);
      _previewUpdater = null;
    }
  }
  public Font showDialog()
  {
    return showDialog(null);
  }
  /**
   * Show dialog defaulting to the passed font.
   *
   * @param font  The font to default to.
   */
  public Font showDialog(Font font)
  {
    if (font != null)
    {
      _fontNamesCmb.setSelectedItem(font.getName());
      _fontSizesCmb.setSelectedItem("" + font.getSize());
      _boldChk.setSelected(_selectStyles && font.isBold());
      _italicChk.setSelected(_selectStyles && font.isItalic());
    }
    else
    {
      _fontNamesCmb.setSelectedIndex(0);
      _fontSizesCmb.setSelectedIndex(0);
      _boldChk.setSelected(false);
      _italicChk.setSelected(false);
    }
    setupPreviewLabel();
    setVisible(true);
    return _font;
  }
  public Font getSelectedFont()
  {
    return _font;
  }
  protected void setupFontFromDialog()
  {
    int size = 12;
    try
    {
      size = Integer.parseInt((String)_fontSizesCmb.getSelectedItem());
    }
    catch (Exception ignore)
    {
      // Ignore.
    }
    FontInfo fi = new FontInfo();
    fi.setFamily((String)_fontNamesCmb.getSelectedItem());
    fi.setSize(size);
    fi.setIsBold(_boldChk.isSelected());
    fi.setIsItalic(_italicChk.isSelected());
    _font = fi.createFont();
  }
  private void createUserInterface()
  {
    final JPanel content = new JPanel(new GridBagLayout());
    final GridBagConstraints gbc = new GridBagConstraints();
    setContentPane(content);
    content.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(2, 2, 2, 2);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = gbc.gridy = 0;
    content.add(new JLabel("Font"), gbc);
    ++gbc.gridx;
    content.add(new JLabel("Size"), gbc);
    if (_selectStyles)
    {
      ++gbc.gridx;
      content.add(new JLabel("Style"), gbc);
    }
    ++gbc.gridy;
    gbc.gridx = 0;
    _fontNamesCmb = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
    content.add(_fontNamesCmb, gbc);
    ++gbc.gridx;
    _fontSizesCmb.setEditable(true);
    content.add(_fontSizesCmb, gbc);
    if (_selectStyles)
    {
      ++gbc.gridx;
      content.add(_boldChk, gbc);
      ++gbc.gridy;
      content.add(_italicChk, gbc);
    }
    gbc.gridx = 0;
    ++gbc.gridy;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.CENTER;
    content.add(createPreviewPanel(), gbc);
    ++gbc.gridy;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    content.add(createButtonsPanel(), gbc);
    pack();
    setResizable(true);
  }
  private JPanel createPreviewPanel()
  {
    final JPanel pnl = new JPanel(new BorderLayout());
    pnl.setBorder(BorderFactory.createTitledBorder("PreviewTitle"));
    Dimension prefSize = _previewLbl.getPreferredSize();
    prefSize.height = 50;
    _previewLbl.setPreferredSize(prefSize);
    pnl.add(_previewLbl, BorderLayout.CENTER);
    setupPreviewLabel();
    return pnl;
  }
  private JPanel createButtonsPanel()
  {
    JPanel pnl = new JPanel();
    JButton okBtn = new JButton("OK");
    okBtn.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        setupFontFromDialog();
        dispose();
      }
    });
    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        FontChooser.this._font = null;
        dispose();
      }
    });
    pnl.add(okBtn);
    pnl.add(cancelBtn);
    getRootPane().setDefaultButton(okBtn);
    return pnl;
  }
  private void setupPreviewLabel()
  {
    setupFontFromDialog();
    _previewLbl.setFont(_font);
  }
  private final class PreviewLabelUpdater implements ActionListener
  {
    public void actionPerformed(ActionEvent evt)
    {
      setupPreviewLabel();
    }
  }
}

/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 class FontInfo implements Cloneable, Serializable
{
    private static final long serialVersionUID = 1L;
    public interface IPropertyNames
  {
    String FAMILY = "family";
    String IS_BOLD = "isBold";
    String IS_ITALIC = "isItalic";
    String SIZE = "size";
  }
  private static String DEFAULT_FAMILY = "Monospaced";
  private String _familyName;
  private boolean _isBold;
  private boolean _isItalic;
  private int _size;
  public FontInfo()
  {
    super();
    setFamily(DEFAULT_FAMILY);
    setSize(12);
  }
  public FontInfo(Font font)
  {
    super();
    if (font == null)
    {
      throw new IllegalArgumentException("Null Font passed");
    }
    setFont(font);
  }
  /**
   * Return a copy of this object.
   */
  public Object clone()
  {
    try
    {
      return super.clone();
    }
    catch (CloneNotSupportedException ex)
    {
      throw new InternalError(ex.getMessage()); // Impossible.
    }
  }
  public String getFamily()
  {
    return _familyName;
  }
  public void setFamily(String value)
  {
    _familyName = value != null ? value : DEFAULT_FAMILY;
  }
  public boolean isBold()
  {
    return _isBold;
  }
  public void setIsBold(boolean value)
  {
    _isBold = value;
  }
  public boolean isItalic()
  {
    return _isItalic;
  }
  public void setIsItalic(boolean value)
  {
    _isItalic = value;
  }
  public int getSize()
  {
    return _size;
  }
  public void setSize(int value)
  {
    _size = value;
  }
  public void setFont(Font font) throws IllegalArgumentException
  {
    if (font == null)
    {
      throw new IllegalArgumentException("Null Font passed");
    }
    _familyName = font.getFamily();
    _isBold = font.isBold();
    _isItalic = font.isItalic();
    _size = font.getSize();
  }
  public boolean doesFontMatch(Font font)
  {
    if (font == null)
    {
      return false;
    }
    return font.getFamily().equals(_familyName)
      && font.getSize() == getSize()
      && font.getStyle() == generateStyle();
  }
  public int generateStyle()
  {
    int style = 0;
    if (!_isBold && !_isItalic)
    {
      style = Font.PLAIN;
    }
    else
    {
      if (_isBold)
      {
        style |= Font.BOLD;
      }
      if (_isItalic)
      {
        style |= Font.ITALIC;
      }
    }
    return style;
  }
  public Font createFont()
  {
    return new Font(_familyName, generateStyle(), _size);
  }
  // i18n ? What is this used for?
  public String toString()
  {
    StringBuffer buf = new StringBuffer();
    buf.append(_familyName).append(", " + _size);
    if (_isBold)
    {
      buf.append(", bold");
    }
    if (_isItalic)
    {
      buf.append(", italic");
    }
    return buf.toString();
  }
    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((_familyName == null) ? 0 : _familyName.hashCode());
        result = PRIME * result + (_isBold ? 1231 : 1237);
        result = PRIME * result + (_isItalic ? 1231 : 1237);
        result = PRIME * result + _size;
        return result;
    }
    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final FontInfo other = (FontInfo) obj;
        if (_familyName == null) {
            if (other._familyName != null)
                return false;
        } else if (!_familyName.equals(other._familyName))
            return false;
        if (_isBold != other._isBold)
            return false;
        if (_isItalic != other._isItalic)
            return false;
        if (_size != other._size)
            return false;
        return true;
    }
}





A dialog that presents the user with a sequence of steps for completing a task.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * A dialog that presents the user with a sequence of steps for completing a
 * task. The dialog contains "Next" and "Previous" buttons, allowing the user to
 * navigate through the task.
 * <P>
 * When the user backs up by one or more steps, the dialog keeps the completed
 * steps so that they can be reused if the user doesn"t change anything - this
 * handles the cases where the user backs up a few steps just to review what has
 * been completed.
 * <p>
 * But if the user changes some options in an earlier step, then the dialog may
 * have to discard the later steps and have them repeated.
 * <P>
 * THIS CLASS IS NOT WORKING CORRECTLY YET.
 * 
 * 
 * @author David Gilbert
 */
public class WizardDialog extends JDialog implements ActionListener {
  /** The end result of the wizard sequence. */
  private Object result;
  /** The current step in the wizard process (starting at step zero). */
  private int step;
  /** A reference to the current panel. */
  private WizardPanel currentPanel;
  /**
   * A list of references to the panels the user has already seen - used for
   * navigating through the steps that have already been completed.
   */
  private java.util.List panels;
  /** A handy reference to the "previous" button. */
  private JButton previousButton;
  /** A handy reference to the "next" button. */
  private JButton nextButton;
  /** A handy reference to the "finish" button. */
  private JButton finishButton;
  /** A handy reference to the "help" button. */
  private JButton helpButton;
  /**
   * Standard constructor - builds and returns a new WizardDialog.
   * 
   * @param owner
   *          the owner.
   * @param modal
   *          modal?
   * @param title
   *          the title.
   * @param firstPanel
   *          the first panel.
   */
  public WizardDialog(final JDialog owner, final boolean modal, final String title,
      final WizardPanel firstPanel) {
    super(owner, title + " : step 1", modal);
    this.result = null;
    this.currentPanel = firstPanel;
    this.step = 0;
    this.panels = new ArrayList();
    this.panels.add(firstPanel);
    setContentPane(createContent());
  }
  /**
   * Standard constructor - builds a new WizardDialog owned by the specified
   * JFrame.
   * 
   * @param owner
   *          the owner.
   * @param modal
   *          modal?
   * @param title
   *          the title.
   * @param firstPanel
   *          the first panel.
   */
  public WizardDialog(final JFrame owner, final boolean modal, final String title,
      final WizardPanel firstPanel) {
    super(owner, title + " : step 1", modal);
    this.result = null;
    this.currentPanel = firstPanel;
    this.step = 0;
    this.panels = new ArrayList();
    this.panels.add(firstPanel);
    setContentPane(createContent());
  }
  /**
   * Returns the result of the wizard sequence.
   * 
   * @return the result.
   */
  public Object getResult() {
    return this.result;
  }
  /**
   * Returns the total number of steps in the wizard sequence, if this number is
   * known. Otherwise this method returns zero. Subclasses should override this
   * method unless the number of steps is not known.
   * 
   * @return the number of steps.
   */
  public int getStepCount() {
    return 0;
  }
  /**
   * Returns true if it is possible to back up to the previous panel, and false
   * otherwise.
   * 
   * @return boolean.
   */
  public boolean canDoPreviousPanel() {
    return (this.step > 0);
  }
  /**
   * Returns true if there is a "next" panel, and false otherwise.
   * 
   * @return boolean.
   */
  public boolean canDoNextPanel() {
    return this.currentPanel.hasNextPanel();
  }
  /**
   * Returns true if it is possible to finish the sequence at this point
   * (possibly with defaults for the remaining entries).
   * 
   * @return boolean.
   */
  public boolean canFinish() {
    return this.currentPanel.canFinish();
  }
  /**
   * Returns the panel for the specified step (steps are numbered from zero).
   * 
   * @param step
   *          the current step.
   * 
   * @return the panel.
   */
  public WizardPanel getWizardPanel(final int step) {
    if (step < this.panels.size()) {
      return (WizardPanel) this.panels.get(step);
    } else {
      return null;
    }
  }
  /**
   * Handles events.
   * 
   * @param event
   *          the event.
   */
  public void actionPerformed(final ActionEvent event) {
    final String command = event.getActionCommand();
    if (command.equals("nextButton")) {
      next();
    } else if (command.equals("previousButton")) {
      previous();
    } else if (command.equals("finishButton")) {
      finish();
    }
  }
  /**
   * Handles a click on the "previous" button, by displaying the previous panel
   * in the sequence.
   */
  public void previous() {
    if (this.step > 0) {
      final WizardPanel previousPanel = getWizardPanel(this.step - 1);
      // tell the panel that we are returning
      previousPanel.returnFromLaterStep();
      final Container content = getContentPane();
      content.remove(this.currentPanel);
      content.add(previousPanel);
      this.step = this.step - 1;
      this.currentPanel = previousPanel;
      setTitle("Step " + (this.step + 1));
      enableButtons();
      pack();
    }
  }
  /**
   * Displays the next step in the wizard sequence.
   */
  public void next() {
    WizardPanel nextPanel = getWizardPanel(this.step + 1);
    if (nextPanel != null) {
      if (!this.currentPanel.canRedisplayNextPanel()) {
        nextPanel = this.currentPanel.getNextPanel();
      }
    } else {
      nextPanel = this.currentPanel.getNextPanel();
    }
    this.step = this.step + 1;
    if (this.step < this.panels.size()) {
      this.panels.set(this.step, nextPanel);
    } else {
      this.panels.add(nextPanel);
    }
    final Container content = getContentPane();
    content.remove(this.currentPanel);
    content.add(nextPanel);
    this.currentPanel = nextPanel;
    setTitle("Step " + (this.step + 1));
    enableButtons();
    pack();
  }
  /**
   * Finishes the wizard.
   */
  public void finish() {
    this.result = this.currentPanel.getResult();
    setVisible(false);
  }
  /**
   * Enables/disables the buttons according to the current step. A good idea
   * would be to ask the panels to return the status...
   */
  private void enableButtons() {
    this.previousButton.setEnabled(this.step > 0);
    this.nextButton.setEnabled(canDoNextPanel());
    this.finishButton.setEnabled(canFinish());
    this.helpButton.setEnabled(false);
  }
  /**
   * Checks, whether the user cancelled the dialog.
   * 
   * @return false.
   */
  public boolean isCancelled() {
    return false;
  }
  /**
   * Creates a panel containing the user interface for the dialog.
   * 
   * @return the panel.
   */
  public JPanel createContent() {
    final JPanel content = new JPanel(new BorderLayout());
    content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    content.add((JPanel) this.panels.get(0));
    final L1R3ButtonPanel buttons = new L1R3ButtonPanel("Help", "Previous", "Next", "Finish");
    this.helpButton = buttons.getLeftButton();
    this.helpButton.setEnabled(false);
    this.previousButton = buttons.getRightButton1();
    this.previousButton.setActionCommand("previousButton");
    this.previousButton.addActionListener(this);
    this.previousButton.setEnabled(false);
    this.nextButton = buttons.getRightButton2();
    this.nextButton.setActionCommand("nextButton");
    this.nextButton.addActionListener(this);
    this.nextButton.setEnabled(true);
    this.finishButton = buttons.getRightButton3();
    this.finishButton.setActionCommand("finishButton");
    this.finishButton.addActionListener(this);
    this.finishButton.setEnabled(false);
    buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
    content.add(buttons, BorderLayout.SOUTH);
    return content;
  }
}
/*
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 * 
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info: http://www.jfree.org/jcommon/index.html
 * 
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library 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 Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * 
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. in the
 * United States and other countries.]
 * 
 * ---------------- WizardPanel.java ---------------- (C) Copyright 2000-2004,
 * by Object Refinery Limited.
 * 
 * Original Author: David Gilbert (for Object Refinery Limited); Contributor(s): -;
 * 
 * $Id: WizardPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $
 * 
 * Changes (from 26-Oct-2001) -------------------------- 26-Oct-2001 : Changed
 * package to com.jrefinery.ui.*; 14-Oct-2002 : Fixed errors reported by
 * Checkstyle (DG);
 * 
 */
/**
 * A panel that provides the user interface for a single step in a WizardDialog.
 * 
 * @author David Gilbert
 */
abstract class WizardPanel extends JPanel {
  /** The owner. */
  private WizardDialog owner;
  /**
   * Creates a new panel.
   * 
   * @param layout
   *          the layout manager.
   */
  protected WizardPanel(final LayoutManager layout) {
    super(layout);
  }
  /**
   * Returns a reference to the dialog that owns the panel.
   * 
   * @return the owner.
   */
  public WizardDialog getOwner() {
    return this.owner;
  }
  /**
   * Sets the reference to the dialog that owns the panel (this is called
   * automatically by the dialog when the panel is added to the dialog).
   * 
   * @param owner
   *          the owner.
   */
  public void setOwner(final WizardDialog owner) {
    this.owner = owner;
  }
  /**
   * Returns the result.
   * 
   * @return the result.
   */
  public Object getResult() {
    return null;
  }
  /**
   * This method is called when the dialog redisplays this panel as a result of
   * the user clicking the "Previous" button. Inside this method, subclasses
   * should make a note of their current state, so that they can decide what to
   * do when the user hits "Next".
   */
  public abstract void returnFromLaterStep();
  /**
   * Returns true if it is OK to redisplay the last version of the next panel,
   * or false if a new version is required.
   * 
   * @return boolean.
   */
  public abstract boolean canRedisplayNextPanel();
  /**
   * Returns true if there is a next panel.
   * 
   * @return boolean.
   */
  public abstract boolean hasNextPanel();
  /**
   * Returns true if it is possible to finish from this panel.
   * 
   * @return boolean.
   */
  public abstract boolean canFinish();
  /**
   * Returns the next panel in the sequence, given the current user input.
   * Returns null if this panel is the last one in the sequence.
   * 
   * @return the next panel in the sequence.
   */
  public abstract WizardPanel getNextPanel();
}
/*
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 * 
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info: http://www.jfree.org/jcommon/index.html
 * 
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library 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 Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * 
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. in the
 * United States and other countries.]
 * 
 * -------------------- L1R3ButtonPanel.java -------------------- (C) Copyright
 * 2000-2004, by Object Refinery Limited.
 * 
 * Original Author: David Gilbert (for Object Refinery Limited); Contributor(s): -;
 * 
 * $Id: L1R3ButtonPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $
 * 
 * Changes (from 26-Oct-2001) -------------------------- 26-Oct-2001 : Changed
 * package to com.jrefinery.ui.* (DG); 26-Jun-2002 : Removed unnecessary import
 * (DG); 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 
 */
/**
 * A "ready-made" panel that has one button on the left and three buttons on the
 * right - nested panels and layout managers take care of resizing.
 * 
 * @author David Gilbert
 */
class L1R3ButtonPanel extends JPanel {
  /** The left button. */
  private JButton left;
  /** The first button on the right of the panel. */
  private JButton right1;
  /** The second button on the right of the panel. */
  private JButton right2;
  /** The third button on the right of the panel. */
  private JButton right3;
  /**
   * Standard constructor - creates panel with the specified button labels.
   * 
   * @param label1
   *          the label for button 1.
   * @param label2
   *          the label for button 2.
   * @param label3
   *          the label for button 3.
   * @param label4
   *          the label for button 4.
   */
  public L1R3ButtonPanel(final String label1, final String label2, final String label3,
      final String label4) {
    setLayout(new BorderLayout());
    // create the pieces...
    final JPanel panel = new JPanel(new BorderLayout());
    final JPanel panel2 = new JPanel(new BorderLayout());
    this.left = new JButton(label1);
    this.right1 = new JButton(label2);
    this.right2 = new JButton(label3);
    this.right3 = new JButton(label4);
    // ...and put them together
    panel.add(this.left, BorderLayout.WEST);
    panel2.add(this.right1, BorderLayout.EAST);
    panel.add(panel2, BorderLayout.CENTER);
    panel.add(this.right2, BorderLayout.EAST);
    add(panel, BorderLayout.CENTER);
    add(this.right3, BorderLayout.EAST);
  }
  /**
   * Returns a reference to button 1, allowing the caller to set labels,
   * action-listeners etc.
   * 
   * @return the left button.
   */
  public JButton getLeftButton() {
    return this.left;
  }
  /**
   * Returns a reference to button 2, allowing the caller to set labels,
   * action-listeners etc.
   * 
   * @return the right button 1.
   */
  public JButton getRightButton1() {
    return this.right1;
  }
  /**
   * Returns a reference to button 3, allowing the caller to set labels,
   * action-listeners etc.
   * 
   * @return the right button 2.
   */
  public JButton getRightButton2() {
    return this.right2;
  }
  /**
   * Returns a reference to button 4, allowing the caller to set labels,
   * action-listeners etc.
   * 
   * @return the right button 3.
   */
  public JButton getRightButton3() {
    return this.right3;
  }
}





A Simple Modal Dialog

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AboutDialog extends JDialog implements ActionListener {
  public AboutDialog(JFrame parent, String title, String message) {
    super(parent, title, true);
    if (parent != null) {
      Dimension parentSize = parent.getSize(); 
      Point p = parent.getLocation(); 
      setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
    }
    JPanel messagePane = new JPanel();
    messagePane.add(new JLabel(message));
    getContentPane().add(messagePane);
    JPanel buttonPane = new JPanel();
    JButton button = new JButton("OK"); 
    buttonPane.add(button); 
    button.addActionListener(this);
    getContentPane().add(buttonPane, BorderLayout.SOUTH);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    pack(); 
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    setVisible(false); 
    dispose(); 
  }
  public static void main(String[] a) {
    AboutDialog dlg = new AboutDialog(new JFrame(), "title", "message");
  }
}





Dialog Introduction

  1. A dialog can be either modal or modeless.
  2. A modal dialog blocks user input to all other windows in the same application when it is visible. You have to close a modal dialog before other windows in the same application can get focus.
  3. A modeless one does not block user input.
  4. A dialog can belong to another dialog or a frame. Or, it can stand alone like a JFrame.



class Help extends JDialog {
  Help(Frame frame, String title) {
    super(frame, title);
    setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
    try {
      JEditorPane ep = new JEditorPane("file:///" + new File("").getAbsolutePath() + "/uchelp.html");
      ep.setEnabled(false);
      getContentPane().add(ep);
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(frame, "Unable to install editor pane");
      return;
    }
    setSize(200, 200);
    setLocationRelativeTo(frame);
    setVisible(true);
  }
}





Dialog Panel

/*
 * Enhydra Java Application Server Project
 *
 * The contents of this file are subject to the Enhydra Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License on
 * the Enhydra web site ( http://www.enhydra.org/ ).
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific terms governing rights and limitations
 * under the License.
 *
 * The Initial Developer of the Enhydra Application Server is Lutris
 * Technologies, Inc. The Enhydra Application Server and portions created
 * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
 * All Rights Reserved.
 *
 * Contributor(s):
 *
 */
// Standard imports
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.WindowEvent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
//
public class DialogPanel extends JPanel {
    public final static int CANCEL_OPTION = JOptionPane.CANCEL_OPTION;
    public final static int OK_OPTION = JOptionPane.OK_OPTION;
    //
    private int             option = DialogPanel.CANCEL_OPTION;
    private LocalDialog     dialog = null;
    private Window          owner = null;
    private boolean         windowClose = false;
    private boolean         standalone = false;
    private boolean         modal = true;
    private String          title = new String();
    public Window getOwner() {
        return owner;
    }
    public void setOwner(Window w) {
        owner = w;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String t) {
        title = t;
    }
    public boolean isModal() {
        return modal;
    }
    public void setModal(boolean b) {
        modal = b;
    }
    public int getOption() {
        return option;
    }
    public void setOption(int o) {
        option = o;
    }
    public LocalDialog getDialog() {
        return dialog;
    }
    public void startDialogThread() {
        Thread dialogThread = new Thread() {
            public void run() {
                showDialog();
            }
        };
        dialogThread.start();
    }
    public int showDialog() {
        BorderLayout layout = null;
        Point        cp = null;
        if (dialog == null) {
            if (getOwner() == null) {
                dialog = new LocalDialog();
            } else if (getOwner() instanceof Frame) {
                dialog = new LocalDialog((Frame) getOwner());
            } else if (getOwner() instanceof Dialog) {
                dialog = new LocalDialog((Dialog) getOwner());
            } else {
                dialog = new LocalDialog();
            }
        }
        dialog.setModal(isModal());
        dialog.setTitle(getTitle());
        layout = new BorderLayout();
        dialog.getRootPane().setLayout(layout);
        dialog.getRootPane().add(this, BorderLayout.CENTER);
        dialog.pack();
  
        dialog.show();
        return option;
    }
    //
    // PROTECTED
    //
    protected void hideDialog() {
        if (dialog != null) {
            dialog.setVisible(false);
        }
    }
    protected void clearDialog() {
        if (dialog != null) {
            dialog.setVisible(false);
            dialog.getRootPane().removeAll();
            dialog.removeAll();
            dialog.dispose();
        }
        if (isStandalone()) {
            System.exit(0);
        }
    }
    protected boolean isWindowClose() {
        return windowClose;
    }
    protected void setWindowClose(boolean b) {
        windowClose = b;
    }
    protected boolean isStandalone() {
        return standalone;
    }
    protected void setStandalone(boolean b) {
        standalone = b;
    }
    private class LocalDialog extends JDialog {
        public LocalDialog() {
            super();
        }
        public LocalDialog(Dialog owner) {
            super(owner);
        }
        public LocalDialog(Frame owner) {
            super(owner);
        }
        protected void processWindowEvent(WindowEvent e) {
            if (isWindowClose()) {
                if (e.getID() == WindowEvent.WINDOW_CLOSING) {
                    clearDialog();
                }
                super.processWindowEvent(e);
            }
        }
    }
}





Extending JDialog

If you need to extend JDialog, the class has two protected methods of importance:



protected void dialogInit()
protected JRootPane createRootPane()





extends JDialog to create your own dialog

/*
 * Copyright (c) 1995 - 2008 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:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - 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.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
/*
 * DialogDemo.java requires these files: CustomDialog.java images/middle.gif
 */
public class DialogDemo extends JPanel {
  JLabel label;
  ImageIcon icon = createImageIcon("images/middle.gif");
  JFrame frame;
  String simpleDialogDesc = "Some simple message dialogs";
  String iconDesc = "A JOptionPane has its choice of icons";
  String moreDialogDesc = "Some more dialogs";
  CustomDialog customDialog;
  /** Creates the GUI shown inside the frame"s content pane. */
  public DialogDemo(JFrame frame) {
    super(new BorderLayout());
    this.frame = frame;
    customDialog = new CustomDialog(frame, "geisel", this);
    customDialog.pack();
    // Create the components.
    JPanel frequentPanel = createSimpleDialogBox();
    JPanel featurePanel = createFeatureDialogBox();
    JPanel iconPanel = createIconDialogBox();
    label = new JLabel("Click the \"Show it!\" button"
        + " to bring up the selected dialog.", JLabel.CENTER);
    // Lay them out.
    Border padding = BorderFactory.createEmptyBorder(20, 20, 5, 20);
    frequentPanel.setBorder(padding);
    featurePanel.setBorder(padding);
    iconPanel.setBorder(padding);
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Simple Modal Dialogs", null, frequentPanel,
        simpleDialogDesc); // tooltip text
    tabbedPane.addTab("More Dialogs", null, featurePanel, moreDialogDesc); // tooltip
                                                                            // text
    tabbedPane.addTab("Dialog Icons", null, iconPanel, iconDesc); // tooltip
                                                                  // text
    add(tabbedPane, BorderLayout.CENTER);
    add(label, BorderLayout.PAGE_END);
    label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
  }
  /** Sets the text displayed at the bottom of the frame. */
  void setLabel(String newText) {
    label.setText(newText);
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = DialogDemo.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn"t find file: " + path);
      return null;
    }
  }
  /** Creates the panel shown by the first tab. */
  private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();
    JButton showItButton = null;
    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";
    radioButtons[0] = new JRadioButton("OK (in the L&F"s words)");
    radioButtons[0].setActionCommand(defaultMessageCommand);
    radioButtons[1] = new JRadioButton("Yes/No (in the L&F"s words)");
    radioButtons[1].setActionCommand(yesNoCommand);
    radioButtons[2] = new JRadioButton("Yes/No "
        + "(in the programmer"s words)");
    radioButtons[2].setActionCommand(yeahNahCommand);
    radioButtons[3] = new JRadioButton("Yes/No/Cancel "
        + "(in the programmer"s words)");
    radioButtons[3].setActionCommand(yncCommand);
    for (int i = 0; i < numButtons; i++) {
      group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);
    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String command = group.getSelection().getActionCommand();
        // ok dialog
        if (command == defaultMessageCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.");
          // yes/no dialog
        } else if (command == yesNoCommand) {
          int n = JOptionPane.showConfirmDialog(frame,
              "Would you like green eggs and ham?", "An Inane Question",
              JOptionPane.YES_NO_OPTION);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("Ewww!");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("Me neither!");
          } else {
            setLabel("Come on -- tell me!");
          }
          // yes/no (not in those words)
        } else if (command == yeahNahCommand) {
          Object[] options = { "Yes, please", "No way!" };
          int n = JOptionPane.showOptionDialog(frame,
              "Would you like green eggs and ham?", "A Silly Question",
              JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
              options, options[0]);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("You"re kidding!");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("I don"t like them, either.");
          } else {
            setLabel("Come on -- "fess up!");
          }
          // yes/no/cancel (not in those words)
        } else if (command == yncCommand) {
          Object[] options = { "Yes, please", "No, thanks", "No eggs, no ham!" };
          int n = JOptionPane.showOptionDialog(frame,
              "Would you like some green eggs to go " + "with that ham?",
              "A Silly Question", JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
          if (n == JOptionPane.YES_OPTION) {
            setLabel("Here you go: green eggs and ham!");
          } else if (n == JOptionPane.NO_OPTION) {
            setLabel("OK, just the ham, then.");
          } else if (n == JOptionPane.CANCEL_OPTION) {
            setLabel("Well, I"m certainly not going to eat them!");
          } else {
            setLabel("Please tell me what you want!");
          }
        }
        return;
      }
    });
    return createPane(simpleDialogDesc + ":", radioButtons, showItButton);
  }
  /**
   * Used by createSimpleDialogBox and createFeatureDialogBox to create a pane
   * containing a description, a single column of radio buttons, and the Show
   * it! button.
   */
  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.PAGE_AXIS));
    box.add(label);
    for (int i = 0; i < numChoices; i++) {
      box.add(radioButtons[i]);
    }
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.PAGE_START);
    pane.add(showButton, BorderLayout.PAGE_END);
    return pane;
  }
  /**
   * Like createPane, but creates a pane with 2 columns of radio buttons. The
   * number of buttons passed in *must* be even.
   */
  private JPanel create2ColPane(String description,
      JRadioButton[] radioButtons, JButton showButton) {
    JLabel label = new JLabel(description);
    int numPerColumn = radioButtons.length / 2;
    JPanel grid = new JPanel(new GridLayout(0, 2));
    for (int i = 0; i < numPerColumn; i++) {
      grid.add(radioButtons[i]);
      grid.add(radioButtons[i + numPerColumn]);
    }
    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    box.add(label);
    grid.setAlignmentX(0.0f);
    box.add(grid);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.PAGE_START);
    pane.add(showButton, BorderLayout.PAGE_END);
    return pane;
  }
  /*
   * Creates the panel shown by the 3rd tab. These dialogs are implemented using
   * showMessageDialog, but you can specify the icon (using similar code) for
   * any other kind of dialog, as well.
   */
  private JPanel createIconDialogBox() {
    JButton showItButton = null;
    final int numButtons = 6;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();
    final String plainCommand = "plain";
    final String infoCommand = "info";
    final String questionCommand = "question";
    final String errorCommand = "error";
    final String warningCommand = "warning";
    final String customCommand = "custom";
    radioButtons[0] = new JRadioButton("Plain (no icon)");
    radioButtons[0].setActionCommand(plainCommand);
    radioButtons[1] = new JRadioButton("Information icon");
    radioButtons[1].setActionCommand(infoCommand);
    radioButtons[2] = new JRadioButton("Question icon");
    radioButtons[2].setActionCommand(questionCommand);
    radioButtons[3] = new JRadioButton("Error icon");
    radioButtons[3].setActionCommand(errorCommand);
    radioButtons[4] = new JRadioButton("Warning icon");
    radioButtons[4].setActionCommand(warningCommand);
    radioButtons[5] = new JRadioButton("Custom icon");
    radioButtons[5].setActionCommand(customCommand);
    for (int i = 0; i < numButtons; i++) {
      group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);
    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String command = group.getSelection().getActionCommand();
        // no icon
        if (command == plainCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.", "A plain message",
              JOptionPane.PLAIN_MESSAGE);
          // information icon
        } else if (command == infoCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.",
              "Inane informational dialog", JOptionPane.INFORMATION_MESSAGE);
          // XXX: It doesn"t make sense to make a question with
          // XXX: only one button.
          // XXX: See "Yes/No (but not in those words)" for a better solution.
          // question icon
        } else if (command == questionCommand) {
          JOptionPane.showMessageDialog(frame,
              "You shouldn"t use a message dialog " + "(like this)\n"
                  + "for a question, OK?", "Inane question",
              JOptionPane.QUESTION_MESSAGE);
          // error icon
        } else if (command == errorCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.", "Inane error",
              JOptionPane.ERROR_MESSAGE);
          // warning icon
        } else if (command == warningCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.", "Inane warning",
              JOptionPane.WARNING_MESSAGE);
          // custom icon
        } else if (command == customCommand) {
          JOptionPane.showMessageDialog(frame,
              "Eggs aren"t supposed to be green.", "Inane custom dialog",
              JOptionPane.INFORMATION_MESSAGE, icon);
        }
      }
    });
    return create2ColPane(iconDesc + ":", radioButtons, showItButton);
  }
  /** Creates the panel shown by the second tab. */
  private JPanel createFeatureDialogBox() {
    final int numButtons = 5;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();
    JButton showItButton = null;
    final String pickOneCommand = "pickone";
    final String textEnteredCommand = "textfield";
    final String nonAutoCommand = "nonautooption";
    final String customOptionCommand = "customoption";
    final String nonModalCommand = "nonmodal";
    radioButtons[0] = new JRadioButton("Pick one of several choices");
    radioButtons[0].setActionCommand(pickOneCommand);
    radioButtons[1] = new JRadioButton("Enter some text");
    radioButtons[1].setActionCommand(textEnteredCommand);
    radioButtons[2] = new JRadioButton("Non-auto-closing dialog");
    radioButtons[2].setActionCommand(nonAutoCommand);
    radioButtons[3] = new JRadioButton("Input-validating dialog "
        + "(with custom message area)");
    radioButtons[3].setActionCommand(customOptionCommand);
    radioButtons[4] = new JRadioButton("Non-modal dialog");
    radioButtons[4].setActionCommand(nonModalCommand);
    for (int i = 0; i < numButtons; i++) {
      group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);
    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String command = group.getSelection().getActionCommand();
        // pick one of many
        if (command == pickOneCommand) {
          Object[] possibilities = { "ham", "spam", "yam" };
          String s = (String) JOptionPane.showInputDialog(frame,
              "Complete the sentence:\n" + "\"Green eggs and...\"",
              "Customized Dialog", JOptionPane.PLAIN_MESSAGE, icon,
              possibilities, "ham");
          // If a string was returned, say so.
          if ((s != null) && (s.length() > 0)) {
            setLabel("Green eggs and... " + s + "!");
            return;
          }
          // If you"re here, the return value was null/empty.
          setLabel("Come on, finish the sentence!");
          // text input
        } else if (command == textEnteredCommand) {
          String s = (String) JOptionPane
              .showInputDialog(frame, "Complete the sentence:\n"
                  + "\"Green eggs and...\"", "Customized Dialog",
                  JOptionPane.PLAIN_MESSAGE, icon, null, "ham");
          // If a string was returned, say so.
          if ((s != null) && (s.length() > 0)) {
            setLabel("Green eggs and... " + s + "!");
            return;
          }
          // If you"re here, the return value was null/empty.
          setLabel("Come on, finish the sentence!");
          // non-auto-closing dialog
        } else if (command == nonAutoCommand) {
          final JOptionPane optionPane = new JOptionPane(
              "The only way to close this dialog is by\n"
                  + "pressing one of the following buttons.\n"
                  + "Do you understand?", JOptionPane.QUESTION_MESSAGE,
              JOptionPane.YES_NO_OPTION);
          // You can"t use pane.createDialog() because that
          // method sets up the JDialog with a property change
          // listener that automatically closes the window
          // when a button is clicked.
          final JDialog dialog = new JDialog(frame, "Click a button", true);
          dialog.setContentPane(optionPane);
          dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
          dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
              setLabel("Thwarted user attempt to close window.");
            }
          });
          optionPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              if (dialog.isVisible() && (e.getSource() == optionPane)
                  && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
                // If you were going to check something
                // before closing the window, you"d do
                // it here.
                dialog.setVisible(false);
              }
            }
          });
          dialog.pack();
          dialog.setLocationRelativeTo(frame);
          dialog.setVisible(true);
          int value = ((Integer) optionPane.getValue()).intValue();
          if (value == JOptionPane.YES_OPTION) {
            setLabel("Good.");
          } else if (value == JOptionPane.NO_OPTION) {
            setLabel("Try using the window decorations "
                + "to close the non-auto-closing dialog. " + "You can"t!");
          } else {
            setLabel("Window unavoidably closed (ESC?).");
          }
          // non-auto-closing dialog with custom message area
          // NOTE: if you don"t intend to check the input,
          // then just use showInputDialog instead.
        } else if (command == customOptionCommand) {
          customDialog.setLocationRelativeTo(frame);
          customDialog.setVisible(true);
          String s = customDialog.getValidatedText();
          if (s != null) {
            // The text is valid.
            setLabel("Congratulations!  " + "You entered \"" + s + "\".");
          }
          // non-modal dialog
        } else if (command == nonModalCommand) {
          // Create the dialog.
          final JDialog dialog = new JDialog(frame, "A Non-Modal Dialog");
          // Add contents to it. It must have a close button,
          // since some L&Fs (notably Java/Metal) don"t provide one
          // in the window decorations for dialogs.
          JLabel label = new JLabel("<html><p align=center>"
              + "This is a non-modal dialog.<br>"
              + "You can have one or more of these up<br>"
              + "and still use the main window.");
          label.setHorizontalAlignment(JLabel.CENTER);
          Font font = label.getFont();
          label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));
          JButton closeButton = new JButton("Close");
          closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              dialog.setVisible(false);
              dialog.dispose();
            }
          });
          JPanel closePanel = new JPanel();
          closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
          closePanel.add(Box.createHorizontalGlue());
          closePanel.add(closeButton);
          closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));
          JPanel contentPane = new JPanel(new BorderLayout());
          contentPane.add(label, BorderLayout.CENTER);
          contentPane.add(closePanel, BorderLayout.PAGE_END);
          contentPane.setOpaque(true);
          dialog.setContentPane(contentPane);
          // Show it.
          dialog.setSize(new Dimension(300, 150));
          dialog.setLocationRelativeTo(frame);
          dialog.setVisible(true);
        }
      }
    });
    return createPane(moreDialogDesc + ":", radioButtons, showItButton);
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("DialogDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    DialogDemo newContentPane = new DialogDemo(frame);
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
/*
 * Copyright (c) 1995 - 2008 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:
 *  - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *  - 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.
 *  - Neither the name of Sun Microsystems nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */
/* 1.4 example used by DialogDemo.java. */
class CustomDialog extends JDialog implements ActionListener,
    PropertyChangeListener {
  private String typedText = null;
  private JTextField textField;
  private DialogDemo dd;
  private String magicWord;
  private JOptionPane optionPane;
  private String btnString1 = "Enter";
  private String btnString2 = "Cancel";
  /**
   * Returns null if the typed string was invalid; otherwise, returns the string
   * as the user entered it.
   */
  public String getValidatedText() {
    return typedText;
  }
  /** Creates the reusable dialog. */
  public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {
    super(aFrame, true);
    dd = parent;
    magicWord = aWord.toUpperCase();
    setTitle("Quiz");
    textField = new JTextField(10);
    // Create an array of the text and components to be displayed.
    String msgString1 = "What was Dr. SEUSS"s real last name?";
    String msgString2 = "(The answer is \"" + magicWord + "\".)";
    Object[] array = { msgString1, msgString2, textField };
    // Create an array specifying the number of dialog buttons
    // and their text.
    Object[] options = { btnString1, btnString2 };
    // Create the JOptionPane.
    optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE,
        JOptionPane.YES_NO_OPTION, null, options, options[0]);
    // Make this dialog display it.
    setContentPane(optionPane);
    // Handle window closing correctly.
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        /*
         * Instead of directly closing the window, we"re going to change the
         * JOptionPane"s value property.
         */
        optionPane.setValue(new Integer(JOptionPane.CLOSED_OPTION));
      }
    });
    // Ensure the text field always gets the first focus.
    addComponentListener(new ComponentAdapter() {
      public void componentShown(ComponentEvent ce) {
        textField.requestFocusInWindow();
      }
    });
    // Register an event handler that puts the text into the option pane.
    textField.addActionListener(this);
    // Register an event handler that reacts to option pane state changes.
    optionPane.addPropertyChangeListener(this);
  }
  /** This method handles events for the text field. */
  public void actionPerformed(ActionEvent e) {
    optionPane.setValue(btnString1);
  }
  /** This method reacts to state changes in the option pane. */
  public void propertyChange(PropertyChangeEvent e) {
    String prop = e.getPropertyName();
    if (isVisible()
        && (e.getSource() == optionPane)
        && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY
            .equals(prop))) {
      Object value = optionPane.getValue();
      if (value == JOptionPane.UNINITIALIZED_VALUE) {
        // ignore reset
        return;
      }
      // Reset the JOptionPane"s value.
      // If you don"t do this, then if the user
      // presses the same button next time, no
      // property change event will be fired.
      optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
      if (btnString1.equals(value)) {
        typedText = textField.getText();
        String ucText = typedText.toUpperCase();
        if (magicWord.equals(ucText)) {
          // we"re done; clear and dismiss the dialog
          clearAndHide();
        } else {
          // text was invalid
          textField.selectAll();
          JOptionPane.showMessageDialog(CustomDialog.this, "Sorry, \""
              + typedText + "\" " + "isn"t a valid response.\n"
              + "Please enter " + magicWord + ".", "Try again",
              JOptionPane.ERROR_MESSAGE);
          typedText = null;
          textField.requestFocusInWindow();
        }
      } else { // user closed dialog or clicked cancel
        dd.setLabel("It"s OK.  " + "We won"t force you to type " + magicWord
            + ".");
        typedText = null;
        clearAndHide();
      }
    }
  }
  /** This method clears the dialog and hides it. */
  public void clearAndHide() {
    textField.setText(null);
    setVisible(false);
  }
}





FontChooser by Noah w

/* This code was found posted on a forum without any copyright
 * restrictions. It was written by someone named Noah W.
 * That"s all I know */
/* I have modified the original code but claim no copyright on it of any kind */

/*
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
 */

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.FontUIResource;

//
// FontChooser by Noah w.
//
public class NwFontChooserS extends JDialog {
    String[] styleList = new String[] { "Plain", "Bold", "Italic" };
    String[] sizeList =
    new String[] {
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20",
        "22",
        "24",
        "27",
        "30",
        "34",
        "39",
        "45",
        "51",
        "60" };
        NwList StyleList;
        NwList FontList;
        NwList SizeList;
        static JLabel Sample = new JLabel();
        boolean ob = false;
        
        private NwFontChooserS(Frame parent, boolean modal, Font font) {
            super(parent, modal);
            initAll();
            setTitle("Font Choosr");
            if (font == null)
                font = Sample.getFont();
            FontList.setSelectedItem(font.getName());
            SizeList.setSelectedItem(font.getSize() + "");
            StyleList.setSelectedItem(styleList[font.getStyle()]);
            
        }
        public static Font showDialog(Frame parent, String s, Font font) {
            NwFontChooserS fd = new NwFontChooserS(parent, true, font);
            if (s != null)
                fd.setTitle(s);
            fd.setVisible(true);
            Font fo = null;
            if (fd.ob)
                fo = Sample.getFont();
            fd.dispose();
            return (fo);
        }
        private void initAll() {
            getContentPane().setLayout(null);
            setBounds(50, 50, 450, 450);
            addLists();
            addButtons();
            Sample.setBounds(10, 320, 415, 25);
            Sample.setForeground(Color.black);
            getContentPane().add(Sample);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    setVisible(false);
                }
            });
        }
        private void addLists() {
            FontList =
            new NwList(
            GraphicsEnvironment
            .getLocalGraphicsEnvironment()
            .getAvailableFontFamilyNames());
            StyleList = new NwList(styleList);
            SizeList = new NwList(sizeList);
            FontList.setBounds(10, 10, 260, 295);
            StyleList.setBounds(280, 10, 80, 295);
            SizeList.setBounds(370, 10, 40, 295);
            getContentPane().add(FontList);
            getContentPane().add(StyleList);
            getContentPane().add(SizeList);
        }
        private void addButtons() {
            JButton ok = new JButton("OK");
            ok.setMargin(new Insets(0, 0, 0, 0));
            JButton ca = new JButton("Cancel");
            ca.setMargin(new Insets(0, 0, 0, 0));
            ok.setBounds(260, 350, 70, 20);
            ok.setFont(new Font(" ", 1, 11));
            ca.setBounds(340, 350, 70, 20);
            ca.setFont(new Font(" ", 1, 12));
            getContentPane().add(ok);
            getContentPane().add(ca);
            ok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    ob = true;
                }
            });
            ca.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    ob = false;
                }
            });
        }
        private void showSample() {
            int g = 0;
            try {
                g = Integer.parseInt(SizeList.getSelectedValue());
            }
            catch (NumberFormatException nfe) {
            }
            String st = StyleList.getSelectedValue();
            int s = Font.PLAIN;
            if (st.equalsIgnoreCase("Bold"))
                s = Font.BOLD;
            if (st.equalsIgnoreCase("Italic"))
                s = Font.ITALIC;
            Sample.setFont(new Font(FontList.getSelectedValue(), s, g));
            Sample.setText("The quick brown fox jumped over the lazy dog.");
        }
        //////////////////////////////////////////////////////////////////////
        private class NwList extends JPanel {
            JList jl;
            JScrollPane sp;
            JLabel jt;
            String si = " ";
            
            public NwList(String[] values) {
                setLayout(null);
                jl = new JList(values);
                sp = new JScrollPane(jl);
                jt = new JLabel();
                jt.setBackground(Color.white);
                jt.setForeground(Color.black);
                jt.setOpaque(true);
                jt.setBorder(new JTextField().getBorder());
                jt.setFont(getFont());
                jl.setBounds(0, 0, 100, 1000);
                jl.setBackground(Color.white);
                jl.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                        jt.setText((String) jl.getSelectedValue());
                        si = (String) jl.getSelectedValue();
                        showSample();
                    }
                });
                add(sp);
                add(jt);
            }
            public String getSelectedValue() {
                return (si);
            }
            public void setSelectedItem(String s) {
                jl.setSelectedValue(s, true);
            }
            public void setBounds(int x, int y, int w, int h) {
                super.setBounds(x, y, w, h);
                sp.setBounds(0, y + 12, w, h - 23);
                sp.revalidate();
                jt.setBounds(0, 0, w, 20);
            }
        }
        
        static public String fontString(Font font) {
            String fs = font.getFamily();
            if( !font.isPlain() ) {
                fs += "-";
                if( font.isBold()) {
                    fs += "BOLD";
                }
                if( font.isItalic()) {
                    fs += "ITALIC";
                }
            }
            fs += "-" + font.getSize();
            return(fs);
        }
        
        static public void setDefaultFont(Font f ) {
            FontUIResource fui = new FontUIResource(f);
            Enumeration<Object> keys = UIManager.getDefaults().keys();
            while (keys.hasMoreElements()) {
                Object key = keys.nextElement();
                Object value = UIManager.get(key);
                if (value instanceof FontUIResource)
                    UIManager.put(key, fui);
            }
            
        }
        
        public static void main(String args[]) {
            Font font = null;
            font = NwFontChooserS.showDialog(null, null, null);
            
            System.out.println(fontString(font));
        }
}





Font Chooser extends javax.swing.JDialog

/*
Atlantida is an open source (GPL) multilingual dictionary written in Java.
It can translate words from one language to another and pronounce them.
Copyright (C) 2006 Sergey S. http://atla.revdanica.ru/
This program 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.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
/**
* FontChooser
* @author Janos Szatmary, Sergei S.
* @version 003
*/
/*
 * http://forum.java.sun.ru/thread.jsp?forum=57&thread=124810
 * For those who asked where"s the constructor, have in mind that the constructor provided
 * is private. As the author of the code says, the use of this class is as
 * follows (supposing we are in a Frame class):
 * FontChooser.showDialog(this,"FontChooser",new Font("Dialog", 0, 12));
 * This file originally writter by Janos Szatmary, then modifyed by Sergei S. for
 * Atlantida Multilingual Dictionary http://atla.sf.net
*/

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class FontChooser extends javax.swing.JDialog
{
  String[] styleList = new String[]
  { "Plain","Bold","Italic"};
  String[] sizeList = new String[]
  { "2","4","6","8","10","12","14","16","18","20","22","24","30","36","48","72"};
  String currentFont = null;
  int currentStyle = -1;
  int currentSize = -1;
  public boolean ok = false;
  /* ------------------------------------------------------------- */
  private FontChooser(java.awt.Frame parent,boolean modal)
  {
    super (parent,modal);
    initComponents();
    setListValues(jFontList,GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
    setListValues(jStyleList,styleList);
    setListValues(jSizeList,sizeList);
    setCurrentFont(jSample.getFont());
    pack();
  }
  private FontChooser(java.awt.Frame parent,boolean modal,Font font)
  {
    this(parent,modal);
    setCurrentFont(font);
  }
  /* ------------------------------------------------------------- */
  private void setListValues(JList list,String[] values)
  {
    if(list.getModel() instanceof DefaultListModel)
    {
      DefaultListModel model = (DefaultListModel)
                               list.getModel();
      model.removeAllElements();
      for( String value : values )
      {
        model.addElement( value );
      }
    }
  }
  /* ------------------------------------------------------------- */
  private void setSampleFont()
  {
    if(currentFont != null && currentStyle >= 0 && currentSize > 0)
    {
      jSample.setFont(new Font
                      (currentFont,currentStyle,currentSize));
    }
  }
  private String styleToString(int style)
  {
    String str = "";
    if((style&Font.BOLD) == Font.BOLD)
    {
      if(str.length() > 0)
      {
        str += ",";
      }
      str += "Bold";
    }
    if((style&Font.ITALIC) == Font.ITALIC)
    {
      if(str.length() > 0)
      {
        str += ",";
      }
      str += "Italic";
    }
    if( str.length() <= 0 )
    {
      str = "Plain";
    }
    return str;
  }
  /* ------------------------------------------------------------- */
  public Font getCurrentFont()
  {
    return jSample.getFont();
  }
  /* ------------------------------------------------------------- */
  public void setCurrentFont(Font font)
  {
    if(font==null)
    {
      font = jSample.getFont();
    }
    jFont.setText(font.getName());
    jFontActionPerformed(null);
    jStyle.setText(styleToString(font.getStyle()));
    jStyleActionPerformed(null);
    jSize.setText(Integer.toString(font.getSize()));
    jSizeActionPerformed(null);
  }

  // Create font chooser dialog.
  // If user selected a font (i.e. clicked OK button) - return the font that user has selected.
  // If user didn"t click OK button - return "null".
  public static Font showDialog( Frame parent, String title, Font font)
  {
    FontChooser dialog = new FontChooser(parent,true,font);
    Point p1 = parent.getLocation();
    Dimension d1 = parent.getSize();
    Dimension d2 = dialog.getSize();
    int x = p1.x+(d1.width-d2.width)/2;
    int y = p1.y+(d1.height-d2.height)/2;
    if(x < 0)
    {
      x = 0;
    }
    if(y < 0)
    {
      y = 0;
    }
    if(title!=null)
    {
      dialog.setTitle(title);
    }
    dialog.setLocation(x,y);
    dialog.setVisible(true);
    Font newfont = null;
    if(dialog.ok)
    {
      newfont = dialog.getCurrentFont();
    }
    dialog.dispose();
    return newfont;
  }
  /** This method is called from within the constructor to
  * initialize the form.
  * WARNING: Do NOT modify this code. The content of this method is
  * always regenerated by the FormEditor.
  */
  private void initComponents()
  {
    jPanel3 = new javax.swing.JPanel();
    jFont = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFontList = new javax.swing.JList();
    jPanel4 = new javax.swing.JPanel();
    jStyle = new javax.swing.JTextField();
    jScrollPane2 = new javax.swing.JScrollPane();
    jStyleList = new javax.swing.JList();
    jPanel5 = new javax.swing.JPanel();
    jSize = new javax.swing.JTextField();
    jScrollPane3 = new javax.swing.JScrollPane();
    jSizeList = new javax.swing.JList();
    jPanel1 = new javax.swing.JPanel();
    jScrollPane4 = new javax.swing.JScrollPane();
    jSample = new javax.swing.JTextArea();
    jButtons = new javax.swing.JPanel();
    jOk = new javax.swing.JButton();
    jCancel = new javax.swing.JButton();
    jLabel6 = new javax.swing.JLabel();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints1;
    setTitle("Font Chooser");
    addWindowListener(new java.awt.event.WindowAdapter()
                      {
                        public void windowClosing(java.awt.event.WindowEvent evt)
                        {
                          closeDialog(evt);
                        }
                      }
                     );
    jPanel3.setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints2;
    jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), " Font "));
    jFont.setColumns(24);
    jFont.addActionListener(new java.awt.event.ActionListener()
                            {
                              public void actionPerformed(java.awt.event.ActionEvent evt)
                              {
                                jFontActionPerformed(evt);
                              }
                            }
                           );
    gridBagConstraints2 = new java.awt.GridBagConstraints();
    gridBagConstraints2.gridwidth = 0;
    gridBagConstraints2.fill =
    java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints2.insets = new java.awt.Insets(0, 3, 0, 3);
    gridBagConstraints2.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints2.weightx = 1.0;
    jPanel3.add(jFont, gridBagConstraints2);

    jFontList.setModel(new DefaultListModel());
    jFontList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jFontList.addListSelectionListener(new javax.swing.event.ListSelectionListener()
                                       {
                                         public void valueChanged(javax.swing.event.ListSelectionEvent evt)
                                         {
                                           jFontListValueChanged(evt);
                                         }
                                       }
                                      );
    jScrollPane1.setViewportView(jFontList);
    gridBagConstraints2 = new java.awt.GridBagConstraints();
    gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints2.insets = new java.awt.Insets(3, 3, 3, 3);
    gridBagConstraints2.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints2.weightx = 1.0;
    gridBagConstraints2.weighty = 1.0;
    jPanel3.add(jScrollPane1, gridBagConstraints2);

    gridBagConstraints1 = new java.awt.GridBagConstraints();
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 0);
    gridBagConstraints1.weightx = 0.5;
    gridBagConstraints1.weighty = 1.0;
    getContentPane().add(jPanel3, gridBagConstraints1);

    jPanel4.setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints3;
    jPanel4.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), " Style "));
    jStyle.setColumns(18);
    jStyle.addActionListener(new java.awt.event.ActionListener()
                             {
                               public void actionPerformed(java.awt.event.ActionEvent evt)
                               {
                                 jStyleActionPerformed(evt);
                               }
                             }
                            );
    gridBagConstraints3 = new java.awt.GridBagConstraints();
    gridBagConstraints3.gridwidth = 0;
    gridBagConstraints3.fill =
    java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints3.insets = new java.awt.Insets(0, 3, 0, 3);
    gridBagConstraints3.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints3.weightx = 1.0;
    jPanel4.add(jStyle, gridBagConstraints3);
    jStyleList.setModel(new DefaultListModel());
    jStyleList.setVisibleRowCount(4);
    jStyleList.addListSelectionListener(new javax.swing.event.ListSelectionListener()
                                        {
                                          public void valueChanged(javax.swing.event.ListSelectionEvent evt)
                                          {
                                            jStyleListValueChanged(evt);
                                          }
                                        }
                                       );
    jScrollPane2.setViewportView(jStyleList);
    gridBagConstraints3 = new java.awt.GridBagConstraints();
    gridBagConstraints3.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints3.insets = new java.awt.Insets(3, 3, 3, 3);
    gridBagConstraints3.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints3.weightx = 0.5;
    gridBagConstraints3.weighty = 1.0;
    jPanel4.add(jScrollPane2, gridBagConstraints3);
    gridBagConstraints1 = new java.awt.GridBagConstraints();
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 0);
    gridBagConstraints1.weightx = 0.375;
    gridBagConstraints1.weighty = 1.0;
    getContentPane().add(jPanel4, gridBagConstraints1);
    jPanel5.setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints4;
    jPanel5.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), " Size "));
    jSize.setColumns(6);
    jSize.addActionListener(new
                            java.awt.event.ActionListener()
                            {
                              public void actionPerformed(java.awt.event.ActionEvent evt)
                              {
                                jSizeActionPerformed(evt);
                              }
                            }
                           );
    gridBagConstraints4 = new java.awt.GridBagConstraints();
    gridBagConstraints4.gridwidth = 0;
    gridBagConstraints4.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints4.insets = new java.awt.Insets(0, 3, 0, 3);
    gridBagConstraints4.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints4.weightx = 1.0;
    jPanel5.add(jSize, gridBagConstraints4);
    jSizeList.setModel(new DefaultListModel());
    jSizeList.setVisibleRowCount(4);
    jSizeList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jSizeList.addListSelectionListener(new javax.swing.event.ListSelectionListener()
                                       {
                                         public void valueChanged(javax.swing.event.ListSelectionEvent evt)
                                         {
                                           jSizeListValueChanged(evt);
                                         }
                                       }
                                      );
    jScrollPane3.setViewportView(jSizeList);
    gridBagConstraints4 = new java.awt.GridBagConstraints();
    gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints4.insets = new java.awt.Insets(3, 3, 3, 3);
    gridBagConstraints4.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints4.weightx = 0.25;
    gridBagConstraints4.weighty = 1.0;
    jPanel5.add(jScrollPane3, gridBagConstraints4);
    gridBagConstraints1 = new java.awt.GridBagConstraints();
    gridBagConstraints1.gridwidth = 0;
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.insets = new java.awt.Insets(5, 5, 0, 5);
    gridBagConstraints1.weightx = 0.125;
    gridBagConstraints1.weighty = 1.0;
    getContentPane().add(jPanel5, gridBagConstraints1);
    jPanel1.setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints5;
    jPanel1.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), " Sample "));
    jSample.setWrapStyleWord(true);
    jSample.setLineWrap(true);
    jSample.setColumns(20);
    jSample.setRows(3);
    jSample.setText("The quick brown fox jumped over the lazy dog.");
    jScrollPane4.setViewportView(jSample);
    gridBagConstraints5 = new java.awt.GridBagConstraints();
    gridBagConstraints5.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints5.insets = new java.awt.Insets(0, 3, 3, 3);
    gridBagConstraints5.weightx = 1.0;
    gridBagConstraints5.weighty = 1.0;
    jPanel1.add(jScrollPane4, gridBagConstraints5);
    gridBagConstraints1 = new java.awt.GridBagConstraints();
    gridBagConstraints1.gridwidth = 0;
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.insets = new java.awt.Insets(0, 5, 0, 5);
    gridBagConstraints1.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints1.weightx = 1.0;
    getContentPane().add(jPanel1, gridBagConstraints1);
    jButtons.setLayout(new java.awt.GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints6;
    jOk.setMnemonic(KeyEvent.VK_O);
    jOk.setText("OK");
    jOk.setRequestFocusEnabled(false);
    jOk.addActionListener(new java.awt.event.ActionListener()
                          {
                            public void actionPerformed(java.awt.event.ActionEvent evt)
                            {
                              jOkActionPerformed(evt);
                            }
                          }
                         );
    gridBagConstraints6 = new java.awt.GridBagConstraints();
    gridBagConstraints6.insets = new java.awt.Insets(5, 5, 5, 0);
    gridBagConstraints6.anchor = java.awt.GridBagConstraints.WEST;
    jButtons.add(jOk, gridBagConstraints6);

    jCancel.setMnemonic(KeyEvent.VK_C);
    jCancel.setText("Cancel");
    jCancel.setRequestFocusEnabled(false);
    jCancel.addActionListener(new
                              java.awt.event.ActionListener()
                              {
                                public void actionPerformed(java.awt.event.ActionEvent evt)
                                {
                                  jCancelActionPerformed(evt);
                                }
                              }
                             );
    gridBagConstraints6 = new java.awt.GridBagConstraints();
    gridBagConstraints6.gridwidth = 0;
    gridBagConstraints6.insets = new java.awt.Insets(5, 5, 5, 5);
    gridBagConstraints6.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints6.weightx = 1.0;
    jButtons.add(jCancel, gridBagConstraints6);
    gridBagConstraints6 = new java.awt.GridBagConstraints();
    gridBagConstraints6.weightx = 1.0;
    jButtons.add(jLabel6, gridBagConstraints6);
    gridBagConstraints1 = new java.awt.GridBagConstraints();
    gridBagConstraints1.gridwidth = 0;
    gridBagConstraints1.anchor = java.awt.GridBagConstraints.SOUTHWEST;
    gridBagConstraints1.weightx = 1.0;
    getContentPane().add(jButtons, gridBagConstraints1);
  }
  private void jCancelActionPerformed(java.awt.event.ActionEvent evt)
  {
    // Add your handling code here:
    setVisible(false);
  }
  private void jOkActionPerformed (java.awt.event.ActionEvent evt)
  {
    // Add your handling code here:
    ok = true;
    setVisible(false);
  }
  private void jSizeActionPerformed (java.awt.event.ActionEvent evt)
  {
    // Add your handling code here:
    int size = Integer.parseInt(jSize.getText());
    if(size > 0)
    {
      currentSize = size;
      setSampleFont();
    }
  }
  private void jStyleActionPerformed (java.awt.event.ActionEvent evt)
  {
    // Add your handling code here:
    StringTokenizer st = new StringTokenizer(jStyle.getText(),",");
    int style = 0;
    while(st.hasMoreTokens())
    {
      String str = st.nextToken().trim();
      if(str.equalsIgnoreCase("Plain"))
      {
        style |= Font.PLAIN;
      }
      else
        if(str.equalsIgnoreCase("Bold"))
      {
        style |= Font.BOLD;
      }
      else
        if(str.equalsIgnoreCase("Italic"))
      {
        style |= Font.ITALIC;
      }
    }
    if(style >= 0)
    {
      currentStyle = style;
      setSampleFont();
    }
  }
  private void jFontActionPerformed (java.awt.event.ActionEvent evt)
  {
    // Add your handling code here:
    DefaultListModel model = (DefaultListModel)
                             jFontList.getModel();
    if(model.indexOf(jFont.getText()) >= 0)
    {
      currentFont = jFont.getText();
      setSampleFont();
    }
  }
  private void jStyleListValueChanged(javax.swing.event.ListSelectionEvent evt)
  {
    // Add your handling code here:
    String str = "";
    Object[] values = jStyleList.getSelectedValues();
    if(values.length > 0)
    {
      int j;
      for(j=0; j < values.length; j++)
      {
        String s = (String) values[j];
        if(s.equalsIgnoreCase("Plain"))
        {
          str = "Plain";  break;
        }
        if(str.length() > 0)
        {
          str += ",";
        }
        str += (String) values[j];
      }
    }
    else
    {
      str = styleToString(currentStyle);
    }
    jStyle.setText(str);
    jStyleActionPerformed(null);
  }
  private void jSizeListValueChanged(javax.swing.event.ListSelectionEvent evt)
  {
    // Add your handling code here:
    String str = (String) jSizeList.getSelectedValue();
    if(str==null || str.length() <= 0)
    {
      str = Integer.toString(currentSize);
    }
    jSize.setText(str);
    jSizeActionPerformed(null);
  }
  private void jFontListValueChanged(javax.swing.event.ListSelectionEvent evt)
  {
    // Add your handling code here:
    String str = (String) jFontList.getSelectedValue();
    if(str==null || str.length() <= 0)
    {
      str = currentFont;
    }
    jFont.setText(str);
    jFontActionPerformed(null);
  }
  /** Closes the dialog */
  private void closeDialog(java.awt.event.WindowEvent evt)
  {
    setVisible (false);
  }
  // Variables declaration - do not modify
  private javax.swing.JPanel jPanel3;
  private javax.swing.JTextField jFont;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JList jFontList;
  private javax.swing.JPanel jPanel4;
  private javax.swing.JTextField jStyle;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JList jStyleList;
  private javax.swing.JPanel jPanel5;
  private javax.swing.JTextField jSize;
  private javax.swing.JScrollPane jScrollPane3;
  private javax.swing.JList jSizeList;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JScrollPane jScrollPane4;
  private javax.swing.JTextArea jSample;
  private javax.swing.JPanel jButtons;
  private javax.swing.JButton jOk;
  private javax.swing.JButton jCancel;
  private javax.swing.JLabel jLabel6;
  // End of variables declaration
}





JDialog is specify that pressing the Escape key cancels the dialog.

import java.awt.Frame;
import java.awt.event.ActionEvent;
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.JRootPane;
import javax.swing.KeyStroke;
class EscapeDialog extends JDialog {
  public EscapeDialog() {
    super((Frame) null, false);
  }
  protected JRootPane createRootPane() {
    JRootPane rootPane = new JRootPane();
    KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
    Action actionListener = new AbstractAction() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("about to disappear");
        setVisible(false);
      }
    };
    InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(stroke, "ESCAPE");
    rootPane.getActionMap().put("ESCAPE", actionListener);
    return rootPane;
  }
}
public class EscapeDialogTest {
  public static void main(String[] a) {
    EscapeDialog dlg = new EscapeDialog();
    dlg.add(new JButton("asdf"));
    dlg.setSize(300, 100);
    dlg.setVisible(true);
  }
}





Positions the specified dialog at a position relative to its parent.

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.lang.reflect.Method;
/**
 *
 *
 * @author David Gilbert
 */
public class Main{
  /**
   * Positions the specified dialog at a position relative to its parent.
   *
   * @param dialog  the dialog to be positioned.
   * @param horizontalPercent  the relative location.
   * @param verticalPercent  the relative location.
   */
  public static void positionDialogRelativeToParent(final Dialog dialog,
                                                    final double horizontalPercent,
                                                    final double verticalPercent) {
      final Dimension d = dialog.getSize();
      final Container parent = dialog.getParent();
      final Dimension p = parent.getSize();
      final int baseX = parent.getX() - d.width;
      final int baseY = parent.getY() - d.height;
      final int w = d.width + p.width;
      final int h = d.height + p.height;
      int x = baseX + (int) (horizontalPercent * w);
      int y = baseY + (int) (verticalPercent * h);
      // make sure the dialog fits completely on the screen...
      final Rectangle s = getMaximumWindowBounds();
      x = Math.min(x, (s.width - d.width));
      x = Math.max(x, 0);
      y = Math.min(y, (s.height - d.height));
      y = Math.max(y, 0);
      dialog.setBounds(x + s.x, y + s.y, d.width, d.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
   * results are returned. (See Sun-Bug-ID 4463949 for details).
   *
   * @return the maximum bounds of the current screen.
   */
    public static Rectangle getMaximumWindowBounds ()
    {
      final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try
      {
        final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null);
        return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
      }
      catch(Exception e)
      {
        // ignore ... will fail if this is not a JDK 1.4 ..
      }
      final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
      return new Rectangle (0, 0, s.width, s.height);
    }
}





Set Default Close Operation for Dialog

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Test extends JFrame {
  JDialog d = new JDialog(this, "Dialog title", true);
  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    d.getContentPane().add(new JLabel("Click the OK button"), BorderLayout.CENTER);
    JButton closeIt = new JButton("OK");
    closeIt.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Closing dialog");
        d.dispose();
      }
    });
    d.getContentPane().add(closeIt, BorderLayout.SOUTH);
    d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    d.pack();
    getContentPane().add(new JLabel("Placeholder label"));
    pack();
    setSize(200, 200);
    setVisible(true);
    d.setVisible(true);
  }
  public static void main(String[] args) {
    new Test();
  }
}





The base class for standard dialogs.

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -------------------
 * StandardDialog.java
 * -------------------
 * (C) Copyright 2000-2008, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Arnaud Lelievre;
 *
 * $Id: StandardDialog.java,v 1.7 2008/12/18 09:57:32 mungady Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 08-Sep-2003 : Added internationalization via use of properties
 *               resourceBundle (RFE 690236) (AL);
 * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by
 *               Jess Thrysoee (DG);
 *
 */
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

/**
 * The base class for standard dialogs.
 *
 * @author David Gilbert
 */
public class StandardDialog extends JDialog implements ActionListener {
    /** Flag that indicates whether or not the dialog was cancelled. */
    private boolean cancelled;

    /**
     * Standard constructor - builds a dialog...
     *
     * @param owner  the owner.
     * @param title  the title.
     * @param modal  modal?
     */
    public StandardDialog(final Frame owner, final String title,
            final boolean modal) {
        super(owner, title, modal);
        this.cancelled = false;
    }
    /**
     * Standard constructor - builds a dialog...
     *
     * @param owner  the owner.
     * @param title  the title.
     * @param modal  modal?
     */
    public StandardDialog(final Dialog owner, final String title,
            final boolean modal) {
        super(owner, title, modal);
        this.cancelled = false;
    }
    /**
     * Returns a flag that indicates whether or not the dialog has been
     * cancelled.
     *
     * @return boolean.
     */
    public boolean isCancelled() {
        return this.cancelled;
    }
    /**
     * Handles clicks on the standard buttons.
     *
     * @param event  the event.
     */
    public void actionPerformed(final ActionEvent event) {
        final String command = event.getActionCommand();
        if (command.equals("helpButton")) {
            // display help information
        }
        else if (command.equals("okButton")) {
            this.cancelled = false;
            setVisible(false);
        }
        else if (command.equals("cancelButton")) {
            this.cancelled = true;
            setVisible(false);
        }
    }
    /**
     * Builds and returns the user interface for the dialog.  This method is
     * shared among the constructors.
     *
     * @return the button panel.
     */
    protected JPanel createButtonPanel() {
        final L1R2ButtonPanel buttons = new L1R2ButtonPanel(
                "Help",
                "OK",
                "Cancel");
        final JButton helpButton = buttons.getLeftButton();
        helpButton.setActionCommand("helpButton");
        helpButton.addActionListener(this);
        final JButton okButton = buttons.getRightButton1();
        okButton.setActionCommand("okButton");
        okButton.addActionListener(this);
        final JButton cancelButton = buttons.getRightButton2();
        cancelButton.setActionCommand("cancelButton");
        cancelButton.addActionListener(this);
        buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
        return buttons;
    }
}
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * --------------------
 * L1R2ButtonPanel.java
 * --------------------
 * (C) Copyright 2000-2004, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: L1R2ButtonPanel.java,v 1.4 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Jun-2002 : Removed unnecessary import (DG);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 *
 */

/**
 * A "ready-made" panel that has one button on the left and two buttons on the right - nested
 * panels and layout managers take care of resizing.
 *
 * @author David Gilbert
 */
class L1R2ButtonPanel extends JPanel {
    /** The left button. */
    private JButton left;
    /** The first button on the right of the panel. */
    private JButton right1;
    /** The second button on the right of the panel. */
    private JButton right2;
    /**
     * Standard constructor - creates a three button panel with the specified button labels.
     *
     * @param label1  the label for button 1.
     * @param label2  the label for button 2.
     * @param label3  the label for button 3.
     */
    public L1R2ButtonPanel(final String label1, final String label2, final String label3) {
        setLayout(new BorderLayout());
        // create the pieces...
        this.left = new JButton(label1);
        final JPanel rightButtonPanel = new JPanel(new GridLayout(1, 2));
        this.right1 = new JButton(label2);
        this.right2 = new JButton(label3);
        rightButtonPanel.add(this.right1);
        rightButtonPanel.add(this.right2);
        // ...and put them together
        add(this.left, BorderLayout.WEST);
        add(rightButtonPanel, BorderLayout.EAST);
    }
    /**
     * Returns a reference to button 1, allowing the caller to set labels, action-listeners etc.
     *
     * @return the left button.
     */
    public JButton getLeftButton() {
        return this.left;
    }
    /**
     * Returns a reference to button 2, allowing the caller to set labels, action-listeners etc.
     *
     * @return the right button 1.
     */
    public JButton getRightButton1() {
        return this.right1;
    }
    /**
     * Returns a reference to button 3, allowing the caller to set labels, action-listeners etc.
     *
     * @return  the right button 2.
     */
    public JButton getRightButton2() {
        return this.right2;
    }
}