java定时器弹弹球

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class BallsJFrame extends JFrame implements ChangeListener  //定义一个弹弹球类
{
private BallsCanvas canvas;  //弹弹球画布组件类 
private JSpinner spinner;   //微调问本行
public BallsJFrame(Color clolrs[])  //组件框架
{
super("弹弹球");
this.setBounds(400,200,400,300); //设立框架位置和就宽度高度
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.canvas=new BallsCanvas(clolrs,100);  //新建一个BallsCanvas对象,延时为100
this.getContentPane().add(this.canvas);
JPanel panel=new JPanel();
this.getContentPane().add(panel,"South");
panel.add(new JLabel("Delay"));
SpinnerNumberModel model=new SpinnerNumberModel();
model.setStepSize(20);
this.spinner=new JSpinner(model);
this.spinner.setValue(100);
this.spinner.addChangeListener(this);
panel.add(this.spinner);
this.setVisible(true);
}
public void stateChanged(ChangeEvent ev)
{
this.canvas.setDelay(Integer.parseInt(""+this.spinner.getValue()));
}
public static void main(String args[])
{
Color colors[]={Color.red,Color.green,Color.blue,Color.magenta,Color.cyan};
new BallsJFrame(colors);
}
}
class BallsCanvas extends Canvas implements ActionListener,FocusListener
{
private Ball balls[];
private Timer timer;
private static class Ball   //创建内部类
{
int x,y;
Color color;
boolean up,left;
Ball(int x,int y,Color color)
{
this.x=x;
this.y=y;
this.color=color;
up=left=false;
}
}
public BallsCanvas(Color colors[],int delay)
{
this.balls=new Ball[colors.length];
for(int i=0,x=40;i<colors.length;i++,x+=40)
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);
}
public void paint(Graphics g)
{
for(int i=0;i<balls.length;i++)
{
g.setColor(balls[i].color);
balls[i].x=balls[i].left?balls[i].x-10:balls[i].x+10;
if(balls[i].x<=0||balls[i].x>=this.getWidth())
balls[i].left=!balls[i].left;
balls[i].y=balls[i].up?balls[i].y-10:balls[i].y+10;
if(balls[i].y<=0||balls[i].y>=this.getHeight())
balls[i].up=!balls[i].up;
g.fillOval(balls[i].x, balls[i].y,20,20);
}
}
public void actionPerformed(ActionEvent ev)
{
repaint();
}
public void focusGained(FocusEvent ev)
{
timer.stop();
}
public void focusLost(FocusEvent eV)
{
timer.restart();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值