LabelFrame类:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class LabelFrame extends JFrame
{
private JLabel label1;
private JLabel label2;
private JLabel label3;
public LabelFrame()
{
super("Testing JLabel");
setLayout(new FlowLayout());
label1 = new JLabel ("Label with test");
label1.setToolTipText("This is label");
add(label1);
Icon bug = new ImageIcon(getClass().getResource("bug1.gif"));
label2 = new JLabel("Label with text and icon", bug,SwingConstants.LEFT);
label2.setText("Label with icon and text at bottom");
label3.setIcon(bug);
label3.setHorizontalTextPosition(SwingConstants.CENTER);
label3.setVerticalTextPosition(SwingConstants.BOTTOM);
label3.setToolTipText("This is label3");
add(label3);
}
}
创建并显示LabelFrame窗口:
import javax.swing.JFrame;
public class LabelTest {
/**
* @param args
*/
public static void main(String[] args)
{
LabelFrame labelFrame = new LabelFrame();
labelFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labelFrame.setSize(275, 180);
labelFrame.setVisible(true);
}
}
编译没错,就是在运行时出现个错误:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at Jlabel.LabelFrame.<init>(LabelFrame.java:25)
at Jlabel.LabelTest.main(LabelTest.java:12)
小弟实在不知道是错在哪了。麻烦各位大虾帮小弟看看,是错在哪了。
------解决方案--------------------
- Java code
Icon bug = new ImageIcon(getClass().getResource("bug1.gif"));
------解决方案--------------------
- Java code
label3 = new JLabel("Label with text and icon", bug, SwingConstants.LEFT);
------解决方案--------------------
楼上说了答案