当前位置: 代码迷 >> J2SE >> java在窗口中显示文本和图形解决方法
  详细解决方案

java在窗口中显示文本和图形解决方法

热度:163   发布时间:2016-04-24 12:11:13.0
java在窗口中显示文本和图形
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);
------解决方案--------------------
楼上说了答案
  相关解决方案