package amVIP;import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.ImageIcon; class MainFrame extends JFrame {
JPanel contentPane;
JLabel imageLabel = new JLabel();
JLabel headerLabel = new JLabel(); public MainFrame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(new Dimension(400, 300));
setTitle("Your Job Crashed!");
// add the header label
headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
headerLabel.setText(" Your job crashed during the save process!");
contentPane.add(headerLabel, java.awt.BorderLayout.NORTH);
// add the image label
ImageIcon ii = new ImageIcon(this.getClass().getResource("snoopy_dancing.gif"));
//上句出错。我不知道this.class是什么意思,指的是本类MainFrame吗?
imageLabel.setIcon(ii);
contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
// show it
this.setLocationRelativeTo(null);
this.setVisible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
} public static void main(String[] args) {
new MainFrame();
} }
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.ImageIcon; class MainFrame extends JFrame {
JPanel contentPane;
JLabel imageLabel = new JLabel();
JLabel headerLabel = new JLabel(); public MainFrame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(new Dimension(400, 300));
setTitle("Your Job Crashed!");
// add the header label
headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
headerLabel.setText(" Your job crashed during the save process!");
contentPane.add(headerLabel, java.awt.BorderLayout.NORTH);
// add the image label
ImageIcon ii = new ImageIcon(this.getClass().getResource("snoopy_dancing.gif"));
//上句出错。我不知道this.class是什么意思,指的是本类MainFrame吗?
imageLabel.setIcon(ii);
contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
// show it
this.setLocationRelativeTo(null);
this.setVisible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
} public static void main(String[] args) {
new MainFrame();
} }
使用getClass().getResource("...") 来获取的资源必须放到classpath下
http://hi.baidu.com/sdfabc027/blog/item/be915cd6045b23d7a044df4a.html
.\classes\amVIP\MainFrame.classjava -cp classes;resources MainFrame
.\amVIP\MainFrame.classjava -cp . MainFrame
at javax.swing.ImageIcon.<init>(Unknown Source)
at amVIP.MainFrame.<init>(readGif.java:27)
at amVIP.MainFrame.main(readGif.java:39)
ImageIcon ii = new ImageIcon(this.getClass().getResource("snoopy_dancing.gif"));
替换成
ImageIcon ii = new ImageIcon("x:/images/snoopy_dancing.gif");
测试通过。
不会贴图,你就凑合看吧。测试也通过。
amVIP
|
-> MainFrame.java
->a.gif
=》
this.getClass().getClassLoader().getResource("snoopy_dancing.gif")
snoopy_dancing.gif所在的目录也必须使用 -classpath 加进来