返回列表 發帖
  1. import javax.swing.JFrame;
  2. import javax.swing.JLabel;
  3. import javax.swing.ImageIcon;
  4. import java.awt.event.KeyListener;
  5. import java.awt.event.KeyEvent;

  6. public class Ch01 implements KeyListener {

  7.         private JFrame fm;
  8.         private ImageIcon icon1,icon2;
  9.         private JLabel lb;
  10.         private int x=100,y=100;
  11.         Ch01()
  12.         {
  13.                 icon1=new ImageIcon(Ch01.class.getResource("pic/icon.png"));
  14.                 icon2=new ImageIcon(Ch01.class.getResource("pic/baby.png"));

  15.                 lb=new JLabel(icon2);
  16.                 lb.setBounds(x, y, 128, 128);

  17.                 fm=new JFrame("按方向建移動圖形");
  18.                 fm.setIconImage(icon1.getImage());
  19.                 fm.setBounds(100, 100, 410, 320);
  20.                 fm.setVisible(true);
  21.                 fm.setResizable(false);
  22.                 fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.                 fm.setLayout(null);
  24.                 fm.addKeyListener(this);
  25.                 fm.add(lb);        
  26.         }

  27.         public void keyPressed(KeyEvent e)
  28.         {       if(e.isShiftDown()==true){
  29.                 if(e.getKeyCode()==KeyEvent.VK_UP)
  30.                         y-=5;
  31.                 if(e.getKeyCode()==KeyEvent.VK_DOWN)
  32.                         y+=5;
  33.                 if(e.getKeyCode()==KeyEvent.VK_LEFT)
  34.                         x-=5;
  35.                 if(e.getKeyCode()==KeyEvent.VK_RIGHT)
  36.                         x+=5;
  37.                 lb.setLocation(x, y);
  38.         }
  39.         else
  40.         {
  41.                 if(e.getKeyCode()==KeyEvent.VK_UP)
  42.                         y+=5;
  43.                 if(e.getKeyCode()==KeyEvent.VK_DOWN)
  44.                         y-=5;
  45.                 if(e.getKeyCode()==KeyEvent.VK_LEFT)
  46.                         x+=5;

  47.                 if(e.getKeyCode()==KeyEvent.VK_RIGHT)
  48.                         x-=5;
  49.                 lb.setLocation(x, y);
  50.         }
  51. }


  52. public static void main(String[] args) {
  53.         new Ch01();
  54. }

  55. @Override
  56. public void keyReleased(KeyEvent arg0) {
  57.         // TODO 自動產生的方法 Stub
  58.        
  59. }

  60. @Override
  61. public void keyTyped(KeyEvent arg0) {
  62.         // TODO 自動產生的方法 Stub
  63.        
  64. }
  65. }
複製代碼

TOP

返回列表