import java.awt.*;
import javax.swing.*;
/**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/publicclassOptionDialogTest
{publicstaticvoidmain(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new OptionDialogFrame();
frame.setTitle("OptionDialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
/**
* A frame that contains settings for selecting various option dialogs.
*/publicclassOptionDialogFrameextendsJFrame
{private ButtonPanel typePanel;
private ButtonPanel messagePanel;
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messageString = "Message";
private Icon messageIcon = new ImageIcon("blue-ball.gif");
private Object messageObject = new Date();
private Component messageComponent = new SampleComponent();
publicOptionDialogFrame()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(2, 3));
typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other",
"Object[]");
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
"YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
gridPanel.add(typePanel);
gridPanel.add(messageTypePanel);
gridPanel.add(messagePanel);
gridPanel.add(optionTypePanel);
gridPanel.add(optionsPanel);
gridPanel.add(inputPanel);
// add a panel with a Show button
JPanel showPanel = new JPanel();
JButton showButton = new JButton("Show");
showButton.addActionListener(new ShowAction());
showPanel.add(showButton);
add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack();
}
/**
* Gets the currently selected message.
* @return a string, icon, component, or object array, depending on the Message panel selection
*/public Object getMessage()
{
String s = messagePanel.getSelection();
if (s.equals("String")) return messageString;
elseif (s.equals("Icon")) return messageIcon;
elseif (s.equals("Component")) return messageComponent;
elseif (s.equals("Object[]")) returnnew Object[] { messageString, messageIcon,
messageComponent, messageObject };
elseif (s.equals("Other")) return messageObject;
elsereturnnull;
}
/**
* Gets the currently selected options.
* @return an array of strings, icons, or objects, depending on the Option panel selection
*/public Object[] getOptions()
{
String s = optionsPanel.getSelection();
if (s.equals("String[]")) returnnew String[] { "Yellow", "Blue", "Red" };
elseif (s.equals("Icon[]")) returnnew Icon[] { new ImageIcon("yellow-ball.gif"),
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
elseif (s.equals("Object[]")) returnnew Object[] { messageString, messageIcon,
messageComponent, messageObject };
elsereturnnull;
}
/**
* Gets the selected message or option type
* @param panel the Message Type or Confirm panel
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
*/publicintgetType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -1;
}
}
/**
* The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
* depending on the Type panel selection.
*/privateclassShowActionimplementsActionListener
{publicvoidactionPerformed(ActionEvent event)
{
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
elseif (typePanel.getSelection().equals("Input"))
{
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
"Blue");
}
elseif (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
elseif (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions(), getOptions()[0]);
}
}
}
/**
* A component with a painted surface
*/
class SampleComponent extends JComponent
{
publicvoidpaintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
g2.setPaint(Color.YELLOW);
g2.fill(rect);
g2.setPaint(Color.BLUE);
g2.draw(rect);
}
public Dimension getPreferredSize()
{
returnnew Dimension(10, 10);
}
}
import javax.swing.*;
/**
* A panel with radio buttons inside a titled border.
*/publicclassButtonPanelextendsJPanel
{private ButtonGroup group;
/**
* Constructs a button panel.
* @param title the title shown in the border
* @param options an array of radio button labels
*/publicButtonPanel(String title, String... options)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
group = new ButtonGroup();
// make one radio button for each optionfor (String option : options)
{
JRadioButton b = new JRadioButton(option);
b.setActionCommand(option);
add(b);
group.add(b);
b.setSelected(option == options[0]);
}
}
/**
* Gets the currently selected option.
* @return the label of the currently selected radio button.
*/public String getSelection()
{
return group.getSelection().getActionCommand();
}
}
2 创建对话框
import java.awt.*;
import javax.swing.*;
/**
* @version 1.34 2012-06-12
* @author Cay Horstmann
*/publicclassDialogTest
{publicstaticvoidmain(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new DialogFrame();
frame.setTitle("DialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
/**
* A frame with a menu whose File->About action shows a dialog.
*/publicclassDialogFrameextendsJFrame
{privatestaticfinalint DEFAULT_WIDTH = 300;
privatestaticfinalint DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
publicDialogFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Construct a File menu.
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// Add About and Exit menu items.// The About item shows the About dialog.
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.addActionListener(event -> {
if (dialog == null) // first time
dialog = new AboutDialog(DialogFrame.this);
dialog.setVisible(true); // pop up dialog
});
fileMenu.add(aboutItem);
// The Exit item exits the program.
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
fileMenu.add(exitItem);
}
}
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* A sample modal dialog that displays a message and waits for the user to click the OK button.
*/publicclassAboutDialogextendsJDialog
{publicAboutDialog(JFrame owner)
{
super(owner, "About DialogTest", true);
// add HTML label to center
add(
new JLabel(
"<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
BorderLayout.CENTER);
// OK button closes the dialog
JButton ok = new JButton("OK");
ok.addActionListener(event -> setVisible(false));
// add OK button to southern border
JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
pack();
}
}
3 数据交互
import java.awt.*;
import javax.swing.*;
/**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/publicclassDataExchangeTest
{publicstaticvoidmain(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new DataExchangeFrame();
frame.setTitle("DataExchangeTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* A frame with a menu whose File->Connect action shows a password dialog.
*/publicclassDataExchangeFrameextendsJFrame
{publicstaticfinalint TEXT_ROWS = 20;
publicstaticfinalint TEXT_COLUMNS = 40;
private PasswordChooser dialog = null;
private JTextArea textArea;
publicDataExchangeFrame()
{
// construct a File menu
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
// add Connect and Exit menu items
JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem);
// The Exit item exits the program
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
fileMenu.add(exitItem);
textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack();
}
/**
* The Connect action pops up the password dialog.
*/privateclassConnectActionimplementsActionListener
{publicvoidactionPerformed(ActionEvent event)
{
// if first time, construct dialogif (dialog == null) dialog = new PasswordChooser();
// set default values
dialog.setUser(new User("yourname", null));
// pop up dialogif (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
* A password chooser that is shown inside a dialog
*/publicclassPasswordChooserextendsJPanel
{private JTextField username;
private JPasswordField password;
private JButton okButton;
privateboolean ok;
private JDialog dialog;
publicPasswordChooser()
{
setLayout(new BorderLayout());
// construct a panel with user name and password fields
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new JLabel("User name:"));
panel.add(username = new JTextField(""));
panel.add(new JLabel("Password:"));
panel.add(password = new JPasswordField(""));
add(panel, BorderLayout.CENTER);
// create Ok and Cancel buttons that terminate the dialog
okButton = new JButton("Ok");
okButton.addActionListener(event -> {
ok = true;
dialog.setVisible(false);
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false));
// add buttons to southern border
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Sets the dialog defaults.
* @param u the default user information
*/publicvoidsetUser(User u)
{
username.setText(u.getName());
}
/**
* Gets the dialog entries.
* @return a User object whose state represents the dialog entries
*/public User getUser()
{
returnnew User(username.getText(), password.getPassword());
}
/**
* Show the chooser panel in a dialog
* @param parent a component in the owner frame or null
* @param title the dialog window title
*/publicbooleanshowDialog(Component parent, String title)
{
ok = false;
// locate the owner frame
Frame owner = null;
if (parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
// if first time, or if owner has changed, make new dialogif (dialog == null || dialog.getOwner() != owner)
{
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
}
// set title and show dialog
dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}
publicclassUser
{private String name;
privatechar[] password;
publicUser(String aName, char[] aPassword)
{
name = aName;
password = aPassword;
}
public String getName()
{
return name;
}
publicchar[] getPassword()
{
return password;
}
publicvoidsetName(String aName)
{
name = aName;
}
publicvoidsetPassword(char[] aPassword)
{
password = aPassword;
}
}
4 文件对话框
import java.awt.*;
import javax.swing.*;
/**
* @version 1.25 2015-06-12
* @author Cay Horstmann
*/publicclassFileChooserTest
{publicstaticvoidmain(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new ImageViewerFrame();
frame.setTitle("FileChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
/**
* A frame that has a menu for loading an image and a display area for the
* loaded image.
*/publicclassImageViewerFrameextendsJFrame
{privatestaticfinalint DEFAULT_WIDTH = 300;
privatestaticfinalint DEFAULT_HEIGHT = 400;
private JLabel label;
private JFileChooser chooser;
publicImageViewerFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// set up menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(event -> {
chooser.setCurrentDirectory(new File("."));
// show file chooser dialogint result = chooser.showOpenDialog(ImageViewerFrame.this);
// if image file accepted, set it as icon of the labelif (result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
pack();
}
});
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event -> System.exit(0));
// use a label to display the images
label = new JLabel();
add(label);
// set up file chooser
chooser = new JFileChooser();
// accept all image files ending with .jpg, .jpeg, .gif
FileFilter filter = new FileNameExtensionFilter(
"Image files", "jpg", "jpeg", "gif");
chooser.setFileFilter(filter);
chooser.setAccessory(new ImagePreviewer(chooser));
chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
}
}
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
/**
* A file view that displays an icon for all files that match a file filter.
*/publicclassFileIconViewextendsFileView
{private FileFilter filter;
private Icon icon;
/**
* Constructs a FileIconView.
* @param aFilter a file filter--all files that this filter accepts will be shown
* with the icon.
* @param anIcon--the icon shown with all accepted files.
*/publicFileIconView(FileFilter aFilter, Icon anIcon)
{
filter = aFilter;
icon = anIcon;
}
public Icon getIcon(File f)
{
if (!f.isDirectory() && filter.accept(f)) return icon;
elsereturnnull;
}
}
import java.awt.*;
import java.io.*;
import javax.swing.*;
/**
* A file chooser accessory that previews images.
*/publicclassImagePreviewerextendsJLabel
{/**
* Constructs an ImagePreviewer.
* @param chooser the file chooser whose property changes trigger an image
* change in this previewer
*/publicImagePreviewer(JFileChooser chooser)
{
setPreferredSize(new Dimension(100, 100));
setBorder(BorderFactory.createEtchedBorder());
chooser.addPropertyChangeListener(event -> {
if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
// the user has selected a new file
File f = (File) event.getNewValue();
if (f == null)
{
setIcon(null);
return;
}
// read the image into an icon
ImageIcon icon = new ImageIcon(f.getPath());
// if the icon is too large to fit, scale itif (icon.getIconWidth() > getWidth())
icon = new ImageIcon(icon.getImage().getScaledInstance(
getWidth(), -1, Image.SCALE_DEFAULT));
setIcon(icon);
}
});
}
}
5 颜色对话框
import java.awt.*;
import javax.swing.*;
/**
* @version 1.04 2015-06-12
* @author Cay Horstmann
*/publicclassColorChooserTest
{publicstaticvoidmain(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new ColorChooserFrame();
frame.setTitle("ColorChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JPanel;
/**
* A panel with buttons to pop up three types of color choosers
*/publicclassColorChooserPanelextendsJPanel
{publicColorChooserPanel()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());
add(modalButton);
JButton modelessButton = new JButton("Modeless");
modelessButton.addActionListener(new ModelessListener());
add(modelessButton);
JButton immediateButton = new JButton("Immediate");
immediateButton.addActionListener(new ImmediateListener());
add(immediateButton);
}
/**
* This listener pops up a modal color chooser
*/privateclassModalListenerimplementsActionListener
{publicvoidactionPerformed(ActionEvent event)
{
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
defaultColor);
if (selected != null) setBackground(selected);
}
}
/**
* This listener pops up a modeless color chooser. The panel color is changed when the user
* clicks the OK button.
*/privateclassModelessListenerimplementsActionListener
{private JDialog dialog;
private JColorChooser chooser;
publicModelessListener()
{
chooser = new JColorChooser();
dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
false/* not modal */, chooser,
event -> setBackground(chooser.getColor()),
null/* no Cancel button listener */);
}
publicvoidactionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
/**
* This listener pops up a modeless color chooser. The panel color is changed immediately when
* the user picks a new color.
*/privateclassImmediateListenerimplementsActionListener
{private JDialog dialog;
private JColorChooser chooser;
publicImmediateListener()
{
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(
event -> setBackground(chooser.getColor()));
dialog = new JDialog((Frame) null, false/* not modal */);
dialog.add(chooser);
dialog.pack();
}
publicvoidactionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
}
import javax.swing.*;
/**
* A frame with a color chooser panel
*/publicclassColorChooserFrameextendsJFrame
{privatestaticfinalint DEFAULT_WIDTH = 300;
privatestaticfinalint DEFAULT_HEIGHT = 200;
publicColorChooserFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add color chooser panel to frame
ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
}