- 程序 进程 线程
- 步骤一:画窗体
- 鼠标监听器
- 多线程的实现
- 弹球的实现
详见面试专题(后期补坑)。
步骤一:画窗体调用Jframe类,绘制窗体(在Java五子棋开发思路【蓝杰项目】有详细的介绍哦)。
public void showUI(){
this.setSize(800,800);
this.setTitle("THREAD");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
this.setVisible(true);
GameMouse gameMouse = new GameMouse(this.getGraphics());
this.addMouseListener(gameMouse);
}
鼠标监听器
由于我们需要通过鼠标有交互动作,所以我创建了一个GameMouse的类继承MouseAdapter,实现鼠标动作的监听。
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
GameThread gameThread = new GameThread(g,x,y);
gameThread.start();
}
其中重写了mouseClicked方法。
多线程的实现GameThread是继承了Thread类,这样就可以去实现多线程了。
PS:
1.需要将这个线程的任务在run方法中重写。
2.在调用时不要gameThread.run();这样就是调用方法而不是启动线程,线程如何工作请看线程生命周期【面试问题】。
gameThread.run();
启动线程应安装下面方法启动。
gameThread.start();弹球的实现
随机生成一个数,然后对4取余,对应这小球运动的四个方向,然后判断到边界回弹即可。
public void run(){
Random random = new Random();
int flag = random.nextInt(4);
System.out.println(flag);
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
if(flag == 0){
g.fillOval(x++,y++,20,20);
if(y>=771){
flag = 1;
}
if(x>=771){
flag = 2;
}
}
else if(flag == 1){
g.fillOval(x++,y--,20,20);
if(x>=771){
flag = 3;
}
if(y<=59){
flag = 0;
}
}
else if (flag == 2){
g.fillOval(x--,y++,20,20);
if(y>=771){
flag = 3;
}
if(x<=0){
flag = 0;
}
}else {
g.fillOval(x--,y--,20,20);
if(x<=0){
flag = 1;
}
if(y<=59){
flag = 2;
}
}
}
}



