∟Creating Image Buttons with javax.swing.JButton Class
This section provides a tutorial example on how to create an image button with the JButton class and the ImageIcon class.
You can also create a button with your own image. Here is a sample program:
/**
* JButtonIcon.java
* Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.awt.*;
import javax.swing.*;
public class JButtonIcon {
public static void main(String[] a) {
JFrame f = new JFrame("My Icon Button");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton(new ImageIcon("java.gif"));
f.getContentPane().add(b);
f.pack();
f.setVisible(true);
}
}
If you run this example, you will get:
Note: The ImageIcon class is used to create a button with an image.
Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.1, 1.5.0, and 1.6.0.