Você está na página 1de 10

Second AP* Edition

— with GridWorld

Java
Methods
Object-Oriented Programming
and
Data Structures

Maria Litvin
Phillips Academy, Andover, Massachusetts

Gary Litvin
Skylight Software, Inc.

Skylight Publishing
Andover, Massachusetts
Skylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810

web: http://www.skylit.com
e-mail: sales@skylit.com
support@skylit.com

Copyright © 2011 by Maria Litvin, Gary Litvin, and


Skylight Publishing

All rights reserved. No part of this publication may be reproduced,


stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without
the prior written permission of the authors and Skylight Publishing.

Library of Congress Control Number: 2010915303

ISBN 978-0-9824775-7-1
*
AP and Advanced Placement are registered trademarks of The College Board, which was
not involved in the production of and does not endorse this book.

The names of commercially available software and products mentioned in this book are
used for identification purposes only and may be trademarks or registered trademarks
owned by corporations and other commercial entities. Skylight Publishing and the authors
have no affiliation with and disclaim any sponsorship or endorsement by any of these
product manufacturers or trademark owners.

Oracle, Java, and Java logos are trademarks or registered trademarks of Oracle Corporation
and/or its affiliates in the U.S. and other countries.

SCRABBLE® is the registered trademark of HASBRO in the United States and Canada and
of J.W. Spear and Sons, PLC, a subsidiary of Mattel, Inc., outside the United States and
Canada.

1 2 3 4 5 6 7 8 9 10 16 15 14 13 12 11

Printed in the United States of America


Chapter: 17

17 GUI Components and Events


17.1 Prologue 434
Copyright © 2011 by Skylight Publishing

17.2 Pluggable Look and Feel 


17.3 Basic Swing Components and Their Events
17.4 Layouts
17.5 Menus
17.6 Case Study and Lab: the Ramblecs Game
17.7 Summary
Exercises 436

433
434 CHAPTER 17 ~ GUI COMPONENTS AND EVENTS

17.1 Prologue
In this chapter we discuss the basics of graphical user interfaces and event-driven
programming in Java. Event-driven GUI is what made the OOP concept popular,
and it remains the area where it’s most relevant. While you can write console
applications in Java, such programs won’t take full advantage of Java or OOP; in
most cases such programs could just as well be written in C or Python. The style of
modern user interfaces — with many different types of control components such as
menus, buttons, pull-down lists, checkboxes, radio buttons, and text edit fields —
provides an arena where OOP and event-driven programming naturally excel.

Our task in this chapter and the following one is to organize more formally the bits
and pieces of the Swing package and multimedia that you have managed to grasp
from our examples so far. Overall, the Java API lists hundreds of classes and
interfaces, with thousands of constructors and methods. A sizable portion of the API
— more than 100 classes — deals with Swing GUI components, events handlers, and
multimedia. The online documentation in HTML format gives you convenient
access to these detailed specifications. Still, it is not very easy to find what you need
unless you know exactly what to look for. In many cases it may be easier to look up
an example of how a particular type of object is used than to read about it in the API
Copyright © 2011 by Skylight Publishing

spec file. In most cases you need only the most standard uses of classes and their
methods, and there are thousands of examples of these in JDK demos, books, online
tutorials, and other sources.

This is the approach our book has taken, too. While introducing Java’s fundamental
concepts and basic syntax and control structures, we have sneaked in a variety of
commonly used GUI methods and “widgets.” We have added some bells and
whistles here and there, just so you could see, if you cared to, how such things might
be done. This chapter summarizes what you have already seen and fills in some
gaps. Appendix D presents a synopsis and an index of the more commonly used GUI
components that appear in the code examples in this book.

Knowing all the details of the latest GUI package still does not guarantee that the
GUI in your application will “work.” In addition to working the way you, the
programmer, intend, it must also be intuitive and convenient for the user. Designing
a good user interface is a matter of experience, good sense, trial and error, paying
attention to the software users, developing prototypes, and in some cases, relying on
more formal “human factors” research. To become a good user interface designer,
one should gain experience with a wide range of applications, observe what works
17.1 ~ PROLOGUE 435

and what doesn’t, and absorb the latest styles from cyberspace. Note that, strictly
speaking, this skill may not be directly related to programming skills.

In this chapter we will discuss the “pluggable look and feel” and a few basic Swing
components:
y JLabel — displays an icon or a line of text
y JButton — triggers an “action event” when pressed
y JToggleButton and JCheckBox — toggle an option
y JComboBox and JRadioButton — choose an option out of several
possibilities
y JSlider — adjusts a setting
y JTextField, JPasswordField, and JTextArea — allow the user to enter
and display or edit a line of text, a password, or a multi-line fragment of text,
respectively
y JMenuBar, JMenu, JMenuItem — support pull-down menus.

We will discuss some of the methods of these GUI objects and the events they
generate. We will also get familiar with four layout managers that help to arrange
GUI components on the application’s window.
Copyright © 2011 by Skylight Publishing

 17.2 - 17.7 

These sections are online at http://www.skylit.com/javamethods.


436 CHAPTER 17 ~ GUI COMPONENTS AND EVENTS

Exercises
Sections 17.1-17.7

1. For each the following Swing GUI components in Column One, mark the
listeners from Column Two and the “status accessors” from Column Three
that are commonly used with them. 3

(a) JPanel < none > < none >


(b) JLabel ActionListener isSelected
(c) JButton ItemListener getSelectedIndex
(d) JCheckBox ChangeListener getSelectedItem
(e) JRadioButton getText
(f) JComboBox getValue
(g) JTextField
(h) JSlider
(i) JMenuItem

2. Mark true or false and explain:

(a) An object’s actionPerformed method can be called directly in the


program by other methods. ______ 3
Copyright © 2011 by Skylight Publishing

(b) The same object can serve as an action listener for one component and
an item listener for another component. ______ 3

(c) A button can have several different action listeners attached to it.
______ 3

(d) An object can serve as its own action listener. ______

3.„ Write a program that serves as a GUI front end for the code you created for
Question 11 in Chapter 6, the quadratic formula.

4.„ Write a GUI application that adds several “large integers” as described in
Chapter 12, Question 24.
CHAPTER 17 ~ EXERCISES 437

5. (a) In the Boxes program (JM\Ch16\Exercises\Boxes.java) from


Question 5 in Chapter 16, add a menu bar with only one menu of two
items: “Increase size” and “Decrease size.” When clicked, these items
should increase or decrease the current size of the box by 10%.
Modify the BoxDrawer class (your solution to Question 5 in
Chapter 16) to support this functionality.

(b) Unite the rounded and 3-D checkboxes in one group (a


ButtonGroup object), so that they cannot be both selected at the same
time. Usually such groups are used with radio buttons (see
Appendix D), but they can work for checkboxes as well.

6.„ Create the following GUI layout:

English:

Portuguese:

Translate

ÒHint: Put the two labels on a panel with a 2 by 1 grid layout. Use right-
Copyright © 2011 by Skylight Publishing

justified labels JLabel(<text>, null, JLabel.RIGHT). (Instead of


null you can put an icon showing the flag or an emblem of a country that
speaks the language.) Put input fields on another 2 by 1 panel. Put both
panels into a horizontal box with a strut between them; put this box and the
“Translate” button into a vertical box with struts around them. This is only
one way of doing it.Ñ
438 CHAPTER 17 ~ GUI COMPONENTS AND EVENTS

7.„ (a) Create the following GUI layout:

Small Extra cheese

Medium Mushrooms

Large Pepperoni

ÒHint: put all the radio buttons into a panel and all the checkboxes
into another panel, each with a 3 by 1 grid layout. Add a border to
each panel by calling its setBorder method. For example:

import javax.swing.border.*;
< ... other statements >
CompoundBorder border = new CompoundBorder(
new LineBorder(Color.BLACK, 1),
new EmptyBorder(6, 6, 6, 6));
// outside border: black, 1 pixel thick
// inside border: empty, 6 pixels on
// top, left, bottom, right
Copyright © 2011 by Skylight Publishing

panel.setBorder(border);

Put both panels into a horizontal box with struts between them and on
the left and right sides. Unite the radio buttons into a group (see
Appendix D).Ñ 3

(b) Add a JToggleButton “To Go” on the right, initially set to “No.” 3
CHAPTER 17 ~ EXERCISES 439

8.‹ Create a Keypad program. This program can serve as a basis for calculators
of different models. First run a compiled version
(JM\Ch17\Exercises\Keypad.jar). The program consists of two
classes: Keypad and DigitalDisplay. Keypad is the main class. Its
constructor creates an object display of the DigitalDisplay type.
Write a class DigitalDisplay by extending JTextField. Make
DigitalDisplay implement ActionListener and make display serve
as an action listener for all the buttons. The “C” button clears the display;
any other button appends the text from the button to the current display text.
For example:

JButton b = (JButton)e.getSource();
String str = b.getText();
< ... etc. >

Let display’s constructor configure the display: dark green background (for
example, RGB 50, 200, 50), white or yellow foreground. Make it non-
editable to prevent extraneous keyboard input. Set text alignment to the
right:

setHorizontalAlignment(RIGHT);

Set the preferred size of the display in the program and add an empty border
on the left and right to make it look better. For example:
Copyright © 2011 by Skylight Publishing

import javax.swing.border.*;
< ... etc. >

display.setPreferredSize(new Dimension(width, width/6));


display.setBorder(new EmptyBorder(0, 10, 0, 10));
// top, left, bottom, right

Also set display’s font to a fairly large fixed-pitch font (in proportion to
width). Is it a good idea to set display’s size, border, and font in
DigitalDisplay’s constructor? Explain.

In the Keypad class, place all the buttons on a 4 by 3 grid on a panel with
some space between them. Add the display field above the buttons.
ÒHint: place the display and the buttons panel into a vertical box. You can
add the box directly to the content pane, or you can add it to a panel with a
border, as we did.Ñ
440 CHAPTER 17 ~ GUI COMPONENTS AND EVENTS

9.‹ Rewrite the Madlibs program described in Chapter 15 Question 10 as a GUI


application. ÒHint: use a JTextArea component to display the final
text.Ñ
Copyright © 2011 by Skylight Publishing

Você também pode gostar