421
Summary
Graphical user interfaces (GUIs) provide more convenient and intuitive input for
users. However, they also take more programming effort than the simple line-
oriented I/O that we’ve used in the past. Java is one of the first widely used
languages to offer extensive support for GUI programming.
The basic window object is a JFrame; it provides a content pane in the form of a
Containerobject that is returned by the getContentPaneinstance method. We add user in-
terface objects to the content pane with the addmethod, and we remove them with the
removemethod. As part of creating a JFrame, we must specify its default closing operation,
its size, and the layout manager to use for its content pane. We use setVisible(true)to
make the frame appear on the screen and dispose()to remove the frame.
Objects that we can place into a content pane include a JLabel,JTextField, and
JButton. We can change the contents of a JLabelor JTextFieldwith setText, and we
can retrieve the Stringvalue of a JTextFieldwith getText.A JPanelis another class,
with similarities to a content pane, that we can use to preassemble groups of
interface elements. We can then add the whole JPanelas a unit to the content pane
of a JFrame, so that the group of elements appears together.
We must register an event listener with an event source, such as a button, to han-
dle events from the source. The event listener is registered with a call to
addActionListener. An event handler is a method in a class definition that follows the
specification of the ActionListenerinterface.
Event loops provide an implicit way of repeating actions in event-driven applica-
tions. We must check that an event loop is designed properly and that all of its
aspects are implemented correctly.
When a user interface includes multiple buttons, we can use the string associated
with each button to determine which one was clicked. The event handler is passed
an ActionEventvalue as a parameter, and we call its associated value-returning
instance method,getActionCommand, to retrieve the string associated with the button.
Quick Check
1.What contains a content pane, and what does a content pane contain? (pp.
376–380)
2.Where is an event sent when a user clicks a button with the mouse? (pp. 385–393)
3.Where does updating of the process within an event loop occur? (pp. 393–394)
4.What is the handler method to which button events are sent? (pp. 385–393)
5.Write statements that declare a privateJTextFieldvariable called dataField, in-
stantiate a corresponding object, and add it to a content pane called outPane.
(pp. 394–398)
6.Write a statement that adds a label with the message"Quick Check"tooutPane.
(pp. 376–380)