Swing Timer 的使用案例

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. 1. [代码][Java]代码     跳至 [1]  [全屏预览]    
  2. import javax.swing.*;  
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import java.util.Random;  
  6.   
  7. public class BouncingBall extends JPanel implements ActionListener {  
  8.   
  9.     private static final int BALL_SIZE = 25, SPEED = 5;  
  10.       
  11.     private int xPos, yPos;  
  12.     private int xSpeed, ySpeed;  
  13.       
  14.     BouncingBall() {  
  15.         // determine a random position for the ball  
  16.         Random r = new Random();  
  17.         xPos = r.nextInt(300);  
  18.         yPos = r.nextInt(300);  
  19.         // determine speed direction  
  20.         xSpeed = SPEED;  
  21.         ySpeed = -SPEED;  
  22.         // a timer called every 1/10 second  
  23.         Timer timer = new Timer(100this);  
  24.         timer.start();  
  25.     }  
  26.     public void actionPerformed(ActionEvent e) {  
  27.         // get screen size  
  28.         int width = getWidth();  
  29.         int height = getHeight();  
  30.         // update positions  
  31.         xPos += xSpeed;  
  32.         yPos += ySpeed;  
  33.         // test if we go out the screen on the X axis  
  34.         if(xPos < 0) {  
  35.             xPos = 0;  
  36.             xSpeed = SPEED;  
  37.         }  
  38.         else if(xPos > width - BALL_SIZE) {  
  39.             xPos = width - BALL_SIZE;  
  40.             xSpeed = -SPEED;  
  41.         }  
  42.         // test if we go out the screen on the Y axis  
  43.         if(yPos < 0) {  
  44.             yPos = 0;  
  45.             ySpeed = SPEED;  
  46.         }  
  47.         else if(yPos > height - BALL_SIZE) {  
  48.             yPos = height - BALL_SIZE;  
  49.             ySpeed = -SPEED;  
  50.         }  
  51.         // ask to redraw the ball  
  52.         repaint();  
  53.     }  
  54.     // called by the Timer  
  55.     public void paintComponent(Graphics g) {  
  56.         super.paintComponent(g);  
  57.         g.fillOval(xPos, yPos, BALL_SIZE, BALL_SIZE);  
  58.     }  
  59.   
  60.     public static void main(String[] args) {  
  61.         // a JFrame to test the whole thing  
  62.         JFrame frame = new JFrame("Bouncing ball");  
  63.         frame.setSize(500500);  
  64.         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  65.         // add the bouncing panel to the JFrame  
  66.         frame.add(new BouncingBall());  
  67.         frame.setVisible(true);  
  68.     }  
  69. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值