public class Map extends JFrame implements Runnable
{
//地图的构造函数
public Map()
{
this.setLayout(null);
this.setBounds(0,0,400,400);
this.setVisible(true);
}
Random r = new Random();
//定义食物列表
List<JButton> food = new ArrayList();
/*每调用一次方法,往食物列表里面添加了一个食物
* */
public void createFood()
{
JButton bt = new JButton();
int x = r.nextInt(81)*5;
int y = r.nextInt(81)*5;
bt.setBounds(x,y,5,5);
food.add(bt);
}
//显示所有食物
public void showFood()
{
for(int i=0;i<food.size();i++)
{
this.getContentPane().add(food.get(i));
}
}
/*显示食物的线程
* */
public void run()
{
while(true)
{
try
{
createFood();
showFood();
this.update(getGraphics());
Thread.sleep(5000);
}
catch(Exception e)
{
}
}
}
}
以上是代码片段,大家也都能看出来这是一个贪食蛇的源代码,我想问的是,显示食物的线程中,在 [color=#FF9900]createFood();
showFood();
this.update(getGraphics());this.update(getGraphics())有啥作用,为什么没有它就不能显示食物,具体是怎么样实现的,谢谢[/color]
{
//地图的构造函数
public Map()
{
this.setLayout(null);
this.setBounds(0,0,400,400);
this.setVisible(true);
}
Random r = new Random();
//定义食物列表
List<JButton> food = new ArrayList();
/*每调用一次方法,往食物列表里面添加了一个食物
* */
public void createFood()
{
JButton bt = new JButton();
int x = r.nextInt(81)*5;
int y = r.nextInt(81)*5;
bt.setBounds(x,y,5,5);
food.add(bt);
}
//显示所有食物
public void showFood()
{
for(int i=0;i<food.size();i++)
{
this.getContentPane().add(food.get(i));
}
}
/*显示食物的线程
* */
public void run()
{
while(true)
{
try
{
createFood();
showFood();
this.update(getGraphics());
Thread.sleep(5000);
}
catch(Exception e)
{
}
}
}
}
以上是代码片段,大家也都能看出来这是一个贪食蛇的源代码,我想问的是,显示食物的线程中,在 [color=#FF9900]createFood();
showFood();
this.update(getGraphics());this.update(getGraphics())有啥作用,为什么没有它就不能显示食物,具体是怎么样实现的,谢谢[/color]
this.update实质就是调用了paint方法,lz可以参考api说法。
showFood();方法里面对UI元素的操作就无法立马显示出来具体的实现就就看JFrame的update源码,执行的是repaint方法