【发布时间】:2012-12-10 11:55:51
【问题描述】:
我正在使用 eclipse,我想将图像添加到我的 GUI 的标签或徽标上。
我希望它看起来像这样!
我把它上传到网上是因为我没有 10 声望。
(命名酷程序)是图片
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)
【问题讨论】:
-
"I am using eclipse and I want to add a image onto a label or a logo for my GUI. I want it to LOOK LIKE THIS!"... 好的,那么您的具体问题是什么?当你尝试时会发生什么?例外?它不编译?你的电脑炸成 1000 位? -
那是你要放入程序的图像,还是“NAMES COOL PROGRAM”代表你要添加的图像?
-
我猜是你的问题(我们不应该这样做!),但也许你当前的 GUI 并没有按照你想要的方式布置。如果是这样,那么您将需要访问Layout Manager Tutorial 以了解如何使用可用于 Swing GUI 的各种布局。完成此操作后,请考虑下载 MigLayout。
-
如果问题是图像没有出现,请检查
logo.gif是否与MainClass位于同一位置。 -
ImageIcon的问题是它不会以任何有意义的方式报告无法加载图像。尝试改用getClass ().getResource ("/logo.gif")并使用ImageIOAPI,因为如果无法加载图像,它至少会抛出Exception
标签: java image swing user-interface embedded-resource