How do I customize JButton icons?

The example below shows you how we can customize the icon for JButton swing components.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class JButtonCustomIcon extends JFrame {
    public JButtonCustomIcon() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        JButton button = new JButton("Press Me!");

        // Below is how we can set various icons for the JButton swing
        // component. There are the default icon, selected, disabled, presed
        // and rollover icons.
        button.setIcon(new ImageIcon("default.png"));
        button.setSelectedIcon(new ImageIcon("selected.png"));
        button.setDisabledIcon(new ImageIcon("disabled.png"));
        button.setDisabledSelectedIcon(new ImageIcon("disabledSelected.png"));
        button.setPressedIcon(new ImageIcon("pressed.png"));
        button.setRolloverIcon(new ImageIcon("rollover.png"));
        button.setRolloverSelectedIcon(new ImageIcon("rolloverSelected.png"));

        getContentPane().add(button);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JButtonCustomIcon().setVisible(true);
            }
        });
    }
}

How do I display an image in JButton?

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class ButtonImageExample extends JFrame {
    public ButtonImageExample() {
        initComponents();
    }

    private void initComponents() {
        setTitle("My Buttons");
        setSize(200, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));

        // Creates two JButton object with an images to display. The image can be
        // a gif, jpeg, png and some other type supported. And we also set the
        // mnemonic character of the button for short-cut key.
        JButton okButton = new JButton("OK", new ImageIcon("ok.png"));
        okButton.setMnemonic('O');
        JButton cancelButton = new JButton("Cancel", new ImageIcon("cancel.png"));
        cancelButton.setMnemonic('C');

        getContentPane().add(okButton);
        getContentPane().add(cancelButton);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ButtonImageExample().setVisible(true);
            }
        });
    }
}

JButton with ImageIcon