Java基于swing实现的弹球游戏代码(6)
/**
* 创建线程对象的方法
*
* @param speed
* :速度
*
*/
public void creatBall(int speed, int num) {
Random ran = new Random();
if (ml == null) {
g = UI.getGraphics();
ml = new Listener(g);
UI.addMouseListener(ml);
UI.addMouseMotionListener(ml);
}
for (int i = 0; i < num; i++) {
int x = ran.nextInt(600) + 10;
int y = ran.nextInt(300) + 100;
MyThread th = new MyThread(g, ml, UI, x, y, speed);
list.add(th);
th.start();
}
}
/**
* 得到命令的方法
*/
public String getCommand() {
return command;
}
}
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* 鼠标监听器的类
*
* @author Administrator
*
*/
public class Listener extends MouseAdapter {
private Graphics g;
private int x = 5, y = 620;
private int width = 100, height = 10;
public Listener(Graphics g) {
this.g = g;
}
public void mouseMoved(MouseEvent e) {
// 设置画布对象颜色
synchronized (this.g) {
g.setColor(Color.black);
g.fillRect(x, y, width, height);
x = e.getX();
g.setColor(java.awt.Color.green);
g.fillRect(x, y, width, height);
}
}
/**
* 得到x的方法
*
* @return:x
*/
public int getX() {
return x;
}
}
运行效果如下图所示:
希望本文所述对大家的Java程序设计有所帮助。