我正在尝试使用 JFrame/JPanel 使用 Canvasto 转换游戏。以前我有 Game 对象 Extend Canvas 并实现 Runnable
然后创建一个 JFrame 并将其传递给画布......
以前是什么:(有效)
public class Game extends Canvas implements Runnable{
private void render() {
// TODO Auto-generated method stub
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//////////////////////////////
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.drawImage(background,0,0,null);
p.render(g);
c.render(g);
//g.drawImage(player,100,100,this);
//////////////////////////////
g.dispose();
bs.show();
}
public static void main (String args[]){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
}
但我想改为在 JPanel 上而不是 Canvas 上绘制图形,并将其传递给 JFrame .. 但它不起作用..
public class Game extends JPanel implements Runnable{
private void render() {
// TODO Auto-generated method stub
BufferStrategy bs = this.getBufferStrategy(); // error here
if(bs==null){
createBufferStrategy(3); //error here
return;
}
public static void main (String[] args){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
}
Exception in thread "Thread-1" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
使困惑...