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() {

    private void initComponenets() {
        setTitle("My Buttons");
        setSize(200, 200);

        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"));
        JButton cancelButton = new JButton("CANCEL", new ImageIcon("cancel.png"));


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

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply