首页 > 代码库 > 用java实现小球撞墙

用java实现小球撞墙

技术分享
技术分享
技术分享技术分享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实现小球撞墙