我正在使用eclipse,我想在标签或GUI的徽标上添加一张图片。
我希望它看起来像这样!
我将其上传到网络上,因为我没有10个声望值。
(“Names cool program”)是该图片。
程序可以编译,但无法运行。会提示错误信息。
我希望它看起来像这样!
我将其上传到网络上,因为我没有10个声望值。
(“Names cool program”)是该图片。
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
public class MainClass extends JFrame{ // super class JFrame
// Kind of a tutorial for creating GUI's in java
private JLabel label;
private JLabel label1;
private JButton button;
private JTextField textfeild;
private ImageIcon image1; // image for my logo
public MainClass () {
setLayout (new FlowLayout());
image1 = new ImageIcon (getClass ().getResource ("logo.gif")); // declares image
label = new JLabel ("This is the label");
add (label);
label1 = new JLabel (image1); // adds image
add (label1);
textfeild = new JTextField (15);
add (textfeild);
button = new JButton ("Click");
add (button);
}
public static void main(String[] args) {
MainClass gui = new MainClass ();
gui.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // creates window
gui.setSize (300,300);
gui.setVisible (true);
gui.pack ();
gui.setTitle ("Title");
}
}
程序可以编译,但无法运行。会提示错误信息。
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at JonsCalc.<init>(JonsCalc.java:18)
at JonsCalc.main(JonsCalc.java:38)
ImageIcon
的问题在于它无法以任何有意义的方式报告当它不能加载图像时的情况。尝试使用getClass().getResource("/logo.gif")
,并使用ImageIO
API,因为它至少会抛出一个Exception
如果不能加载图像。 - MadProgrammer