Java Reference
In-Depth Information
Display 18.4
Using Icons
(part 1 of 2)
1
import
javax.swing.JFrame;
2
import
javax.swing.JPanel;
3
import
javax.swing.JTextField;
4
import
javax.swing.ImageIcon;
5
import
java.awt.BorderLayout;
6
import
java.awt.FlowLayout;
7
import
java.awt.Color;
8
import
javax.swing.JLabel;
9
import
javax.swing.JButton;
10
import
java.awt.event.ActionListener;
11
import
java.awt.event.ActionEvent;
12
public class
IconDemo
extends
JFrame
implements
ActionListener
13 {
14
public static final int
WIDTH = 500;
15
public static final int
HEIGHT = 200;
16
public static final int
TEXT_FIELD_SIZE = 30;
17
private
JTextField message;
18
public static void
main(String[] args)
19 {
20 IconDemo iconGui =
new
IconDemo();
21 iconGui.setVisible(true);
22 }
23
public
IconDemo()
24 {
25
super
("Icon Demonstration");
26 setSize(WIDTH, HEIGHT);
27 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28 setBackground(Color.WHITE);
29 setLayout(
new
BorderLayout());
30 JLabel dukeLabel =
new
JLabel("Mood check");
31 ImageIcon dukeIcon =
new
ImageIcon("duke_waving.gif");
32 dukeLabel.setIcon(dukeIcon);
33 add(dukeLabel, BorderLayout.NORTH);
34 JPanel buttonPanel =
new
JPanel();
35 buttonPanel.setLayout(
new
FlowLayout());
36 JButton happyButton =
new
JButton("Happy");
37 ImageIcon happyIcon =
new
ImageIcon("smiley.gif");
38 happyButton.setIcon(happyIcon);
39 happyButton.addActionListener(
this
);
40 buttonPanel.add(happyButton);
41 JButton sadButton =
new
JButton("Sad");
42 ImageIcon sadIcon =
new
ImageIcon("sad.gif");
43 sadButton.setIcon(sadIcon);
44 sadButton.addActionListener(
this
);
(continued)