Java Reference
In-Depth Information
An image icon can be displayed in a label or a button using new JLabel(imageIcon)
or new JButton(imageIcon) . Listing 12.8 demonstrates displaying icons in labels
and buttons. The example creates two labels and two buttons with icons, as shown in
Figure 12.13.
F IGURE 12.13
The image icons are displayed in labels and buttons.
L ISTING 12.8 TestImageIcon.java
1
import javax.swing.*;
2
import java.awt.*;
3
4
public class TestImageIcon extends JFrame {
5
6
private ImageIcon usIcon = new ImageIcon( "image/us.gif" );
create image icons
private ImageIcon myIcon = new ImageIcon( "image/my.jpg" );
7
private ImageIcon frIcon = new ImageIcon( "image/fr.gif" );
8
private ImageIcon ukIcon = new ImageIcon( "image/uk.gif" );
9
10 public TestImageIcon() {
11 setLayout( new GridLayout( 1 , 4 , 5 , 5 ));
12
13 add( new JLabel(myIcon));
14
15 add( new JButton(ukIcon));
16 }
17
18 /** Main method */
19 public static void main(String[] args) {
20 TestImageIcon frame = new TestImageIcon();
21 frame.setTitle( "TestImageIcon" );
22 frame.setSize( 200 , 200 );
23 frame.setLocationRelativeTo( null ); // Center the frame
24 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
25 frame.setVisible( true );
26 }
27 }
add( new JLabel(usIcon));
a label with image
add( new JButton(frIcon));
a button with image
Note
Borders and icons can be shared. Thus, you can create a border or icon and use it to set
the border or icon property for any GUI component. For example, the following
statements set a border b for the panels p1 and p2 :
sharing borders and icons
p1.setBorder(b);
p2.setBorder(b);
The following statements set an icon in the buttons jbt1 and jbt2 :
jbt1.setIcon(icon);
jbt2.setIcon(icon);
 
Search WWH ::




Custom Search