我想在 JApplet 中向 JPanel 添加一个图像(以便我可以创建 jar 文件),所以我使用了:
Image x = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
但是发生了 java.lang.NullPointerException。我确定图像路径是正确的,因为我使用时小程序运行良好:
Image image = ImageIO.read(new File("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
例外情况:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:830)
at sun.awt.SunToolkit.getImage(SunToolkit.java:887)
at applet$CustomPanel.paintComponent(applet.java:65)
at javax.swing.JComponent.paint(JComponent.java:1029)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
编码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class applet extends JApplet {
public void init() {
//Execute a job on the event-dispatching thread:
//creating this applet's GUI.
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void createGUI() {
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("CLICK ME");
panel.add(button, BorderLayout.SOUTH);
panel.add(new CustomPanel(), BorderLayout.CENTER);
add(panel);
}
public class CustomPanel extends JPanel{
public void paintComponent(Graphics g) {
Image image = null;
try {
image = ImageIO.read(new File("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Image x = Toolkit.getDefaultToolkit().getImage(getClass().getResource("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
g.drawImage(x, 0, 0, null);
}
}
}
可能是什么问题呢?