- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.KeyListener;
- import java.awt.event.KeyEvent;
- public class Ch90 implements KeyListener {
- private JFrame fm;
- private ImageIcon icon1,icon2;
- private JLabel lb;
- private int x=100,y=100;
- Ch90()
- {
- icon1=new ImageIcon(Ch90.class.getResource("pic/icon.png"));
- icon2=new ImageIcon(Ch90.class.getResource("pic/baby.png"));
- lb=new JLabel(icon2);
- lb.setBounds(x, y, 128, 128);
- fm=new JFrame("按方向建移動圖形");
- fm.setIconImage(icon1.getImage());
- fm.setBounds(100, 100, 410, 320);
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.setLayout(null);
- fm.addKeyListener(this);
- fm.add(lb);
- }
- public void keyPressed(KeyEvent e)
- {
- if(e.isShiftDown()==true){
- 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);
- }
- 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 void keyReleased(KeyEvent e){}
- public void keyTyped(KeyEvent e){}
- public static void main(String[] args) {
- new Ch90();
- }
- }
複製代碼 |