How do I display an image in JButton?

Category: javax.swing, viewed: 13376 time(s).
package org.kodejava.example.swing;

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

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

    private void initComponenets() {
        setTitle("My Buttons");
        setSize(200, 200);
        setDefaultCloseOperation(JFrame.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);
            }
        });
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats