Adding an Icon to a JButton Component
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Main {
public static void main(String[] argv) throws Exception {
// Retrieve the icon
Icon icon = new ImageIcon("icon.gif");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the button; the icon will appear to the left of the label
JButton button = new JButton(action);
}
}
Related examples in the same category