package 贪食蛇;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;/**随机产生Apple(贪食蛇食物)*/
public class Apple extends JPanel{
private int x;    //Apple 随机位置的x坐标
private int y;    //Apple 随机位置的y坐标

public Apple(){
int tempX=(int)(Math.random()*22);
int tempY=(int)(Math.random()*22);
setX(tempX);
setY(tempY);
//创建一个Timer
Timer timer=new Timer(1000,new TimerListener());
timer.start();
}

//设定Apple横坐标
public void setX(int x){
this.x=x;
}

//设定Apple纵坐标
public void setY(int y){
this.y=y;
}

//获取Apple的横坐标
public int getX(){
return this.x;
}

//获取Apple的纵坐标
public int getY(){
return this.y;
}

//画出Apple
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(0, 0, 220, 220);

g.fillRect(getX()*10, getY()*10, 10, 10);
System.out.println("x:"+getX()+"\t"+"y:"+getY());


int tempX=(int)(Math.random()*22);
int tempY=(int)(Math.random()*22);
setX(tempX);
setY(tempY);
}

class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}

}
package 贪食蛇;
import javax.swing.*;;public class Snakes1 extends JFrame{
public Snakes1(){
//创建一个Apple对象
add(new Apple());
} public static void main(String[] args) {
// TODO 自动生成方法存根
Snakes1 frame=new Snakes1();
frame.setTitle("Snakes1");
frame.setSize(250,250);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}这是我写贪食蛇的第一步
写的很不顺,我写了个Apple()类贪食蛇的食物,为此我写了个测试,让它每秒钟在画板上随机画一次,
我采用的方法是,就像每次那张纸画个画,然后把原来的盖上
可运行的结果就是每次盖不齐,不知道怎么解决,或者有更好的思路