In this magercise, you'll learn about adding an Icon
, or
small image, to a JButton
and placing components within a
JFrame
. You'll create two buttons with images on them and
respond to the selection of each. In addition to physically selecting
the button with a mouse, you'll support keyboard selection through
accelerators.
Magercise 3 Prerequisites
None.
Skeleton Code
FirstSwing.java
Resources
Tasks
Import the swing package.
Define two Icon
instance variables in class
FirstSwing
called bee
and dog
.
Then, load the bee.gif
and dog.gif
image files.
Create buttons top
and bottom
with icons
bee
and dog
.
Add an accelerator for each button.
When working with a JFrame
, you add components to an internal
area of the JFrame
, instead of the actual frame. Get a reference
to this Container
via the getContentPane()
method.
To have the buttons appear one on top of each other, modify the skeleton's
constructor so that it sets the content's layout to GridLayout
with
2 rows and 1 column.
Add the buttons to the grid layout.
Save everything and compile the program. Then run it to see the results.
Clicking a button or using the accelerator displays a message to the screen.
As a precaution, the Save command appends a "1"
to the end of the filename you want to save. This can help
prevent you from accidently overwriting your source code.
Note: The accelerator key is ALT under Win32 and Solaris.
Where help exists, the task numbers above are linked to the
step-by-step
help page.
The following JavaTM source file represents
a solution to this Magercise.
Copyright © 1998-1999
MageLang Institute.
All Rights Reserved.