日期:2014-05-20 浏览次数:20651 次
package person.move; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.*; public class KeyListener1 extends JFrame implements ActionListener { public JButton b1=new JButton("确定"); public int x; public int y; public JPanel jpanel=new JPanel(); public JFrame frame = new JFrame("键盘响应"); public void _int() { this.x=110; this.y=180; frame.setLocation(300, 300); frame.setSize(300, 300); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setContentPane(jpanel); jpanel.setBackground(Color.GREEN); jpanel.setLayout(null); jpanel.add(b1); b1.setBounds(this.x, this.y, 80, 25); b1.addActionListener(this); //addMouseListener(new Move().m); jpanel.setFocusable(true); jpanel.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ if(e.getKeyCode()==KeyEvent.VK_RIGHT) b1.setBounds(++x, y, 80, 25); if(e.getKeyCode()==KeyEvent.VK_LEFT) b1.setBounds(--x,y, 80, 25); if(e.getKeyCode()==KeyEvent.VK_UP) b1.setBounds(x,--y, 80, 25); if(e.getKeyCode()==KeyEvent.VK_DOWN) b1.setBounds(x,++y, 80, 25); } }); } public static void main(String[] args){ KeyListener1 move=new KeyListener1(); move._int(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }