java代码弹弹球_java学习日记-----------------------------弹弹球

import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.event.*;public class BallsCanvas extends Canvas implementsActionListener,FocusListener{privateBall balls[];private Timer timer;//定时器

private static classBall{intx,y;

Color color;booleanup,left;

Ball(int x,inty,Color color){this.x=x;this.y=y;this.color=color;

}

}public BallsCanvas(Color color[],int delay){//指定颜色,延时

this.balls=newBall[color.length];for(int i=0,x=40;i

balls[i]=newBall(x,x,color[i]);this.addFocusListener(this);

timer=new Timer(delay,this);

timer.start();//定时器启动

}public void setDelay(intdelay1){

timer.setDelay(delay1);

}public voidpaint(Graphics g){for(int i=0;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);

}

}

@Overridepublic voidfocusGained(FocusEvent e) {//TODO Auto-generated method stub

timer.stop();

}

@Overridepublic voidfocusLost(FocusEvent e) {//TODO Auto-generated method stub

timer.restart();

}

@Overridepublic voidactionPerformed(ActionEvent e) {//TODO Auto-generated method stub

repaint();

}

}class BallsJFrame extends JFrame implementsChangeListener{publicBallsCanvas ball;privateJSpinner spinner;publicBallsJFrame(){super("弹弹球");this.setBounds(300,200, 480, 360);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);

JPanel panel=newJPanel();this.getContentPane().add(panel,"South");

panel.add(new JLabel("Delay"));

spinner=newJSpinner();

spinner.setValue(100);

panel.add(spinner);

spinner.addChangeListener(this);this.setVisible(true);

}

@Overridepublic voidstateChanged(ChangeEvent e) {//TODO Auto-generated method stub

ball.setDelay(Integer.parseInt(""+spinner.getValue()));

}public static voidmain(String[] args) {newBallsJFrame();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值