Java实力弹弹球实现代码
程序员文章站
2024-03-13 14:07:57
先看看效果图:
直接上代码了。
微调按钮加画布画几个圆,再实现监听。。。
package cn.hncu.threaddemo.thread2;...
先看看效果图:
直接上代码了。
微调按钮加画布画几个圆,再实现监听。。。
package cn.hncu.threaddemo.thread2; import java.awt.canvas; import java.awt.color; import java.awt.graphics; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.focusevent; import java.awt.event.focuslistener; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jspinner; import javax.swing.timer; import javax.swing.event.changeevent; import javax.swing.event.changelistener; public class ballsjframe extends jframe implements changelistener{ private ballscanvas ball; private jspinner spinner; public ballsjframe(){ super("弹弹球"); this.setbounds(300, 200, 400, 300); this.setdefaultcloseoperation(exit_on_close); color colors[] = {color.red,color.green,color.blue,color.magenta,color.cyan}; ball = new ballscanvas(colors,100); this.getcontentpane().add(ball);//默认是center位置 jpanel panel = new jpanel(); this.getcontentpane().add(panel,"south"); panel.add(new jlabel("delay")); spinner = new jspinner(); spinner.setvalue(100); panel.add(spinner); spinner.addchangelistener(this); this.setvisible(true); } @override public void statechanged(changeevent e) { int value = integer.parseint(""+spinner.getvalue()); ball.setdelay(value); } public static void main(string[] args) { new ballsjframe(); } } class ballscanvas extends canvas implements actionlistener, focuslistener{ private ball balls[];//存放所有的球 private timer timer;//javax.swing.timer public ballscanvas(color colors[] ,int delay){ this.balls = new ball[colors.length]; for(int i=0,x=40;i<colors.length;i++,x+=20){ this.balls[i] = new ball(x,x,colors[i]); } //让当前画布监听 焦点事件 this.addfocuslistener(this); timer = new timer(delay,this); timer.start(); } public void setdelay(int delay){ timer.setdelay(delay); } @override public void paint(graphics g) { for(int i=0;i<this.balls.length;i++){ g.setcolor(balls[i].color); //让每个球的坐标变化一下---(x坐标) balls[i].x = balls[i].left ? balls[i].x-10:balls[i].x+10; //当球碰壁时,更改球的方向 if(balls[i].x<=0||balls[i].x>=this.getwidth()-24){ balls[i].left = !balls[i].left;//切换方向 } //让每个球的坐标变化一下---(y坐标) balls[i].y = balls[i].up ? balls[i].y-10:balls[i].y+10; //当球碰壁时,更改球的方向 if(balls[i].y<=0||balls[i].y>=this.getheight()-22){ balls[i].up = !balls[i].up;//切换方向 } g.filloval(balls[i].x, balls[i].y, 20, 20); } } @override public void actionperformed(actionevent e) { //system.out.println("aaa"); repaint();//刷新画布.调用paint(graphics g) } @override public void focusgained(focusevent e) { timer.stop(); } @override public void focuslost(focusevent e) { timer.restart(); } private static class ball{ int x,y; boolean up,left; color color; public ball(int x, int y, color color) { this.x = x; this.y = y; this.color = color; up = left = false; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java面试题目集锦
下一篇: 浅谈java泛型的作用及其基本概念