Java 2 Gui Fud Mentals With Swing
Java 2 Gui Fud Mentals With Swing
www.digitalthink.com
© 1999 DigitalThink, Inc. All rights reserved.
Course Syllabus
Module 1:
Lesson 1 - Course introduction
Lesson 2 - Prerequisites
Lesson 3 - What you need
Lesson 4 - What to expect
Sidebar: Copying and pasting on Unix platforms
Lesson 5 - The course tutors
Lesson 6 - Meet your instructor
Sidebar: Michael Morrison's introduction (Audio transcript)
Lesson 7 - Course project
Sidebar: Features of the Doodle application (FlipBook transcript)
Module 2:
Lesson 1 - Events and user interaction
Lesson 2 - Event fundamentals
Sidebar: The delegation event model is not alone
Lesson 3 - Event sources and listeners
Sidebar: Unicast and multicast event delivery
Sidebar: The event delivery process (FlipBook transcript)
Lesson 4 - Responding to events
Sidebar: Significance of the delegation event model (Audio transcript)
Sidebar: Registering a class as an event listener (MouseOver transcript)
Sidebar: Implementing an event listener (MouseOver transcript)
Quiz: Event basics
Lesson 5 - Handling mouse events
Sidebar: The MouseListener interface (MouseOver transcript)
Sidebar: The MouseMotionListener interface (MouseOver transcript)
Exercise: Starting the Doodle application
Lesson 6 - Using event adapters
Sidebar: Inner classes
Sidebar: The MouseHandler inner class (MouseOver transcript)
Exercise: Using event adapters in Doodle
Lesson 7 - Handling keyboard events
Sidebar: The KeyListener interface (MouseOver transcript)
Exercise: Supporting the keyboard in Doodle
Lesson 8 - Module wrap-up
Quiz: Events and user interaction
Module 3:
Lesson 1 - Introducing Swing
Lesson 2 - GUI basics
Sidebar: GUI design
Sidebar: GUI components (FlipBook transcript)
Glossary
A set of classes and interfaces in the Java API that is devoted to building graphical user
interfaces (GUIs) in Java applets and applications. The AWT forms the basis of the Swing
toolkit, which provides more advanced GUI features.
Accelerator
Provides a means of directly accessing menu items without navigating through a menu
hierarchy. An accelerator key-combination is identified visually to the right of a menu item.
Access modifier
Access modifiers define different levels of access for class members including private,
protected, public, and a default access level.
Applet
AppletViewer
A utility included with the Java Development Kit that allows you to test applets without using a
Web browser.
The set of Java packages and classes included in the Java 2 Software Development Kit (SDK)
that programmers use to create Java programs.
Array
Special constructs in Java that allow you to store a list of items of the same data type.
Border
A special class that determines the appearance of the outer edge of components.
Border layout
The default layout manager for the content pane of frames. The border layout arranges
components in the geographic directions north, south, east, and west, along with another
component in the center.
Box layout
Branch statement
Java supports two different kinds of branch statements. The if-else is the most commonly used,
and it is useful in situations where you need to conditionally execute one section of code or
another. Java's other branch statement, the switch statement, is designed to choose between
multiple branches of code.
Break statement
Buffered I/O
Buffered I/O is a special type of I/O where data is written to a temporary buffer instead of to an
actual stream. When the buffer is full, all of the data in the buffer is written to the stream.
Buffered I/O is more efficient than non-buffered I/O since data is transferred to and from a
physical device in large blocks.
Button
A GUI component that allows the user to invoke a command or set a value. Regular buttons are
used to invoke commands, while radio buttons, toggle buttons, and check boxes provide a
means of setting a value.
Bytecode
The executable form of Java code, which is capable of being executed in the Java runtime
system.
Card layout
A layout manager that arranges multiple panels so that they act as a stack of cards. Only one of
the panels is visible at any given time when you use the card layout. The card layout is handy
for creating wizard-style interfaces, where the user is presented with a sequence of GUIs
implemented as card panels.
Catch clause
The catch clause is the part of the try-catch construct that is used to catch any exceptions that
may be thrown by code in the try clause.
Chooser
A specialized dialog box designed to retrieve information from the user within the context of a
commonly performed task. For example, Swing includes a file chooser that provides a powerful
GUI for browsing for files, along with a color chooser for selecting colors.
Class
A template that defines the implementation of an object, effectively acting as a blueprint for the
object. A class defines data and methods and is a unit of organization in a Java program.
Client
A client is a program that requests and displays information from a special program called a
server. This type of information exchange between a client and server is known as a
client/server architecture.
Combo box
A GUI component that allows the user to select an item from a list. Unlike lists, combo boxes
only display a single item; multiple items are revealed in a drop-down window when you
activate the combo box. Combo boxes also allow users to manually enter new items.
Command-line arguments
Information passed into a command-line application that somehow controls the way the
application runs.
Comments
Comments are used to document code for the purposes of the programmer. Java supports three
different types of comments: //, /* */, and /** */.
Component
A component is an object that performs a function within a graphical user interface (GUI).
Examples of Java components include buttons, combo boxes, menus, and toolbars.
Compound statement
A compound statement is a block of code that is surrounded by curly braces ({ }). Compound
statements allow you to use multiple lines of code in situations where a single statement is
expected. A good example is the code executed in the branch of an if statement.
Conditional operator
The conditional operator acts a like a shorthand if-else statement. It evaluates a test expression
and conditionally evaluates another expression based on the test.
Container
A component that serves as a context for grouping together other components. Examples of
Java containers include panes, toolbars, and dialog boxes.
Data types
Data types dictate the type of information that can be stored in a variable. Java supports a wide
range of simple data types such as int, long, float, boolean, and char. Composite data types in
Java are implemented as objects. An example of a composite data type is String.
The event model employed by Java 2, which involves registering event listeners with event
sources in order for events to be delivered. This model is very efficient since the only events
that are delivered are those for which a listener has specifically been registered.
Dialog box
A special window that provides a means of displaying a "temporary" user interface that displays
or retrieves information, and then goes away. Constructing a custom dialog box GUI is very
similar to constructing an application GUI through the content pane of a frame window.
Event
Something that occurs within an object that an application or other object might want to know
about and to which it might possibly react.
Event adapter
A helper class that makes the handling of events much cleaner. More specifically, an event
adapter alleviates the need to implement all of the event response methods in an event listener
interface, allowing you to implement only the methods you need.
Event listener
An object capable of responding to an event. You connect an event listener to an event source
in order to receive and respond to events.
Event source
An object capable of generating an event. Most GUI elements are event sources since they
typically generate events in response to user interactions.
Event-driven programming
Exception
An exceptional situation that a program doesn't know how to handle is known as an exception.
An example of an exception is attempting to divide a number by zero or the system running out
of memory.
Expression
An expression usually involves an equal sign ( = ) and somehow manipulates one or more
variables or values.
Finally clause
The finally clause is used in conjunction with the try-catch construct to place code that is
always executed regardless of whether an exception is thrown.
Flow layout
The default layout manager for panels. The flow layout arranges components across a container
in rows from left to right.
Frame
A container that serves as the main window for an application. Since they serve as main
application windows, frames support familiar UI window features such as a title, border, and
buttons for sizing and closing the frame.
Glue
Used in the box layout to maximize the space between components in one direction (horizontal
or vertical).
The program elements involved in communicating with the user through visual cues, typically
utilizing both the keyboard and mouse.
Graphics class
The Graphics class represents an abstract drawing surface called a graphics context, and is
logically equivalent to a piece of paper. Java uses graphics contexts to help abstract the drawing
process, which allows you to use the same drawing code to draw to different graphical devices
such as monitors and printers.
Graphics context
A graphics context is an abstract drawing surface that is logically equivalent to a piece of paper.
GIF is an image format that is useful for storing non-photographic images such as illustrations
and diagrams; GIF image files typically have a .gif file extension.
Graphics primitives
Graphics primitives are basic geometric shapes such as lines, rectangles, squares, ovals, circles,
polygons, and arcs.
A layout manager that provides the most flexibility of all the layouts. The grid bag layout is
similar to a grid layout except that you have a lot more control over the size and position of the
cells in the grid. For example, in a grid bag layout you can specify that some cells span multiple
columns and also control the physical arrangement of components within specific cells in the
grid.
Grid layout
A layout manager that arranges components in a grid of rows and columns. Like the flow
layout, the grid layout arranges components from left to right but they conform to a fixed
arrangement of rows and columns.
Heavyweight component
A component that has an underlying native component, or peer, associated with it. For example,
an AWT button is a heavyweight component because it uses an underlying Windows peer when
running on the Windows platform.
Icon
An image that provides visual cues associated with GUI features. Icons are regularly used with
Swing menu items and buttons, as well as other components.
Identifier
Tokens that represent unique names for variables, methods, classes, packages and any other
named Java construct.
Inheritance
The ability to derive new classes from existing classes in object-oriented programming.
Inner class
A class defined within the scope of another class. Inner classes are often used with event
adapters to make event handling cleaner.
Interface
An IP address is a number that is used to uniquely identify computers connected to the Internet.
Invisible filler
A standard suite of tools, utilities, and related resources used to build Java applets and
applications.
Java compiler
The tool used to compile Java source code into executable Java programs.
Java Interpreter
A program responsible for translating Java bytecode into native code that can execute on a
given platform.
JPEG is an image format that provides a highly efficient means of storing photographic images;
JPEG image files typically have a .jpg or .jpeg file extension.
Keywords
Keywords are special identifiers set aside as Java programming constructs. Typical keywords in
Java include int, class, for, while, new, private, and switch to name a few.
Label
An output-only component used to present both text and graphical information to the user. You
often see labels used in conjunction with input components such as text edit fields.
Layout manager
A layout manager determines how components are physically arranged within a container. A
layout manager is often referred to simply as a layout.
Lightweight component
List
A GUI component that allows the user to select one or more text and/or icon items from a list.
Literals
Loop
There are three types of loops used in Java: for loops, while loops, and do loops.
Low-level event
An event fired in response to a low-level input or graphical user interface interaction such as a
key press or mouse click.
main() method
The method within a Java application that is called by the Java interpreter to run the
application.
Menu
A GUI component that provides a hierarchical user interface for selecting commands and
altering settings within an applet or application. A Swing menu consists of a menu bar that is a
container for individual drop-down menus; these menus contain individual menu items that
represent commands or settings.
Message
Method
Mnemonic
A keyboard user interface used to navigate through the hierarchy of a menu and select a menu
item or invoke a menu command. A mnemonic is often used in conjunction with the Alt key.
An underlined character in the name of a menu item visually identifies a mnemonic.
When an event is broadcast to multiple event listeners simultaneously. Multiple event listeners
can be registered with a multicast event source.
Multithreading
Multithreading is the capability of a program to have multiple paths of execution called threads.
Object
A collection of data and the procedures (methods) that act on that data.
Object class
The class that forms the root of the Java class hierarchy. The Object class serves as the basis for
all Java classes, including the classes in the Java API.
Operator
Option pane
A standard dialog box that makes it easier to accomplish certain tasks. An option pane can often
save you from the task of constructing a custom dialog box GUI.
Overload
To use the same name for several items in the same scope.
Override
Package
Pane
Generic Swing containers. Multiple panes are used in Swing to create an architecture that can
support rich GUI features.
Parameter
A name and value pair identified by the name and value attributes of the PARAM element used
inside an APPLET element.
A feature of Swing that allows you to set the look and feel of a GUI dynamically. By utilizing a
pluggable look and feel, a Swing GUI is capable of querying the underlying native GUI and
taking on its look and feel. The look and feel of a GUI comprises such graphical parameters as
color schemes, component styles, and 3D shading effects, to name a few.
Progress bar
Provides a visual representation of the status of an incomplete process. For example, you might
display a progress bar while loading images in an applet.
Protocol
A protocol is a set of rules and standards that govern how network communication works.
Protocols determine how computers communicate with each other over a network.
Rigid area
Used in box layouts to create fixed-size spaces between components in one direction
(horizontal or vertical).
Semantic event
An event fired in response to an action which is based on the semantics of a particular object,
such as an item change in a list.
Separators
Separators are symbols used to inform the Java compiler of how code elements are grouped.
Server
A server is a program that acts as an information source to special programs called clients. This
type of information exchange between a client and server is known as a client/server
architecture.
Slider
A GUI component that allows the user to graphically select a value by sliding a knob within a
bounded range of values.
Socket
Standard I/O
Standard I/O is the most basic form of input and output available to a Java program. Java
standard I/O is text-based, and operates under the premise that the computer has a standard
input device (keyboard) and a standard output device (monitor).
Stream
A stream is a medium through which data is transferred. A stream acts sort of like a pipe in the
real world, except that it shuttles moving data instead of water or gas. Data is transferred
through a stream one byte at a time, and can be directed in different ways.
String
A Java object that represents textual information. Although you can think of a string in Java as
a series of characters, strings are implemented in the String class.
Swing toolkit
A set of classes and interfaces that serve as an extension to the Java AWT. Swing provides
replacements for many of the classes in the AWT. In general, Swing classes and interfaces are
more extensible and powerful than their AWT counterparts.
Table
A GUI component that allows the user to view and manipulate data in a two-dimensional table
format, similar to a spreadsheet.
Text component
A GUI component that allows the user to view and manipulate text.
Thread synchronization
Thread synchronization is the process of structuring threads so that they never interrupt each
other while performing sensitive tasks.
Token
Tool tip
A small text window that appears when the user pauses with the mouse cursor over a
component. Tool tip windows are designed to be unobtrusive. The text associated with a tool tip
is typically very concise.
Toolbar
A GUI component that serves as a container for buttons or other components, and is typically
positioned along a bar at the top of an application's main window frame. Toolbars can be
positioned anywhere in an application's frame but the top is the most popular location.
Tree
A GUI component that allows the user to view and manipulate a set of hierarchical data as an
outline.
Try clause
The try clause is the part of the try-catch construct where code is placed that can potentially
throw an exception. You then catch any exceptions that may be thrown in one or more catch
clauses.
When an event is broadcast to a single event listener. Only one event listener can be registered
with a unicast event source.
Variables
Variables are locations in memory that are used to store information. You can think of variables
as storage containers designed to hold data of a certain type.
Z-order
The Z-order of a layered pane is a number that indicates the depth of the layer with respect to
the screen. In other words, the screen is the highest layer with a theoretical Z-order of infinity,
while other layers have decreasing Z-orders behind the screen. Z-order is what allows you to
layer panes on top of one another.
Course introduction
Java 2 GUI Fundamentals with Swing teaches you
how to construct graphical user interfaces (GUIs) in
Java.
You’ll use the Swing toolkit in Java 2, which
provides a rich set of classes and interfaces for
creating very powerful and intuitive GUIs.
Course After completing the course, you will have the skills
goals and knowledge necessary to:
● Handle mouse and keyboard events
Prerequisites
Make sure you have the necessary
background for this course.
Other resources
A listing of links to online Java resources are
available on the Resources page. You can reach this
page at any time by clicking the Resources button on
the toolbar.
Course bookstore
Purchase the optional texts for this course online by
visiting the course Bookstore page. These books are
not required to take this course, but do contain
helpful, additional information. You can reach the
Bookstore page at any time by clicking the
Resources button on the toolbar.
Sampler Courses "Your exercises show the true power of the language and are easy to
C, C++ Programming follow. Great job!!"
Database Concepts -Andy Erickson, Cincinnati, OH
Design & Publishing
Desktop Course Description
IT Management Java 2 Fundamentals I provides moderately experienced programmers
Internet Literacy with a foundation in Java basics and prepares them to learn more
Java Programming advanced aspects of the Java language. Students install and use Sun's
Lotus Java 2 platform, explore stand-alone applications and Web-hosted
MS Certification:MCDBA
applets, learn about Java's object-oriented building blocks, and work
MS Certification:MCSD
MS Certification:MCSE
with Java's operators and control flow statements.
Object Programming
Networking
This course covers fundamentals of Java programming and does not
Oracle
address material that is specific to the Java 2 platform. Therefore,
UNIX Java 2 Fundamentals I is not an upgrade course for those who already
Web Programming understand the fundamentals of Java programming using the JDK
Windows Programming 1.0.2 or 1.1.
Learning Objectives
After completing this course, students will be able to:
● Use many of the tools in the Java 2 platform
● Implement Java classes, objects, and methods
● Use Java data types, expressions, and control flow structures
● Develop stand-alone character-based applications
● Develop and embed Java applets in Web pages using HTML
Prerequisites
In order to get the most from this course, students should have an
understanding of computer programming and experience with a
programming language such as C or C++. Object-oriented
programming experience isn't necessary, but will make learning Java a
little easier.
Note that this is not a beginning course and is not a course designed
for non-programmers. In addition, this course is not an upgrade
course for those who already understand the fundamentals of Java
programming using the JDK 1.0.2 or 1.1.
Required Software
● The Java 2 platform
Platform Support
You can take this course on computers running Windows, Macintosh,
or UNIX. To complete the exercises, however, you must have access
to a computer running Windows or UNIX; Sun does not support a
Macintosh version of Java 2.
Instructor
Sampler Courses "Teaching a language such as Java lends itself well to this type of
C, C++ Programming self-paced instruction. I was impressed with the level of tutorial
Database Concepts competence and activity in the course."
Design & Publishing -Jim Cant, Ontario, Canada
Desktop
IT Management Course Description
Internet Literacy Java 2 Fundamentals II picks up where Java 2 Fundamentals I leaves
Java Programming off by rounding out the Java knowledge base required for beginning
Lotus Java programmers. Students dig deeper into object-oriented
MS Certification:MCDBA
programming with Java and learn the basics of Java graphics.
MS Certification:MCSD
MS Certification:MCSE
Additionally, the course covers multithreading, exception handling, file
Object Programming
input and output (I/O), and networking basics.
Networking
Oracle
This course covers fundamentals of Java programming and does not
UNIX address material that is specific to the Java 2 platform. Therefore,
Web Programming Java 2 Fundamentals II is not an upgrade course for those who
Windows Programming already understand the fundamentals of Java programming using the
JDK 1.0.2 or 1.1.
Learning Objectives
After completing this course, students will be able to:
● Organize Java classes into packages
● Leverage the use of interfaces in the design of Java classes
● Use the Java AWT to draw primitive graphics, text, and images
● Create and use threads
● Catch program errors using exceptions
● Read and write files
● Use Java's networking features to scan the Web
Prerequisites
Java 2 Fundamentals I, or equivalent knowledge and experience.
Required Software
● The Java 2 platform
Platform Support
You can take this course on computers running Windows, Macintosh,
or UNIX. To complete the exercises, however, you must have access
to a computer running Windows or UNIX; Sun does not support a
Macintosh version of Java 2.
Instructor
Michael Morrison, instructor for the Introduction to Java 2 Series,
JavaBeans for Programmers Series and Win32 Programming Series, is
an author and contributor to many Java-related books including
Complete Idiot's Guide to Java (Que), Java 1.1 Unleashed (Sams),
How To Program JavaBeans (Ziff-Davis Press), Presenting JavaBeans
What to expect
Explore key course features.
Glossary
Throughout this course, you'll have the opportunity
to review definitions of key terms. Many terms will
link to their definition, which will appear in a small
window.
Java Technologies
● General Java info
● JavaBeans
● Java Foundation Classes
● Microsoft SDK for Java
● Java Commerce Toolkit
● HotJava Browser
● JavaOS
● Jini
directory.
● The CLASSPATH environment variable is
used to notify SDK tools and some other Java
programs where they can find support classes.
It isn't necessary to set the CLASSPATH
environment variable for this course.
Other Options
• What is Web Buy?
• Asian Font Packs
for Acrobat Reader Select an Acrobat Please provide your Now download and
4.0 Reader version. name and e-mail install - it's just that
• Acrobat Reader 4.0 address. easy!
Language:
Middle Eastern Name: The version of Acrobat
English
• Acrobat Reader Reader you are
and Acrobat Platform: downloading:
Reader + Search Win 95 E-mail address: The download file size is:
4.0 CD-ROM
Location nearest you:
• Acrobat Viewer
USA
(Java) ✔ Notify me about
Include option for Adobe software and
searching PDF files offers
✔ Allow others to send
(longer download)
me special offers
Macintosh: .bin or .hqx? Full privacy policy
If you have trouble downloading, or need a 3.x version of the Reader, try this
alternate source.
The Bookstore lets you purchase course texts directly over the
Internet. Working with Amazon.com, the most respected
name in online booksellers, we supply you with everything
you need to purchase your books right now. If you prefer, you
can also use this information to find the books at your local
bookstore.
The course tutors are the people who will review all
your exercise submissions and send you personal
email in response. You can also email the course
tutors whenever you have a question or get stuck in a
lesson or exercise.
What to expect
Copying and pasting on Unix
platforms
All of the text files you need to get started on course
exercises are included in the download file available
on the Resources page. Open the text file in your text
editor and make any modifications necessary to
complete the exercise. Save the file under a different
name.
From text Once you have the exercise solution in a text file,
editor to you're ready to submit your solution to the course
browser tutors.
How to... If you find you cannot cut and paste text from one
application to another, follow the steps listed below.
Please note that DigitalThink supports only Netscape
Navigator 3.x or above on Unix platforms. The
instructions refer to Navigator 4.x, but instructions
for doing this procedure in Navigator 3.x are very
similar:
1. When you are ready to submit an exercise
solution, navigate to the appropriate exercise
page in the course using the course Syllabus.
You'll notice a text box in which you'll want to
paste your exercise solution.
2. From the File menu in Navigator, choose the
Open Page option. The Open Page dialog box
appears.
3. Click the Choose File button. The Choose File
dialog box appears.
Find me on I have a Web site called The Tribe. This site contains
the Web information about my interests and hobbies, as well
as resources associated with my writing projects and
software development efforts.
Course project
Find out about the course project.
Transcript
This page is under construction - sorry for the inconvenience. This page has been accessed times.
Course project
Features of the Doodle application
(FlipBook transcript)
Some features of the Doodle application:
Event fundamentals
Get acquainted with events, Java's
mechanism for handling user interaction.
release.
MouseEvent Fired when a component
receives a mouse button click,
mouse button release, mouse
move, or mouse drag.
Transcript
Event fundamentals
The delegation event model is not
alone
The delegation event model is not the only event
model Java has seen. Early versions of Java
employed a very different event model that was
found to be limiting as Java grew and incorporated
more advanced technologies such as JavaBeans. It
took a few iterations before the Java architects
settled on the delegation event model, which was
introduced in Java 1.1.
Responding to events
Respond to events.
Transcript
Transcript
Quiz
Click the Quiz button to test your knowledge of events.
Transcript
Transcript
Exercise
Click the Exercise button to begin creating the
Doodle application.
Responding to events
Significance of the delegation
event model (Audio transcript)
Just in case you're thinking the event
source/listener architecture of the delegation event
model seems like an unnecessary complication,
allow me to explain its significance. One of the key
design goals of the delegation event model is
efficiency. If you consider how many event
notifications are generated for some events such as
mouse drags, it becomes apparent that an event
model that isn't highly efficient could easily create
performance bottlenecks.
The delegation event model is designed so events in
which you aren't interested are never delivered. The
process of registering an event listener is how you
notify an event source that it should deliver events to
the listener. Any event that isn't explicitly registered
via an event listener will never be delivered.
Responding to events
Registering a class as an event
listener (MouseOver transcript)
Responding to events
Implementing an event listener
(MouseOver transcript)
Quiz
Event basics
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Transcript
Exercise
In this exercise, you'll use an event adapter to handle
mouse events.
Exercise
Instructions
The Doodle application relies heavily on a support class named DoodleShape that represents a simple
graphic shape. The DoodleShape class provides constants identifying each shape that it can represent:
LINE, RECTANGLE, TRIANGLE, and OVAL. Since your focus is on the Doodle application itself, I've
provided the code for the DoodleShape class (also available in the file DoodleShape.java):
import java.awt.*;
case RECTANGLE:
g.drawRect(Math.min(start.x, end.x),
Math.min(start.y, end.y),
Math.abs(end.x - start.x),
Math.abs(end.y - start.y));
break;
case TRIANGLE:
g.drawLine(start.x, end.y,
start.x + (end.x - start.x) / 2, start.y);
g.drawLine(start.x + (end.x - start.x) / 2,
start.y, end.x, end.y);
g.drawLine(end.x, end.y, start.x, end.y);
break;
case OVAL:
g.drawOval(Math.min(start.x, end.x),
Math.min(start.y, end.y),
Math.abs(end.x - start.x),
Math.abs(end.y - start.y));
break;
default:
System.err.println("ERROR : Unknown shape type.");
}
Your task in this exercise is to add mouse support to the Doodle application. This involves implementing
both Java mouse event listener interfaces in the Doodle application class and adding code to track the
mouse and draw a graphic shape.
Following is the starter code for the Doodle application (available in the file Doodle.txt). This starter
code contains everything you need except the code to deal with mouse events:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public Doodle() {
super("Doodle");
Notice that there is a comment in the constructor that indicates where you should register the mouse
event listeners. You also need to clarify in the Doodle class declaration that Doodle implements the
two mouse listener interfaces: MouseListener and MouseMotionListener. Finally, you need to
implement all of the event response methods defined in the listener interfaces.
You may have noticed that the Doodle application already responds to window events, as is evident by
the call to addWindowListener(). This is necessary so that the application is exited properly when
the frame window is closed. The WindowHandler class is an event adapter class that makes handling
window events cleaner. You'll learn how to create and use event adapters in the next lesson.
I've provided the code that goes in the important mouse event response methods. Following is the code
that should be executed when the mouse button is pressed (available in the file MousePressed.txt):
Following is the code that should be executed when the mouse button is released (available in the file
MouseReleased.txt):
repaint();
}
Following is the code that should be executed when the mouse is dragged (available in the file
MouseDragged.txt):
In the text box below, cut and paste the complete code for the Doodle class. Click OK, I'm Done to
submit your code to the course tutors.
Transcript
Exercise
Add keyboard support to the Doodle application in
this exercise.
Exercise
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Quiz
Click the Quiz button to test what you've learned in
this module.
For more control over a typed key, you can use the
keyPressed() and keyReleased() methods,
which are called in response to a key press and a key
release.
Exercise
The above code cycles through the different shape types, allowing the user to change the shape by
pressing the space key. Following is the code for the R key, which is identified by the VK_R constant:
shapeColor = Color.red;
This code uses the Color.red color constant to set the current shape color to red, which means that
any shapes drawn after pressing the R key will be red. Feel free to add code to support as many colors as
you choose. For information about the different color constants supported in Java, refer to the Color
class in the Java documentation.
What to submit to the course tutors
In the text box below, cut and paste the code for the new Doodle class. Click OK, I'm Done to submit
your code to the course tutors.
Introducing Swing
Module introduction
The Java programming language has evolved to
provide an extremely rich set of graphical user
interface classes that you can use to build powerful
and effective user interfaces.
Quiz
Events and user interaction
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
GUI basics
Evaluate the significance of GUI
components.
Transcript
Exercise
In this exercise, you'll modify the Doodle application
so that its drawing functionality is encapsulated in a
component.
Why Swing? The main reason for the addition of Swing has to do
with a limitation in the AWT. Components in the
AWT are known as heavyweight components
because they are associated with native components,
or peers, on a given operating system. For example,
an AWT button uses an underlying Windows peer
when running on the Windows platform. This
approach results in platform dependencies that make
it difficult to build truly cross-platform GUIs.
Swing is built around the concept of lightweight
components, which are peerless components.
Lightweight components have no underlying native
component, meaning that Swing components are
100% Java. As a result, Swing components don't
GUI basics
GUI design
Since a GUI is a graphical application's only means
of communicating with the user, you should
carefully consider its design. Major software
publishers spend lots of money researching GUI
design to find out how users can get the most out of
their software. The good news is that there is no right
or wrong in GUI design. It is an art form that
involves merging the aesthetic value of a design with
practical function.
GUI basics
GUI components (FlipBook
transcript)
Following are examples of some GUI components:
Exercise
Gui basics
Moving Doodle's drawing functionality into a component
Objective
Encapsulate the drawing functionality of Doodle in a component.
Exercise scoring
The full credit for this exercise is 5 points. You'll submit your source code to the course tutors.
Overview
It is helpful to have the drawing functionality of the Doodle application encapsulated in a component. In
this exercise, you create a component class named DoodlePad that is derived from the Component
class.
Source files
We've supplied the starter code for this exercise in a file called Doodle.java. You'll find this file in
the 03-02 folder of the course download available from the Resources page.
Instructions
Create a component class named DoodlePad that is derived from the Component class. The
DoodlePad class should handle the mouse and keyboard events that were handled in the application,
and completely take on the responsibility of drawing the graphic objects. To help get you started, I've
provided the code for the new Doodle class, which creates a DoodlePad component and adds it to the
application's user interface:
import java.awt.*;
import java.awt.event.*;
public Doodle() {
super("Doodle");
The only trick to creating the DoodlePad class is to make sure that you call the requestFocus()
method in response to the mouse button being pressed. This step makes sure that the input focus is set to
the component so that it receives keyboard events.
What to submit to the course tutors
In the text box below, cut and paste the code for new DoodlePad component class. Click OK, I'm Done
to submit your code to the course tutors.
Quiz
Click the Quiz button to test your knowledge of
Swing basics
Framing an application
Use Swing's JFrame class
Transcript
Exercise
In this exercise, you'll modify Doodle’s GUI so that
it uses the Swing toolkit.
Quiz
Swing basics
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Understanding panes
Define how panes are used within Swing
user interfaces.
The good news about the root pane is that you don't have to
worry about it too much when constructing a Swing GUI.
However, occasionally this knowledge will come in handy
so it's important that you at least understand the basic panes
housed in the root pane.
Framing an application
The getContentPane() method
(MouseOver transcript)
Exercise
Framing an application
Porting the Doodle application to Swing
Objective
Modify the Doodle application's GUI so that it uses the Swing toolkit.
Exercise scoring
This exercise is worth a total of 1 point. You don't have to submit your code to the course tutors to
receive credit for this exercise.
Overview
In this exercise you'll modify the Doodle application to use the Swing toolkit.
Instructions
Modifying the Doodle application so that it uses the Swing toolkit basically requires changing the parent
classes for Doodle and DoodlePad to Swing classes instead of AWT classes. More specifically, you
should use JFrame instead of Frame, and JComponent instead of Component.
Keep in mind that the JFrame class requires you to add components to its content pane instead of
adding them directly to the frame itself. So, you'll need to make a small change to the code that adds the
DoodlePad component to the frame.
Don't forget that the requestFocus() method should be called in response to the mouse button being
pressed. This step makes sure that the input focus is set to the component so that it receives keyboard
events.
One more thing - the JFrame and JComponent classes are defined in the javax.swing package, so
you need to import this package in the Doodle and DoodlePad source code files.
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Introducing Swing
Module wrap-up
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Discuss button on the toolbar, locate the module
topic folder that pertains to your question or
comment, and read through the discussions to see if
someone has already asked your question. If not,
post it yourself.
Quiz
Click the Quiz button to test what you've learned in
this module.
Understanding panes
Mixing AWT with Swing (Audio
transcript)
Even though Swing co-exists with the Java
AWT, in many ways Swing represents a departure
from the way in which GUIs were constructed using
the AWT in prior versions of Java. However, keep in
mind that Java 2 is still backward compatible with
earlier Java versions. This means that you have the
freedom to use the traditional AWT approach to
building GUIs or the new Swing approach.
One interesting problem associated with Java's
support for both approaches to GUI construction is
the mixing of lightweight and heavyweight
components. Consider the example of creating two
buttons, a Button and a JButton. The first button
is a heavyweight component with a peer while the
second button is a peerless lightweight component.
Java has to be able to allow these two components to
peacefully co-exist within a common GUI
framework, which is why it employs the root pane
architecture.
Understanding panes
Layering components
The layered pane determines how components
overlap each other. It does this by establishing a
Z-order for each layer, which you can think of as a
number indicating the depth of a layer with respect to
the screen. In other words, the screen is the highest
layer with a theoretical Z-order of infinity, while
other layers have decreasing Z-orders behind the
screen.
Quiz
Module quiz
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Layout managers
Explain the role of layout managers in
containers.
● Grid layout
● Border layout
● Card layout
Transcript
Transcript
Transcript
You can also set the layout for a new container in the
container's constructor when you first create it:
JPanel panel =
new JPanel(new FlowLayout());
Layout managers
Using layouts (Audio transcript)
Layouts provide a means of arranging
components in a container using relative positioning,
which means that the components are positioned
relative to each other. Relative positioning is
important because it helps to alleviate problems
associated with variations across different computing
platforms. For example, resolutions and window
sizes can vary greatly from platform to platform, in
which case components that are positioned at
absolute locations may not look like you would
expect.
Transcript
Quiz
Click the Quiz button to test what you've learned
about layouts.
Exercise
In this exercise, you'll use a flow layout.
GridLayout grid =
new GridLayout(3, 2);
Transcript
Exercise
Click the Exercise button to use a grid layout
manager.
Quiz
Layout basics
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Exercise
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Transcript
Exercise
Modify the Doodle application so that it uses a
border layout manager.
Exercise
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Transcript
Exercise
group.add(button);
buttonPanel.add(button);
button = new JRadioButton("Rectangle", false);
button.addActionListener(this);
group.add(button);
buttonPanel.add(button);
button = new JRadioButton("Triangle", false);
button.addActionListener(this);
group.add(button);
buttonPanel.add(button);
button = new JRadioButton("Oval", false);
button.addActionListener(this);
group.add(button);
buttonPanel.add(button);
Since the border layout is the default layout for the frame's content pane, you don't need to call
setLayout(). However you will need to specify the border positions of the button panel and
DoodlePad component when adding them to the content pane.
You may notice that the Doodle class (this) is registered as an action event listener for each of the
buttons. You need modify the Doodle class declaration to indicate that Doodle implements the
ActionListener interface. Following is the implementation of the actionPerformed() event
response method, which sets the graphic tool based on the button pressed (ActionPerformed.txt):
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Transcript
Alignment
The box layout takes an interesting approach to
aligning components: you provide a floating point
number between 0.0 and 1.0 that determines how a
component is aligned with other components in the
box. Following are examples of what different
alignment values mean for a vertical box:
Transcript
Transcript
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Discuss button on the toolbar, locate the module
Quiz
Click the Quiz button to test what you've learned in
this module.
Quiz
Module quiz
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Icons
Create and use icon components.
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.BOTTOM);
Exercise
Click the Exercise button to build an application that
uses labels.
Icons
Disabled image icons
You are probably familiar with images used on
toolbar buttons in many popular applications such as
a Web browser. And you've probably noticed that
when these buttons become disabled, the images on
them take on a gray, colorless appearance. This
grayed image provides a visual cue to let you know
that a particular button is disabled.
In Java, image icons are used to represent images in
most components, including buttons, and are
therefore responsible for offering a grayed look in
response to a component becoming disabled.
Using buttons
Create and use button components.
Quiz
Test your knowledge of icons, labels, and buttons in
this quiz.
Exercise
Click the Exercise button to create an application
that uses buttons.
Exercise
● An icon label
● A combination text/icon label with the text centered below the icon
You can use a GIF or JPEG image of your choice for the icon and any text that you choose. Also, set the
layout for the application's content pane to a 1x3 grid layout.
Source files
We've provided some sample images for you to use in the sample images folder of the course download
available from the Resources page.
Transcript
label.setBorder(
new LineBorder(Color.magenta, 3));
label1.setBorder(
new EtchedBorder(EtchedBorder.RAISED));
label2.setBorder(
new BevelBorder(BevelBorder.LOWERED));
label.setBorder(
new MatteBorder(new ImageIcon("Heart.gif")));
Exercise
In this exercise, you’ll modify the ButtonTest
application so that it uses borders.
Quiz
Icons, labels, and buttons
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Exercise
Using buttons
Tinkering with buttons
Objective
Create several button components and respond to their action events.
Exercise scoring
The full credit for this exercise is 5 points. You'll submit your source code to the course tutors.
Instructions
Write an application named ButtonTest that creates three different buttons using the JButton class.
The buttons should demonstrate the following:
● A simple text button
● An icon button
You can use a GIF or JPEG image of your choice for the icon and any text that you choose. Also, set the
layout for the application's content pane to a 1x3 grid layout.
Respond to the button events by registering the application as an action event listener and implementing
the actionPerformed() method. Check to see which button was pressed by calling getSource()
on the event object and comparing the result to each of the button objects. Print a string to standard
output indicating the button that was pressed.
Source files
We've provided some sample images for you to use in the sample images folder of the course download
available from the Resources page.
Lists
Use lists to manage the selection of items.
Using lists Lists are used to list a series of text and/or icon items
from which the user can select one or more items.
You can create a list from an array by passing the
array into the constructor for the JList object:
Transcript
list.setSelectionInterval(2, 4);
List events Lists generate list selection events when you select an
item in a list. To handle a list event, you simply
implement the ListSelectionListener
interface, which defines a single method:
valueChanged(). Following is an example of
printing the list item that was selected using the
getSelectedValue() method in the JList
class:
Exercise
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Combo boxes
Use combo boxes to manage the selection
of items.
Using combo Combo boxes are similar to lists in that they provide
boxes a GUI for selecting items from a list. Unlike lists,
combo boxes only display a single item. Multiple
items are revealed in a drop-down window when you
activate the combo box. Combo boxes are limited in
that they only allow one item to be selected at a time.
On the other hand, combo boxes are flexible in that
they can allow users to manually enter new items.
The JComboBox class is similar in many ways to
JList, which means that working with combo
boxes in Java code is similar to using lists.
Flip through the following frames to view some
sample combo boxes:
Transcript
Exercise
Click the Exercise button to create a list.
Lists
Various features of lists (FlipBook
transcript)
Lists
Scrolling components
Swing makes it very easy to support scrolling in a
component by using the JScrollPane class. The
JScrollPane class implements a scrolling pane
that serves as a container for components that require
scrolling functionality.
Transcript
Combo boxes
Sample combo boxes (FlipBook
transcript)
Exercise
Combo boxes
Presenting a list of choices
Objective
Create a list that presents the user with a set of choices.
Exercise scoring
The full credit for this exercise is 5 points. You'll submit your source code to the course tutors.
Instructions
1. Write an application named ListTest that creates a list and fills it with items that you find
interesting.
2. Write a list selection event response method that prints the name of the item selected from the list
to standard output. Be sure to use a scroll pane so that the list supports scrolling.
What to submit to the course tutors
In the text box below, cut and paste the source code for ListTest. Click OK, I'm Done to submit the
code to the course tutors.
progress bar
tree
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Discuss button on the toolbar, locate the module
topic folder that pertains to your question or
comment, and read through the discussions to see if
someone has already asked your question. If not,
post it yourself.
Quiz
Click the Quiz button to test what you’ve learned in
this module.
Quiz
Module quiz
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Menus
Examine menus and their role in Swing
GUIs.
Transcript
Menu creation
Create a menu.
Transcript
Exercise
Click the Exercise button to add a menu to the
Doodle application.
Menus
Drop-down menu types (FlipBook
transcript)
Items within a drop-down menu can be one of the
following types:
Transcript
Exercise
In this exercise, you’ll add support for keyboard
mnemonics and accelerators to the menu items in
Doodle.
Menu creation
Creating a menu (FlipBook
transcript)
Exercise
Menu creation
Adding a menu to the Doodle application
Objective
Add a menu to the Doodle application to support drawing commands.
Exercise scoring
Full credit for this exercise is 10 points. You'll submit your source code to the course tutors.
Instructions
Add code to the constructor of the Doodle class to create a menu. This menu should provide commands
for setting the current shape type.
In addition, create a menu command for selecting the drawing color. The actionPerformed() event
response method can simply print a string to standard output when the Select Color command is invoked,
since you won't be adding color selection functionality to Doodle until later in the course.
Following are the specific menu items you'll be creating:
● A Draw drop-down menu
● A separator between the shape type and color selection menu items
Hints
To create a separator (space) between menu items, call the addSeparator() method on the JMenu
object, like this:
drawMenu.addSeparator();
Keep in mind that the radio button menu items on the menu work very much like normal radio buttons.
You'll need to add them to a ButtonGroup object for them to be mutually exclusive. Also, you’ll need
to call addActionListener() on each menu item to register the application. This way, the
application will receive action events from the items. Note: After adding the menu to Doodle there are
now two different ways to set the current shape type. You may notice that the current shape type
indicated by the menu items is not synchronized with the current shape type indicated by the buttons
along the top of the content pane. That's ok for now. You will have an opportunity to correct this a little
later on in the course.
Transcript
button.setActionCommand("Edit");
Quiz
In this quiz, you’ll test your knowledge of menu and
toolbar basics.
Exercise
Click the Exercise button to add a toolbar to the
Doodle application.
Exercise
Transcript
Sharing action If you don't care about matching GUI elements, there
commands is a simpler approach to coordinating actions among
multiple components. All you have to do is set the
action command strings to match. In fact, you've
probably already done this in the Doodle application
when you set the action commands for the toolbar
buttons. That is why the single
actionPerformed() method responds to both
menu item and toolbar button events.
Exercise
In this exercise, you’ll coordinate GUI actions in
Doodle.
Quiz
Menu and toolbar basics
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
Exercise
Source files
The GIF images for these buttons are available for download from the Resources page. The specific
images for this exercise can be found in the toolbar images folder. You’re also welcome to create your
own.
Hints
To create a separator (space) between toolbar buttons, call the addSeparator() method on the
JToolBar object, like this: toolbar.addSeparator();
Use the JToggleButton class for the toggle buttons that set the shape type. Keep in mind that the
toggle buttons on the toolbar should work like radio buttons. You’ll need to add them to a
ButtonGroup object for them to be mutually exclusive.
Use the JButton class for the select color button.
You will need to call addActionListener() on each toolbar button to register the application so
that it receives action events from the items.
Make sure to set the action command for the buttons by calling the setActionCommand() method on each
of them.
What to submit to the course tutors
In the text box below, cut and paste the new code for the Doodle class. Click OK, I'm Done to submit
your code to the course tutors.
Transcript
This code sets the tool tip text for a button to the
string "Copy", which is displayed whenever the
user pauses with the mouse cursor over the button.
Exercise
In this exercise, you’ll add tool tips to Doodle.
Exercise
if (cmd.equals("Line")) {
pad.setshapeType(DoodleShape.LINE);
lineItem.setSelected(true);
lineButton.setSelected(true);
}
Modify the actionPerformed() method in Doodle so that all of the graphic type commands are
properly coordinated.
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Discuss button on the toolbar, locate the module
topic folder that pertains to your question or
comment, and read through the discussions to see if
someone has already asked your question. If not,
post it yourself.
Quiz
Click the Quiz button to test what you've learned in
this module.
Exercise
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
● Play sounds
Quiz
Digging deeper into Swing
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
1.What do you use to navigate through the hierarchy of a menu and select
a menu item or invoke a menu command?
Please select the best answer.
A. A keyboard mnemonic
B. A keyboard accelerator
C. A hot-key
2.What special construct do you use to coordinate GUI actions that are
common to multiple components?
Please select the best answer.
A. The Action interface
B. The GUIAction class
C. The ActionEvent class
3.How do you add a space between buttons on a toolbar?
Please select the best answer.
A. Create and add a button with no label or icon to the toolbar.
B. Call the addSeparator() method on the toolbar object.
C. Create a JSeparator object and add it to the toolbar.
4.Which one of the following strings would best serve as tool tip text for a
toolbar button that allows the user to browse for and open a text file?
Please select the best answer.
A. Open a text file
B. Browse for a file and open it
C. Open file
JOptionPane.showMessageDialog(this,
"You are running low on memory.",
"Memory warning", JOptionPane.WARNING_MESSAGE);
JOptionPane.showConfirmDialog(this,
"Are you sure you want to exit the application?",
"Exit application", JOptionPane.YES_NO_OPTION);
Exercise
Add an option pane to Doodle in this exercise.
Transcript
Transcript
Quiz
Click the Quiz button to test your knowledge of
dialog boxes, option panes, and choosers.
Exercise
In this exercise, you’ll add a color chooser dialog
box to the Doodle application.
Exercise
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Quiz
Dialog boxes, option panes, and choosers
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
1.If you want to present information to the user and require no input from
her, which one of the following JOptionPane methods would you
use?
Please select the best answer.
A. showConfirmDialog()
B. showMessageDialog()
C. showInputDialog()
2.If the user presses the Yes button in a confirmation dialog box, the
showConfirmDialog() method returns the constant:
Please select the best answer.
A. YES_OPTION
B. YES_BUTTON
C. APPROVE_OPTION
3.Which one of the following static methods do you call in
JColorChooser class to invoke the color chooser dialog box?
Please select the best answer.
A. showColorDialog()
B. showOpenDialog()
C. showDialog()
Exercise
try {
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");
}
catch (Exception e) {
}
javax.swing.plaf.metal.MetalLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.mac.MacLookAndFeel
try {
String laf =
UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(laf);
}
catch (Exception e) {
}
Exercise
In this exercise, you’ll modify the Doodle application
so that it assumes the look and feel of the native
platform on which it is running.
Playing sound
Use sound to liven up user interfaces.
try {
AudioClip clip = Applet.newAudioClip(
new URL("file:" + "Applause.au"));
clip.play();
}
catch (MalformedURLException exception) {
}
Exercise
In this exercise, you’ll add sound support to Doodle.
Exercise
Exercise scoring
This exercise is worth a total of 1 point. You don't have to submit your code to the course tutors to
receive credit for this exercise.
Instructions
Modify the Doodle application so that it assumes the look and feel of the native platform on which it is
running.
After completing the exercise, click the OK, I'm Done button and the system will award you full credit.
Discussion
Do you have any questions or comments about the
material covered so far in this course? If so, click the
Discuss button on the toolbar, locate the module
topic folder that pertains to your question or
comment, and read through the discussions to see if
someone has already asked your question. If not,
post it yourself.
Quiz
Click the Quiz button to test what you’ve learned in
this module.
Playing sound
Why you call a static method
(Audio transcript)
It might seem strange that you must call a static
method in the Applet class to create an audio clip
for an application. This arrangement is due to the
fact that versions of Java prior to Java 2 only
supported the playback of audio clips within applets.
Since the Applet class already had support for
loading audio clips, the Java architects apparently
decided not to confuse things by moving it around.
Exercise
Playing sound
Spicing up Doodle with sound
Objective
Add sound support to Doodle.
Exercise scoring
Full credit for this exercise is 5 points. You'll submit your source code to the course tutors.
Source files
We've supplied two audio clips, Drip.au and Ding.au, in the download file available from the
Resources page. The clips for this exercise can be found in the folder called audio. You're also free to use
audio clips of your own.
Instructions
Modify the Doodle application so that it plays one sound when the user selects a new drawing tool and
another when the user creares a new shape.
Playing sounds for the two actions I mentioned involves adding code to the following places in the
Doodle code:
● the mouseReleased() event response method in the DoodlePad class
It doesn't really matter which sound you play in each of these methods, although I found that the Drip
audio clip sounded better when played in response to the user drawing a new graphic (releasing the
mouse button in DoodlePad). Also, keep in mind that there is a slight delay when loading and playing
an audio clip, so it's a good idea to play the clip before doing anything else in the methods.
What to submit to the course tutors
In the text box below, cut and paste the new source code for both the DoodlePad class and the
Doodle class. Click OK, I'm Done to submit your code to the course tutors.
Course conclusion
You’ve reached the end of your journey through
Swing. You now have a solid understanding of the
Swing toolkit and how it is used to build GUIs with
the Java 2 API. You've covered a lot of territory and
amassed a great deal of knowledge that will
undoubtedly prove helpful when you start building
GUIs of your own.
Quiz
Module quiz
Each question is worth one point. Some questions ask you to select the
best answer, others ask you to select all the correct answers. To receive
credit for questions asking for all the correct answers, you must select all
the correct answers and only the correct answers.
1.If you don't explicitly set the look and feel of an applet or application,
Swing will:
Please select the best answer.
A. Default to using a text-based user interface
B. Automatically use the Java look and feel
C. Automatically use the Windows look and feel
2.Which of the following look and feels could you use on a Windows
platform?
Please select the best answer.
A. Windows, Motif, and Mac
B. Windows, Mac, and Java
C. Windows, Java, and Motif
3.What class contains the static methods used to get and set the look and
feel for an application?
Please select the best answer.
A. UIManager
B. JFrame
C. LAFSelector
4.What static method do you call to create and load an audio clip?
Please select the best answer.
A. AudioClip.loadAudioClip()
B. AudioClip.newAudioClip()
C. Applet.newAudioClip()
Course conclusion
GUI design and construction with
Swing (Audio transcript)
Before you go, I want to leave you with a few
thoughts regarding GUI design and construction with
Swing. The first thing to understand is that there is
no such thing as a right or wrong GUI design. Your
ultimate goal in designing GUIs is to make them as
intuitive and easy to use as possible. One way to
achieve this goal is to keep things simple. Many of
the most elegant GUIs are relatively simplistic.
Software can be complicated enough without
overburdening users with complex GUIs.
Please read each of the following statements and then select the sentiment
that most closely matches your reaction. Following the statements is the
most important part of this short survey--a space for you to provide
feedback in your own words.
The DigitalThink Web site
1. The pages on the DigitalThink Web site were quick to load.
strongly agree
agree
neutral
disagree
strongly disagree
2. The DigitalThink site is easy to navigate through.
strongly agree
agree
neutral
disagree
strongly disagree
3. I was able to learn all I needed to know about DigitalThink courses
from the information on the site.
strongly agree
agree
neutral
disagree
strongly disagree
4. The design of the DigitalThink site struck me as confusing and unclear.
strongly agree
agree
neutral
disagree
strongly disagree
5. I have a clear understanding of what DigitalThink does and how
Web-based training at DigitalThink works.
strongly agree
agree
neutral
disagree
strongly disagree
Your course experience
6. The course covered the materials that I expected it would.
strongly agree
agree
neutral
disagree
strongly disagree
7. I found it easy to navigate through the course.
strongly agree
agree
neutral
disagree
strongly disagree
8. The course Syllabus window was a useful tool for moving through the
course.
strongly agree
agree
neutral
disagree
strongly disagree
9. There was too much text to read in most of the lessons.
strongly agree
agree
neutral
disagree
strongly disagree
10. The quizzes were an important part of my overall course experience.
strongly agree
agree
neutral
disagree
strongly disagree
11. The course audio worked well and I could easily understand the
instructor's spoken comments.
strongly agree
agree
neutral
disagree
strongly disagree
12. The interactive Chat and Discussion areas were an important and fun
part of my overall course experience.
strongly agree
agree
neutral
disagree
strongly disagree
Learning via the Web
13. Web-based learning at DigitalThink enabled me to learn the course
materials quickly and conveniently.
strongly agree
agree
neutral
disagree
strongly disagree
14. My DigitalThink course was a more effective learning method than I
thought it would be.
strongly agree
agree
neutral
disagree
strongly disagree
15. I would rather learn from a book instead of taking another
DigitalThink course.
strongly agree
agree
neutral
disagree
strongly disagree
16. I would rather take a CD-ROM-based training course than learn from
DigitalThink.
strongly agree
agree
neutral
disagree
strongly disagree
17. I would rather take a classroom-based training course with a live
instructor than learn via the Web using DigitalThink.
strongly agree
agree
neutral
disagree
strongly disagree
18. I would be interested in taking another Web-based course from
DigitalThink.
strongly agree
agree
neutral
disagree
strongly disagree
19. If I needed to learn a new skill for my job, I would check with
DigitalThink to see if they offered a Web-based course on the topic.
strongly agree
agree
neutral
disagree
strongly disagree
20. The best feedback we get comes in the form of your own words. In
two sentences or more, how would you describe your DigitalThink course
experience to a friend?
Thank you for taking the time to help us make the DigitalThink experience
the greatest way to learn!
Academic Credit
You can receive academic credit upon successful completion of most
DigitalThink courses.
Students who successfully complete a course receive Continuing
Sampler Courses Education Units (CEUs), which are then applicable (for most courses)
C, C++ Programming towards transcripted college credit at the University of Phoenix. The
Database Concepts number of credits awarded for each course varies with the length of
Design & Publishing the course.
Desktop
IT Management The University of Phoenix is the largest accredited private university in
Internet Literacy the US, and offers on-site classes at locations in twelve states. The
Java Programming UOP Online degree program is available to students worldwide.
Lotus
MS Certification:MCDBA How to earn CEUs from DigitalThink
MS Certification:MCSD
MS Certification:MCSE
Object Programming
How to obtain college credit from the University of Phoenix
Networking
Oracle Frequently Asked Questions
UNIX
Web Programming
Windows Programming
Contact
Use these email addresses to direct your questions or comments to the appropriate person at
DigitalThink.
[email protected] Our Sales Team can set up a Corporate Account to provide Web-based
training to your entire company. We can also produce and deliver custom courses to help your
organization train employees, sales people, or customers.
request support If you're having trouble using your credit card to buy a course, or if you can't
log into a course you're registered for, please contact us.
[email protected] Use this address to get more general information about our company.
[email protected] How do we look? Comments and questions about our site design or
graphics should be sent here.
[email protected] If you've discovered a bug (for example, a broken link or an image that
won't load), let us know. The more details you can give us about the problem, the better.