Help is available for each task, or you can go straight to
the solution source code.
Task 1
Import the swing package.
import javax.swing.*;
Task 2
Define two Icon
instance variables in class
FirstSwing
called bee
and dog
.
Then, load the bee.gif
and dog.gif
image files.
public Icon bee = new ImageIcon("bee.gif");
public Icon dog = new ImageIcon("dog.gif");
Task 3
Create buttons top
and bottom
with icons
bee
and dog
.
The following code defines the top
button.
JButton top = new JButton("A bee", bee);
top.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("bee");
}
});
The following code defines the bottom
button.
JButton bottom = new JButton("and a dog", dog);
bottom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("dog");
}
});
Task 4
Add an accelerator for each button.
Use the setMnemonic()
method.
top.setMnemonic (KeyEvent.VK_B);
bottom.setMnemonic (KeyEvent.VK_D);
Task 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.
Container content = getContentPane();
Task 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.
Add the following method call to the constructor.
content.setLayout(new GridLayout(2,1));
Task 7
Add the buttons to the grid layout.
content.add(top);
content.add(bottom);
Task 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.
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.
javac FirstSwing.java
java FirstSwing
If you are using Swing with JavaTM Developer Kit 1.1.+, make sure your
CLASSPATH environment variable has the swingall.jar
file in it.
Copyright © 1998-1999
MageLang Institute.
All Rights Reserved.