我正试图在java中制作蛇游戏,但蛇并没有出现在屏幕上,我不知道为什么......这是我的代码...我已经制作了它分为三类
public class SnakeGame extends JFrame {
public SnakeGame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.green);
setSize(WIDTH, HEIGHT);
setTitle("Snake Game");
setVisible(true);
setResizable(false);
play p = new play();
add(p);
pack();
}
public static void main(String[] args) {
new SnakeGame();
}
}
public class play extends JPanel implements Runnable{
public static final int WIDTH = 700,HEIGHT = 700;
private ArrayList<SnakeDesign> snake;
public play(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
snake = new ArrayList<SnakeDesign>();
}
public void paint(Graphics g){
for(int i=0;i<snake.size();i++){
snake.get(i).paintSnake(g);
}
}
@Override
public void run() {
repaint();
}
}
public class SnakeDesign {
private int Xcoor, Ycoor, width, height;
public SnakeDesign(int Xcoor, int Ycoor,int tileSize){
this.Xcoor = Xcoor;
this.Ycoor = Ycoor;
width = tileSize;
height = tileSize;
}
public void paintSnake (Graphics g){
g.setColor(Color.red);
g.drawRect(Xcoor*width, Xcoor*height, width, height);
}
所以请有人说为什么蛇不会出现......提前谢谢
答案 0 :(得分:6)
paint(Graphics g)
方法,而是覆盖其paintComponent(Graphics g)
方法。这有很多原因,其中一些包括
super.paintComponent(g)
覆盖中调用超级paintComponent(Graphics g)
方法。setVisible(true)
最后,而不是之前。snake.add(...)
将一个体元素传递给蛇?如果你给你的蛇没有身体,它会显示什么?run()
,因此它实际上什么都不做)。