- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class Ch91 implements KeyListener{
- JFrame fm;
- JLabel lb;
- int x=100,y=100;
- ImageIcon ic,pic1,pic2,pic3,pic4;
- Ch91()
- {
- ic=new ImageIcon(Ch91.class.getResource("pic/android.png"));
- pic1=new ImageIcon(Ch91.class.getResource("pic/1.png"));
- pic2=new ImageIcon(Ch91.class.getResource("pic/2.png"));
- pic3=new ImageIcon(Ch91.class.getResource("pic/3.png"));
- pic4=new ImageIcon(Ch91.class.getResource("pic/4.png"));
- lb=new JLabel(pic2);
- lb.setBounds(x, y, 128, 128);
- fm=new JFrame("螃蟹走路");
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.setBounds(100,100, 500, 500);
- fm.setIconImage(ic.getImage());
- fm.add(lb);
- fm.addKeyListener(this);
- }
- public static void main(String[] args)
- {
- new Ch91();
- }
- @Override
- public void keyPressed(KeyEvent e)
- {
- if(e.getKeyCode()==KeyEvent.VK_UP)
- {
- y-=5;
- lb.setIcon(pic1);
- lb.setLocation(x, y);
- }
- if(e.getKeyCode()==KeyEvent.VK_DOWN)
- {
- y+=5;
- lb.setIcon(pic4);
- lb.setLocation(x, y);
- }
- if(e.getKeyCode()==KeyEvent.VK_LEFT)
- {
- x-=5;
- lb.setIcon(pic3);
- lb.setLocation(x, y);
- }
- if(e.getKeyCode()==KeyEvent.VK_RIGHT)
- {
- x+=5;
- lb.setIcon(pic2);
- lb.setLocation(x, y);
- }
- }
- @Override
- public void keyReleased(KeyEvent e) {}
- @Override
- public void keyTyped(KeyEvent e) {}
- }
複製代碼 |