//实现键盘监听
public class my_keymove extends JFrame implements KeyListener{
MyPanel mp = null;
public static void main(String[] args) {
my_keymove mk = new my_keymove();
}
//构造函数
public my_keymove(){
mp = new MyPanel();
this.add(mp);
//给界面上绑定键盘监听
this.addKeyListener(this);
this.setSize(200,150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//当键盘被按下,code是指定内容时,坐标更改。
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y++;
}
if(e.getKeyCode()==KeyEvent.VK_UP){
y--;
}
if(e.getKeyCode()==KeyEvent.VK_LEFT){
x--;
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x++;
}
//重绘图形
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
int x = 10;
int y = 10;
//定义自己的panel,里面在x,y的位置画圆。
class MyPanel extends JPanel{
public void paint(Graphics g){
super.paint(g);
g.fillOval(x,y,20,20);
}
}
}
j2se使用KeyListener实现界面上的物体移动
最新推荐文章于 2024-07-25 19:04:54 发布