返回列表 發帖
本帖最後由 陳宥穎 於 2021-9-21 13:04 編輯
  1. import java.awt.event.KeyEvent;
  2. import java.awt.event.KeyListener;
  3. import javax.swing.ImageIcon;
  4. import javax.swing.JFrame;
  5. import javax.swing.JLabel;


  6. public class JPD04 implements KeyListener{
  7.       
  8.     JFrame j1;   
  9.     JLabel lb1;
  10.     ImageIcon ic1,baby;
  11.     int x=100,y=100;
  12.     JPD04()
  13.     {
  14.                 baby=new ImageIcon(JPD04.class.getResource("pic2/baby.png"));
  15.                 lb1=new JLabel();
  16.                 lb1.setBounds(100, 100, 234,351);
  17.                 lb1.setIcon(baby);
  18.                      
  19.                 ic1 =new ImageIcon(JPD04.class.getResource("pic2/icon.png"));                              
  20.             j1=new JFrame("按方向鍵移動圖形");         
  21.             j1.setBounds(100, 100, 500, 400);
  22.             j1.setVisible(true);
  23.             j1.setLayout(null);
  24.             j1.setResizable(false);
  25.             j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  26.             j1.addKeyListener(this);        
  27.             j1.setIconImage(ic1.getImage());
  28.                                 
  29.             j1.add(lb1);
  30.     }
  31.         public static void main(String[] args) {
  32.                 new JPD04();

  33.         }
  34.         @Override
  35.         public void keyPressed(KeyEvent e) {
  36.                 if(e.getKeyCode()==KeyEvent.VK_UP)
  37.                 {
  38.                         y-=5;
  39.                 }
  40.                 if(e.getKeyCode()==KeyEvent.VK_DOWN)
  41.                 {
  42.                         y+=5;
  43.                 }
  44.                 if(e.getKeyCode()==KeyEvent.VK_LEFT)
  45.                 {
  46.                         x-=5;
  47.                 }
  48.                 if(e.getKeyCode()==KeyEvent.VK_RIGHT)
  49.                 {
  50.                         x+=5;
  51.                 }
  52.                 lb1.setLocation(x,y);
  53.                
  54.         }
  55.         @Override
  56.         public void keyReleased(KeyEvent e) {
  57.                 // TODO 自動產生的方法 Stub
  58.                
  59.         }
  60.         @Override
  61.         public void keyTyped(KeyEvent e) {
  62.                 // TODO 自動產生的方法 Stub
  63.                
  64.         }

  65.       
  66.                
  67.         }
複製代碼

TOP

返回列表