Java Reference
In-Depth Information
EXAMPLE:
(continued)
In this GUI, a label becomes visible or invisible when a button is clicked. For exam-
ple, the following code from the method
actionPerformed
in Display 18.9 determines
what happens when the button with the text
"Wave"
on it is clicked:
if
(actionCommand.equals("Wave"))
{
wavingLabel.setVisible(
true
);
standingLabel.setVisible(
false
);
}
We used the
setVisible
method on the labels containing the icons rather than directly
on the icons because the class
ImageIcon
does not have the
setVisible
method.
The two statements
wavingLabel.setVisible(
true
);
standingLabel.setVisible(
false
);
make
wavingLabel
visible and
standingLabel
invisible.
Display 18.9
Labels with Changing Visibility
(part 1 of 3)
1
import
javax.swing.JFrame;
2
import
javax.swing.ImageIcon;
3
import
javax.swing.JPanel;
4
import
javax.swing.JLabel;
5
import
javax.swing.JButton;
6
import
java.awt.BorderLayout;
7
import
java.awt.FlowLayout;
8
import
java.awt.Color;
9
import
java.awt.event.ActionListener;
10
import
java.awt.event.ActionEvent;
11
public class
VisibilityDemo
extends
JFrame
12
implements
ActionListener
13
{
14
public static final int
WIDTH = 300;
15
public static final int
HEIGHT = 200;
16
private
JLabel wavingLabel;
17
private
JLabel standingLabel;
18
public static void
main(String[] args)
19
{