赞
踩
写在前面(可能不同版本的包不同)
编写主类,设置窗口大小
public class W {
public static void main(String args[]){
Win win=new Win();
win.setSize(500,500);
}
}
添加监视对象(这里我用按钮),设定布局(空布局–简单粗暴)
import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class Win extends JFrame{ JButton a; Police police; Win(){ setLayout(null); police=new Police(); a=new JButton("请按方向键移动"); a.setBounds(150,60,160,20); a.addKeyListener(police); add(a); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
添加监视器反应动作
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; public class Police implements KeyListener{ public void keyPressed(KeyEvent e){ JButton b=(JButton)e.getSource(); if(e.getKeyCode()==e.VK_LEFT){ b.setBounds(b.getX()-10, b.getY(),160,20); } else if(e.getKeyCode()==e.VK_RIGHT){ b.setBounds(b.getX()+10,b.getY(),160,20); } else if(e.getKeyCode()==e.VK_UP){ b.setBounds(b.getX(),b.getY()-10,160,20); } else if(e.getKeyCode()==e.VK_DOWN){ b.setBounds(b.getX(),b.getY()+10,160,20); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。