/*
*通过KeyListener接口来监听,通过repaint()来重画,最终实现由方向键来控制球的上下左右的移动
![通过方向键控制球的移动(练习5) - lishirong - The CTO of LiShirong 通过方向键控制球的移动(练习5) - lishirong - The CTO of LiShirong](http://img.ph.126.net/t9tZGiUSnR7C4V55lT5TIg==/2825164341261673327.jpg)
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ContralBall extends JFrame{
ContralBall(){
this.setSize(300,400);
int width=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int height=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
this.setLocation((width-300)/2,(height-400)/2);
this.setUndecorated(true);//去掉边框的作用,实现JWindow的效果
this.setVisible(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
public static void main(String args[]){
ContralBall cb=new ContralBall();
MyMovingBall mmb=new MyMovingBall();
mmb.setBackground(Color.orange);
cb.add(mmb);
cb.addKeyListener(mmb);
mmb.addKeyListener(mmb);
cb.show();
}
}
class MyMovingBall extends Panel implements KeyListener{
int x=140;
int y=200;
public void paint(Graphics g){
g.setColor(Color.green);
g.fillOval(x,y,20,20);
}
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==37)x--;
if(arg0.getKeyCode()==38)y--;
if(arg0.getKeyCode()==39)x++;
if(arg0.getKeyCode()==40)y++;
repaint();
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}