Java之GUI鍵盤監聽事件KeyListener
阿新 • • 發佈:2019-02-09
例項:監聽鍵盤的上下左右鍵
/** * KeyListener:鍵盤監聽事件 * @author Administrator */ public class KeyListenerDemo { public static void main(String[] args) { // TODO Auto-generated method stub JFrame frame = new JFrame("視窗程式");//建立一個帶標題的視窗物件frame frame.setVisible(true);//顯示視窗 frame.setSize(600, 400);//設定視窗大小 frame.setLocationRelativeTo(null);//設定視窗居中 frame.setDefaultCloseOperation(3);//點選X關閉程式 3為結束程式 frame.setLayout(null);//清空佈局 Button button = new Button("按鈕"); button.setBounds(100,100,100,50); button.setBackground(Color.ORANGE); MyKeyListener myKeyListener = new MyKeyListener(button);//建立一個鍵盤監聽事件物件 frame.addKeyListener(myKeyListener);//新增myKeyListener鍵盤監聽事件 frame.add(button); } } class MyKeyListener implements KeyListener{ private Button button; public MyKeyListener(Button button) { super(); this.button = button; } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } //每按下一個任意鍵盤,此方法都會自動呼叫一次 @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub /* * 監聽鍵盤上下左右鍵,改變按鈕的座標 */ int keyCode = e.getKeyCode();//獲取所按鍵盤的鍵盤編碼 int x = button.getX();//獲取按鈕當前的橫座標值 int y = button.getY();//獲取按鈕當前的縱座標值 int width = button.getWidth();//獲取按鈕當前的寬 int height = button.getHeight();//獲取按鈕當前的高 if (keyCode == KeyEvent.VK_UP) { //KeyEvent.VK_UP上鍵編碼 button.setBounds(x, y-20, width, height); }else if (keyCode == KeyEvent.VK_DOWN) { //下鍵 button.setBounds(x, y+20, width, height); }else if (keyCode == KeyEvent.VK_LEFT) { //左鍵 button.setBounds(x-20, y, width, height); }else if (keyCode == KeyEvent.VK_RIGHT) { //右鍵 button.setBounds(x+20, y, width, height); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }