本帖最後由 陳宥穎 於 2021-9-21 13:04 編輯
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class JPD04 implements KeyListener{
-
- JFrame j1;
- JLabel lb1;
- ImageIcon ic1,baby;
- int x=100,y=100;
- JPD04()
- {
- baby=new ImageIcon(JPD04.class.getResource("pic2/baby.png"));
- lb1=new JLabel();
- lb1.setBounds(100, 100, 234,351);
- lb1.setIcon(baby);
-
- ic1 =new ImageIcon(JPD04.class.getResource("pic2/icon.png"));
- j1=new JFrame("按方向鍵移動圖形");
- j1.setBounds(100, 100, 500, 400);
- j1.setVisible(true);
- j1.setLayout(null);
- j1.setResizable(false);
- j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- j1.addKeyListener(this);
- j1.setIconImage(ic1.getImage());
-
- j1.add(lb1);
- }
- public static void main(String[] args) {
- new JPD04();
- }
- @Override
- public void keyPressed(KeyEvent e) {
- 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;
- }
- lb1.setLocation(x,y);
-
- }
- @Override
- public void keyReleased(KeyEvent e) {
- // TODO 自動產生的方法 Stub
-
- }
- @Override
- public void keyTyped(KeyEvent e) {
- // TODO 自動產生的方法 Stub
-
- }
-
-
- }
複製代碼 |