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

JButton with ImageIcon

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.