A dialog is another standard feature of user interfaces.
Dialogs are frequently used to present information to the user (“Your
fruit salad is ready.”) or to ask a question (“Shall I bring the car
around?”). Dialogs are used so commonly in GUI applications that Swing
includes a handy set of prebuilt dialogs. These are accessible from static
methods in the JOptionPane
class. Many
variations are possible; JOptionPane
groups them into four basic types:
- Message dialog
Displays a message to the user, usually accompanied by an OK button.
- Confirmation dialog
Ask a question and displays answer buttons—usually Yes, No, and Cancel.
- Input dialog
Asks the user to type in a string.
- Option dialogs
The most general type. You pass it your own components, which are displayed in the dialog.
A confirmation dialog is shown in Figure 17-13.
Let’s look at examples of each kind of dialog. The following code produces a message dialog:
JOptionPane
.
showMessageDialog
(
frame
,
"You have mail."
);
The first parameter to showMessageDialog()
is
the parent component (in this case, frame
, an existing JFrame
). The dialog will be centered on the
parent component. If you pass null
for
the parent component, the dialog is centered in your screen. The dialogs
that JOptionPane
displays are
modal, which means they block other input to your
application while they are showing.
Here’s a slightly fancier message dialog. We’ve specified a title for the dialog and a message type, which affects the icon that is displayed:
JOptionPane
.
showMessageDialog
(
frame
,
"You are low on memory."
,
"Apocalyptic message"
,
JOptionPane
.
WARNING_MESSAGE
);
Here’s how to display the confirmation dialog shown in Figure 17-13:
int
result
=
JOptionPane
.
showConfirmDialog
(
null
,
"Do you want to remove Windows now?"
);
In this case, we’ve passed null
for the parent component and it will be displayed centered on the screen.
Special values are returned from showConfirmDialog()
to
indicate which button was pressed. A full example later in this section
shows how to use this return value.
Sometimes you need to ask the user to type some input. The following code puts up a dialog requesting the user’s name:
String
name
=
JOptionPane
.
showInputDialog
(
null
,
"Please enter your name."
);
Whatever the user types is returned as a String
or null
if the user presses the Cancel
button.
The most general type of dialog is the option dialog. You supply an
array of objects you wish to be displayed; JOptionPane
takes care of formatting them and
displaying the dialog. The following example displays a text label, a
JTextField
, and a JPasswordField
. (Text components are described
in the next chapter.)
JTextField
userField
=
new
JTextField
();
JPasswordField
passField
=
new
JPasswordField
();
String
message
=
"Please enter your user name and password."
;
result
=
JOptionPane
.
showOptionDialog
(
frame
,
new
Object
[]
{
message
,
userField
,
passField
},
"Login"
,
JOptionPane
.
OK_CANCEL_OPTION
,
JOptionPane
.
QUESTION_MESSAGE
,
null
,
null
,
null
);
We’ve also specified a dialog title (“Login”) in the call to
showOptionDialog()
. We
want OK and Cancel buttons, so we pass OK_CANCEL_OPTION
as the
dialog type. The QUESTION_MESSAGE
argument
indicates we’d like to see the question mark icon. The last three items
are optional: an Icon
, an array of
different choices, and a current selection. Because the icon parameter is
null
, a default is used. If the array
of choices and the current selection parameters were not null
, JOptionPane
might try to display the choices in
a list or combo box.
The following application includes all the examples we’ve covered:
import
javax.swing.*
;
public
class
ExerciseOptions
{
public
static
void
main
(
String
[]
args
)
{
JFrame
frame
=
new
JFrame
(
"ExerciseOptions v1.0"
);
frame
.
setSize
(
200
,
200
);
frame
.
setVisible
(
true
);
JOptionPane
.
showMessageDialog
(
frame
,
"You have mail."
);
JOptionPane
.
showMessageDialog
(
frame
,
"You are low on memory."
,
"Apocalyptic message"
,
JOptionPane
.
WARNING_MESSAGE
);
int
result
=
JOptionPane
.
showConfirmDialog
(
null
,
"Do you want to remove Windows now?"
);
switch
(
result
)
{
case
JOptionPane
.
YES_OPTION
:
System
.
out
.
println
(
"Yes"
);
break
;
case
JOptionPane
.
NO_OPTION
:
System
.
out
.
println
(
"No"
);
break
;
case
JOptionPane
.
CANCEL_OPTION
:
System
.
out
.
println
(
"Cancel"
);
break
;
case
JOptionPane
.
CLOSED_OPTION
:
System
.
out
.
println
(
"Closed"
);
break
;
}
String
name
=
JOptionPane
.
showInputDialog
(
null
,
"Please enter your name."
);
System
.
out
.
println
(
name
);
JTextField
userField
=
new
JTextField
();
JPasswordField
passField
=
new
JPasswordField
();
String
message
=
"Please enter your user name and password."
;
result
=
JOptionPane
.
showOptionDialog
(
frame
,
new
Object
[]
{
message
,
userField
,
passField
},
"Login"
,
JOptionPane
.
OK_CANCEL_OPTION
,
JOptionPane
.
QUESTION_MESSAGE
,
null
,
null
,
null
);
if
(
result
==
JOptionPane
.
OK_OPTION
)
System
.
out
.
println
(
userField
.
getText
()
+
" "
+
new
String
(
passField
.
getPassword
()));
System
.
exit
(
0
);
}
}
A JFileChooser
is a
standard file selection box. As with other Swing components, JFileChooser
is implemented in pure Java, so
it can look and act the same on different platforms or take on the
native appearance of the operating system, depending on what look and
feel is in effect.
Selecting files all day can be pretty boring without a greater
purpose, so we’ll exercise the JFileChooser
in a mini-editor application.
Editor
provides a text area in which
we can load and work with files. (The JFileChooser
created by Editor
is shown in Figure 17-14.) We’ll stop just shy of the
capability to save and let you fill in the blanks (with a few
caveats).
Here’s the code:
import
java.awt.*
;
import
java.awt.event.*
;
import
java.io.*
;
import
javax.swing.*
;
public
class
Editor
extends
JFrame
implements
ActionListener
{
private
JEditorPane
textPane
=
new
JEditorPane
();
public
Editor
()
{
super
(
"Editor v1.0"
);
Container
content
=
getContentPane
();
// unnecessary in 5.0+
content
.
add
(
new
JScrollPane
(
textPane
),
BorderLayout
.
CENTER
);
JMenu
menu
=
new
JMenu
(
"File"
);
menu
.
add
(
makeMenuItem
(
"Open"
));
menu
.
add
(
makeMenuItem
(
"Save"
));
menu
.
add
(
makeMenuItem
(
"Quit"
));
JMenuBar
menuBar
=
new
JMenuBar
();
menuBar
.
add
(
menu
);
setJMenuBar
(
menuBar
);
setSize
(
300
,
300
);
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
}
public
void
actionPerformed
(
ActionEvent
e
)
{
String
command
=
e
.
getActionCommand
();
if
(
command
.
equals
(
"Quit"
))
System
.
exit
(
0
);
else
if
(
command
.
equals
(
"Open"
))
loadFile
();
else
if
(
command
.
equals
(
"Save"
))
saveFile
();
}
private
void
loadFile
()
{
JFileChooser
chooser
=
new
JFileChooser
();
int
result
=
chooser
.
showOpenDialog
(
this
);
if
(
result
==
JFileChooser
.
CANCEL_OPTION
)
return
;
try
{
File
file
=
chooser
.
getSelectedFile
();
java
.
net
.
URL
url
=
file
.
toURL
();
textPane
.
setPage
(
url
);
}
catch
(
Exception
e
)
{
textPane
.
setText
(
"Could not load file: "
+
e
);
}
}
private
void
saveFile
()
{
JFileChooser
chooser
=
new
JFileChooser
();
chooser
.
showSaveDialog
(
this
);
// Save file data...
}
private
JMenuItem
makeMenuItem
(
String
name
)
{
JMenuItem
m
=
new
JMenuItem
(
name
);
m
.
addActionListener
(
this
);
return
m
;
}
public
static
void
main
(
String
[]
s
)
{
new
Editor
().
setVisible
(
true
);
}
}
Editor
is a JFrame
that lays itself out with a JEditorPane
(which is covered in Chapter 18) and a pull-down menu. From the pull-down
File menu, we can Open, Save, or Quit. The actionPerformed()
method catches the events
associated with these menu selections and takes the appropriate
action.
The interesting parts of Editor
are the private
methods loadFile()
and saveFile()
. The loadFile()
method creates a new JFileChooser
and calls its showOpenDialog()
method.
A JFileChooser
does its work
when the showOpenDialog()
method is
called. This method blocks the caller until the dialog completes its
job, at which time the file chooser disappears. After that, we can
retrieve the designated file with the getFile()
method. In loadFile()
, we convert the selected File
to a URL
and pass it to the JEditorPane
, which displays the selected file.
As you’ll learn in the next chapter, JEditorPane
can display HTML and RTF
files.
You can fill out the unfinished saveFile()
method if you wish, but it would be
prudent to add the standard safety precautions. For example, you could
use one of the confirmation dialogs we just looked at to prompt the user
before overwriting an existing file.
Swing is chock full of goodies. JColorChooser
is yet another ready-made dialog
supplied with Swing; it allows your users to choose colors. The
following brief example shows how easy it is to use JColorChooser
:
import
java.awt.*
;
import
java.awt.event.*
;
import
javax.swing.*
;
public
class
LocalColor
{
public
static
void
main
(
String
[]
args
)
{
final
JFrame
frame
=
new
JFrame
(
"LocalColor v1.0"
);
final
Container
content
=
frame
.
getContentPane
();
// unnecessary in 5.0+
content
.
setLayout
(
new
GridBagLayout
());
JButton
button
=
new
JButton
(
"Change color..."
);
content
.
add
(
button
);
button
.
addActionListener
(
new
ActionListener
()
{
public
void
actionPerformed
(
ActionEvent
e
)
{
Color
c
=
JColorChooser
.
showDialog
(
frame
,
"Choose a color"
,
content
.
getBackground
());
if
(
c
!=
null
)
content
.
setBackground
(
c
);
}
});
frame
.
setSize
(
200
,
200
);
frame
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
frame
.
setVisible
(
true
);
}
}
This example shows a frame window with a single button. When you click on the button, a color chooser pops up. After you select a color, it becomes the background color of the frame window.
Basically, all we have to do is call JColorChooser
’s static method showDialog()
. In this
example, we specified a parent component, a dialog title, and an initial
color value. But you can get away with just specifying a parent
component. Whatever color the user chooses is returned; if the user
presses the Cancel button, null
is
returned.
Get Learning Java, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.