I want to add an image to JPanel in JApplet (so that I could create the jar file), so I used :
Image x = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
but the java.lang.NullPointerException occured. I'm sure the image path is correct, because the applet run fine when I used :
Image image = ImageIO.read(new File("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
The exceptions :
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)
The code:
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);
}
}
}
What could be the problem?
getClass().getResource()
Works only for the class path of the project.
You need to put the image file on the class path in order to find
Where ImageIO.read()
can read whatever is passed in the params as input stream.