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);
}
}
}
何が問題なのですか?