Java Reference
In-Depth Information
You can add an icon to a label with the method setIcon , as follows:
setIcon
JLabel dukeLabel = new JLabel("Mood check");
dukeLabel.setIcon(dukeIcon);
Alternatively, you give the icon as an argument to the JLabel constructor, as follows:
JLabel dukeLabel = new JLabel(dukeIcon);
You can leave the label as created and it will have an icon but no text, or you can add
text with the method setText , as follows:
setText
dukeLabel.setText("Mood check");
Icons and text may be added to JButton s and JMenuItem s in the same way as they
are added to a JLabel . For example, the following is taken from Display 18.4, which is
a demonstration of the use of icons:
JButton happyButton = new JButton("Happy");
ImageIcon happyIcon = new ImageIcon("smiley.gif");
happyButton.setIcon(happyIcon);
Display 18.4 Using Icons (part 1 of 3)
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;
(continued)
Search WWH ::




Custom Search