本帖最後由 tonyh 於 2021-9-24 20:36 編輯
試完成如畫面所示之視窗程式,視窗中的鱷魚能向左向右自由行走。
pic.zip- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class Ch05 extends KeyAdapter{
- JFrame fm;
- ImageIcon bk, ic, l[]=new ImageIcon[10], r[]=new ImageIcon[10];
- JLabel lb, role;
- int x=150, step=0;
-
- Ch05()
- {
- for(int i=0; i<10; i++)
- {
- l[i]=new ImageIcon(Ch05.class.getResource("pic/l"+(i+1)+".png"));
- r[i]=new ImageIcon(Ch05.class.getResource("pic/r"+(i+1)+".png"));
- }
-
- role=new JLabel(r[step]);
- role.setBounds(x, 120, 117, 102);
-
- bk=new ImageIcon(Ch05.class.getResource("pic/bk.jpg"));
- ic=new ImageIcon(Ch05.class.getResource("pic/icon.png"));
- lb=new JLabel(bk);
- lb.setBounds(0, 0, 500, 300);
-
- fm=new JFrame("鱷魚走路");
- fm.setBounds(100, 100, 500, 320);
- fm.setIconImage(ic.getImage());
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.addKeyListener(this);
- fm.add(role);
- fm.add(lb);
- }
-
- @Override
- public void keyPressed(KeyEvent e) {
- step++;
- if(step==10)
- step=0;
- if(e.getKeyCode()==KeyEvent.VK_LEFT)
- {
- role.setIcon(l[step]);
- x-=8;
- }
- if(e.getKeyCode()==KeyEvent.VK_RIGHT)
- {
- role.setIcon(r[step]);
- x+=8;
- }
- role.setLocation(x, 120);
- }
- public static void main(String[] args) {
- new Ch05();
- }
- }
複製代碼 |