I can't get my icon to show up in my JLabel swing component
Below is the java Swing code to place a icon in a JLabel Swing component.
package com.TheMcLeodgrp;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.开发者_JS百科swing.JLabel;
public class Main extends JFrame {
public Main() throws HeadlessException {
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
Icon icon = new ImageIcon("myIcon.gif");
JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);
JLabel label2 = new JLabel("Address :", JLabel.LEFT);
label2.setIcon(new ImageIcon("myIcon.gif"));
getContentPane().add(label1);
getContentPane().add(label2);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
It is a simple label program where everything else works fine. The icon (myIcon.gif) just wont show up in the label when I run the program. I am running it from a standard Eclipse IDE, and myIcon.gif resides in a folder - ie; images/myIcon.gif. It seems like I missing something simple here, but I don't know. Do I need to place the icon somewhere else in the application.
I think the following article will do much better job of explaining how to load image resources then I will :)
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/icon.html
I'll second @eugener's recommendation on the tutorial. Also, try using the relative path, and check the result of constructing the ImageIcon
:
JLabel label2 = new JLabel("Address :", JLabel.LEFT);
ImageIcon icon = new ImageIcon("images/myIcon.gif");
if (icon.getIconWidth() == -1) {
JOptionPane.showMessageDialog(null,
"No image!", "Gahh!", JOptionPane.ERROR_MESSAGE);
} else {
label2.setIcon(icon);
}
精彩评论