Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Creating Buttons With Icons

 

Training Index

[Help | Solution | API Docs | Short Course | Magercises]

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

  1. Import the swing package.


  2. Define two Icon instance variables in class FirstSwing called bee and dog. Then, load the bee.gif and dog.gif image files.


  3. Create buttons top and bottom with icons bee and dog.


  4. Add an accelerator for each button.


  5. 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.


  6. 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.


  7. Add the buttons to the grid layout.


  8. 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.


  9. 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.

result.gif

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 Java source file represents a solution to this Magercise.

Solution

Magercise 4

Short Course

About This Short Course

Copyright © 1998-1999 MageLang Institute. All Rights Reserved.