[英]Snake doesn't appear in the frame of a Java game
I am trying to make snake game in java but the snake doesn't shown up on the screen and I don't know why ... here is my code ... I've made it in three classes 我正在尝试用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);
}
so please can anyone say why the snake doesn't appear ... thanks in advance 因此,请任何人能说出为什么蛇不出现的原因...预先感谢
paint(Graphics g)
method but rather override its paintComponent(Graphics g)
method. 不要覆盖JPanel的paint(Graphics g)
方法,而是覆盖其paintComponent(Graphics g)
方法。 There are many reasons for this, and some include 造成这种情况的原因很多,其中包括
super.paintComponent(g)
method in your paintComponent(Graphics g)
override. 在paintComponent(Graphics g)
覆盖中调用上级的super.paintComponent(g)
方法。 setVisible(true)
last after adding all components, not before. 随时拨打setVisible(true)
最后将所有的组件,而不是之前后。 snake.add(...)
where you pass a body element into the snake? 在哪里将元素添加到ArrayList中,即在哪里将snake.add(...)
元素传递到蛇中? If you give your snake no body, what will it show? 如果您不给蛇任何身体,它将显示什么? run()
and so it is essentially doing nothing). 这将使您摆脱对Runnable接口的需要(该接口当前仅调用run()
,因此实际上什么也不做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.