MyImg.java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
public class MyImg {
private BufferedImage img;
private int x,y;
public MyImg( String imageFileName, int x, int y) {
this.x = x;
this.y = y;
try{
img = ImageIO.read(new File(imageFileName));
} catch (IOException e) {
}
}
public void paint(Graphics2D g) {
g.drawImage(img, x, y, img.getWidth(), img.getHeight(), null);
}
}
Frametester.java
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
This program demonstrates how to install an action listener.
*/
public class FrameTester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
DrawImageTester theImgTester = new DrawImageTester();
frame.add(theImgTester);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 600;
}
DrawImageTester.java
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
public class DrawImageTester extends JComponent{
private MyImg img1, img2;
public DrawImageTester() {
img1 = new MyImg(Definition.IMG_BG_BLACK, 100, 100 );
img2 = new MyImg(Definition.IMG_BG_WHITE, 200, 100);
}
public void paint(Graphics h) {
Graphics2D g = (Graphics2D)h;
img1.paint(g);
img2.paint(g);
}
}
Definition.java
public class Definition{
final public static String IMG_BG_BLACK = "image/black.PNG";
final public static String IMG_BG_WHITE = "image/white.PNG";
final public static String IMG_KNIGHT_BLACK = "image/bKn.png";
}
When I run FrameTester.java, I get the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at MyImg.paint(MyImg.java:27)
at DrawImageTester.paint(DrawImageTester.java:17)
The problem lies within this line:
public void paint(Graphics2D g) {
g.drawImage(img, x, y, img.getWidth(), img.getHeight(), null);
}
I think this is caused by an object not being initialized. I am pretty sure img is initialized. img is declared in MyImg.java, the MyImg object is created in the DrawImageTester.java class. The DrawImageTester object is created inside main. Both x, and y, have values, and getWidth, and getHeight are methods of the BufferedImage class. Can anyone lend me some help?