Tuesday, January 21, 2014

JButton with Icon

JButton with Icon
JButton with Icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaExample extends JFrame {

    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        ImageIcon dukesIcon = null;
        java.net.URL imgURL = JavaExample.class.getResource("dukes_36x36.png");
        if (imgURL != null) {
            dukesIcon = new ImageIcon(imgURL);
        } else {
            System.err.println("Can't load icon! ");
        }

        JButton jButton = new JButton("java-buddy.blogspot.com",
                            dukesIcon);
        jButton.setVerticalTextPosition(JButton.BOTTOM);
        jButton.setHorizontalTextPosition(JButton.RIGHT);

        hPanel.add(jButton);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaExample myExample = new JavaExample();
        myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myExample.prepareUI();
        myExample.pack();
        myExample.setVisible(true);
    }
    
}

No comments:

Post a Comment