Java Reference
In-Depth Information
GUIs are potentially very complex entities because they involve a large number of
interacting objects and classes. Each onscreen component and window is represented
by an object, so a programmer starting out with GUIs must learn many new class,
method, and package names. In addition, if the GUI is to perform sophisticated tasks,
the objects must interact with each other and call each other's methods, which raises
tricky communication and scoping issues.
Another factor that makes writing GUIs challenging is that the path of code execu-
tion becomes nondeterministic. When a GUI program is running, the user can click
any of the buttons and interact with any of the other onscreen components in any
order. Because the program's execution is driven by the series of events that occur,
we say that programs with GUIs are
event-driven.
In this chapter you'll learn how to
handle user events so that your event-driven graphical programs will respond appro-
priately to user interaction.
The simplest way to create a graphical window in Java is to have an
option pane
pop
up. An option pane is a simple message box that appears on the screen and presents a
message or a request for input to the user.
The Java class used to show option panes is called
JOptionPane
.
JOptionPane
belongs to the
javax.swing
package, so you'll need to import this package to use it.
(“Swing” is the name of one of Java's GUI libraries.) Note that the package name
starts with
javax
this time, not
java
. The
x
is because, in Java's early days, Swing
was an extension to Java's feature set.
import javax.swing.*; // for GUI components
JOptionPane
can be thought of as a rough graphical equivalent of
System.out.println
output and
Scanner
console input. The following program
creates a “Hello, world!” message on the screen with the use of
JOptionPane
:
1 // A graphical equivalent of the classic "Hello world" program.
2
3
import
javax.swing.*; // for GUI components
4
5
public class
HelloWorld {
6
public static void
main(String[] args) {
7 JOptionPane.showMessageDialog(
null
, "Hello, world!");
8 }
9 }
The program produces the following graphical “output” (we'll show screenshots
for the output of the programs in this chapter):
Search WWH ::
Custom Search