Monday, January 20, 2014

Example to create JLabel with icon

JLabel with icon
JLabel with icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
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! ");
        }

        JLabel jLabel = new JLabel("java-buddy.blogspot.com",
                            dukesIcon,
                            JLabel.CENTER);
        jLabel.setVerticalTextPosition(JLabel.BOTTOM);
        jLabel.setHorizontalTextPosition(JLabel.CENTER);

        hPanel.add(jLabel);
        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