返回列表 發帖

鍵盤事件 (二)

本帖最後由 tonyh 於 2019-4-27 13:48 編輯

承上個主題,判斷 Shift 鍵是否被按住,使執行時若搭配 Shift 鍵,則上下左右鍵所造成的方向會顛倒。

  1. import javax.swing.JFrame;
  2. import javax.swing.JLabel;
  3. import javax.swing.ImageIcon;
  4. import java.awt.event.KeyAdapter;
  5. import java.awt.event.KeyEvent;
  6. public class Ch90 extends KeyAdapter{

  7.         JFrame fm;
  8.         JLabel lb;
  9.         ImageIcon ii,ic;
  10.         int x=200, y=100;
  11.        
  12.         Ch90()
  13.         {
  14.                 ic=new ImageIcon(Ch90.class.getResource("pic/icon.png"));
  15.                 ii=new ImageIcon(Ch90.class.getResource("pic/baby.png"));
  16.                
  17.                 lb=new JLabel(ii);
  18.                 lb.setBounds(x, y, 128, 128);
  19.                
  20.                 fm=new JFrame("鍵盤事件");
  21.                 fm.setIconImage(ic.getImage());
  22.                 fm.setBounds(100, 100, 500, 350);
  23.                 fm.setVisible(true);
  24.                 fm.setResizable(true);
  25.                 fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  26.                 fm.setLayout(null);
  27.                 fm.add(lb);
  28.                 fm.addKeyListener(this);
  29.         }
  30.        
  31.         public void keyPressed(KeyEvent e)
  32.         {
  33.                 if(e.isShiftDown()==false)
  34.                 {
  35.                         if(e.getKeyCode()==KeyEvent.VK_UP)
  36.                                 y-=5;
  37.                         if(e.getKeyCode()==KeyEvent.VK_DOWN)
  38.                                 y+=5;
  39.                         if(e.getKeyCode()==KeyEvent.VK_LEFT)
  40.                                 x-=5;
  41.                         if(e.getKeyCode()==KeyEvent.VK_RIGHT)
  42.                                 x+=5;
  43.                 }else
  44.                 {
  45.                         if(e.getKeyCode()==KeyEvent.VK_UP)
  46.                                 y+=5;
  47.                         if(e.getKeyCode()==KeyEvent.VK_DOWN)
  48.                                 y-=5;
  49.                         if(e.getKeyCode()==KeyEvent.VK_LEFT)
  50.                                 x+=5;
  51.                         if(e.getKeyCode()==KeyEvent.VK_RIGHT)
  52.                                 x-=5;
  53.                 }
  54.                 lb.setLocation(x, y);
  55.         }
  56.        
  57.         public static void main(String[] args) {
  58.                 new Ch90();
  59.         }

  60. }
複製代碼

返回列表