码迷,mamicode.com
首页 > 编程语言 > 详细

用java实现小球撞墙

时间:2015-01-27 21:50:27      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
技术分享
技术分享技术分享import javax.swing.JFrame;

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Graphics;
public class MyBall extends JFrame{
  ballPanel bp;
  public MyBall(){
    bp=new ballPanel();
    Thread t=new Thread(bp);
    t.start();

    bp .addKeyListener(bp);
    this.addKeyListener(bp);
    this.add(bp);
    this.setSize(400,500);
    // this.setBackground(new Color(50,200,120));
    // this.setLocationRelativeTo(null);
    this.setLocation(300,100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public static void main(String[] args){
    MyBall my=new MyBall();
    my.setVisible(true);
  }

}
class ballPanel extends JPanel implements Runnable,KeyListener{
  private int x=50;
  private int y=50;
  int flag=0;
  public ballPanel(){
    this.setBackground(new Color(50,200,120));
  }
  public void paint(Graphics g){
    super.paint(g);
    g.fillOval(x, y,30,30);
  }
  public void keyPressed(KeyEvent e){
    if(e.getKeyCode()==37){
    x--;
  }
  if(e.getKeyCode()==38){
    y--;
  }
  if(e.getKeyCode()==39){
    x++;
  }
  if(e.getKeyCode()==40){
    y++;
  }
//   System.out.println(e.getKeyChar());
  this.repaint();
  }
  public void keyReleased(KeyEvent e){

  }
  public void keyTyped(KeyEvent e){

  }
  public void run(){
    while(true){
      if(flag==0){
      x++;
      y++;
      }
      if(flag==1){
        x--;
        y++;
      }
      if(flag==2){
        x--;
        y--;
      }
       if(flag==3){
        x++;
        y--;
      }
      if(x>340){
        if(flag==0){
          flag=1;
        }else{
          flag=2;
        }
      }
      if(y>430){
        if(flag==1){
          flag=2;
        }else{
          flag=3;
        }
      }
      if(x<0){
        if(flag==2){
          flag=3;
        }else{
          flag=0;
        }
      }
      if(y<0){
        if(flag==3){
          flag=0;
        }else{
          flag=1;
        }
      }
      try{
        Thread.sleep(5);
      }catch(Exception e){

      }
      this.repaint();
    }
  }
}

用java实现小球撞墙

标签:

原文地址:http://www.cnblogs.com/YP-W-Ricardo/p/4254032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!