我做错了什么?我的代码没有画任何东西.. 我找不到它出错的地方.. 我想画一些字段和图像但没有任何反应.. 甚至没有nullpointer异常?
public class Veldmaker extends Canvas {
private int numRows;
private int numCols;
private Graphics2D images;
public Veldmaker(int numRows, int numCols) {
this.numRows = numRows;
this.numCols = numCols;
setSize(numRows, numCols);
}
public void tekenVeld(Locatie locatie) throws IOException {
String filename = System.getProperty("user.dir")
+ java.io.File.separator + "src" + java.io.File.separator + "Sokoban"
+ java.io.File.separator + "Images" + java.io.File.separator + image
+ ".gif";
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("Muur.gif");
BufferedImage img = ImageIO.read(new File(filename));
images = (Graphics2D) img.getGraphics();
images.drawImage(img, locatie.x, locatie.y, null);
}
答案 0 :(得分:0)
public class Veldmaker extends Canvas {
private int numRows;
private int numCols;
//private Graphics2D images; // You don't need this
private BufferedImage img; // But you will need this to load your image once
public Veldmaker(int numRows, int numCols, String image) {
this.numRows = numRows;
this.numCols = numCols;
setSize(numRows, numCols); // this may work, depends on your Frame layout
// now I put in the content of your tekenVeld method
// image loading should be done in constructor
String filename = System.getProperty("user.dir")
+ java.io.File.separator + "src" + java.io.File.separator + "Sokoban"
+ java.io.File.separator + "Images" + java.io.File.separator + image
+ ".gif";
// Why this if you have already an image?
// InputStream stream = this.getClass().getClassLoader().getResourceAsStream("Muur.gif");
try {
img = ImageIO.read(new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
// we do this in paint method
// images = (Graphics2D) img.getGraphics();
// images.drawImage(img, locatie.x, locatie.y, null);
}
@Override
public void paint(Graphics g){
g.drawImage(img, 0, 0, null);
}
}
现在,如果你像这样使用它,你的类应该可以工作
public static void main(String s[]) {
JFrame frame = new JFrame("Hello");
frame.setLayout(new FlowLayout());
frame.add(new Veldmaker(100,100, "yourImage"));
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}