承上個主題,判斷 Shift 鍵是否被按住,使執行時若搭配 Shift 鍵,則上下左右鍵所造成的方向會顛倒。
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- public class Ch90 extends KeyAdapter{
- JFrame fm;
- JLabel lb;
- ImageIcon ii,ic;
- int x=200, y=100;
-
- Ch90()
- {
- ic=new ImageIcon(Ch90.class.getResource("pic/icon.png"));
- ii=new ImageIcon(Ch90.class.getResource("pic/baby.png"));
-
- lb=new JLabel(ii);
- lb.setBounds(x, y, 128, 128);
-
- fm=new JFrame("鍵盤事件");
- fm.setIconImage(ic.getImage());
- fm.setBounds(100, 100, 500, 350);
- fm.setVisible(true);
- fm.setResizable(true);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.setLayout(null);
- fm.add(lb);
- fm.addKeyListener(this);
- }
-
- public void keyPressed(KeyEvent e)
- {
- if(e.isShiftDown()==false)
- {
- if(e.getKeyCode()==KeyEvent.VK_UP)
- y-=5;
- if(e.getKeyCode()==KeyEvent.VK_DOWN)
- y+=5;
- if(e.getKeyCode()==KeyEvent.VK_LEFT)
- x-=5;
- if(e.getKeyCode()==KeyEvent.VK_RIGHT)
- x+=5;
- }else
- {
- if(e.getKeyCode()==KeyEvent.VK_UP)
- y+=5;
- if(e.getKeyCode()==KeyEvent.VK_DOWN)
- y-=5;
- if(e.getKeyCode()==KeyEvent.VK_LEFT)
- x+=5;
- if(e.getKeyCode()==KeyEvent.VK_RIGHT)
- x-=5;
- }
- lb.setLocation(x, y);
- }
-
- public static void main(String[] args) {
- new Ch90();
- }
- }
複製代碼 |