我们设置背景实在MyPanel类中,这个类中有paintComponent()方法,我们重写了父类的方法,在g.drawImage()中设置了背景的位置,因此要想实现背景滚动,我们需要将背景的位置坐标从常量变为变量。
首先定义一个计时器整形变量,相当于程序里的时间,我们可以利于该时间变量去修改位置变量。 所以我们还需要定义一个位置变量。
public int time = 0;
public int top = 0;
在paintComponent()中添加代码, 控制位置变量
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(this.bgImage, 0,
top-this.bgImage.getHeight(this),
this.bgImage.getWidth(this),
this.bgImage.getHeight(this),
null);
g.drawImage(this.bgImage, 0,top,
this.bgImage.getWidth(this),
this.bgImage.getHeight(this),
null);
time ++;
if(time == 10000)
time = 0;
if(time % 10 == 0)
{
top ++;
if(top >= this.bgImage.getHeight(this))
{
top = 0;
}
}
}
每隔一定的时间我们就需要重绘我们的myPanel,所以我们把这个交给线程,新建一个线程的包。包取名为thread
类取名为DrawbleThread, 这个类继承与Thread
package thread;
public class DrawbleThread extends Thread{
public DrawbleThread()
{
}
}
由于我们要调用MyPane中的repaint()方法,所以在线程类的构造函数中需要接受MyPanel 类型的参数。记得导入包。
package thread;
import view.MyPanel;
public class DrawbleThread extends Thread{
public MyPanel myPanel;
public DrawbleThread(MyPanel myPanel)
{
this.myPanel = myPanel;
}
}
附加:
当程序调用start()方法时,会创建一个新线程,然后执行run()方法。
所以在线程中重写run()方法。在run方法中重绘我们面板 myPanel
package thread;
import view.MyPanel;
public class DrawbleThread extends Thread{
public MyPanel myPanel;
public DrawbleThread(MyPanel myPanel)
{
this.myPanel = myPanel;
}
public void run()
{
while(true)
{
this.myPanel.repaint();
}
}
}
然后我们去MyPanel类中的构造函数添加并且启动我们的线程。
package view;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
import thread.DrawbleThread;
public class MyPanel extends JPanel{
public Image bgImage;
public int time = 0;
public int top = 0;
public DrawbleThread drawbleThread;
public MyPanel()
{
//设置背景
this.bgImage = Toolkit.getDefaultToolkit().getImage("images/bg01.jpg");
//创建线程
this.drawbleThread = new DrawbleThread(this);
//启动线程
this.drawbleThread.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(this.bgImage, 0,
top-this.bgImage.getHeight(this),
this.bgImage.getWidth(this),
this.bgImage.getHeight(this),
null);
g.drawImage(this.bgImage, 0,top,
this.bgImage.getWidth(this),
this.bgImage.getHeight(this),
null);
time ++;
if(time == 10000)
time = 0;
if(time % 10 == 0)
{
top ++;
if(top >= this.bgImage.getHeight(this))
{
top = 0;
}
}
}
}