返回列表 發帖
  1. package tw.kuas.edu.tw;

  2. import java.awt.BorderLayout;
  3. import java.awt.EventQueue;

  4. import javax.swing.JFrame;
  5. import javax.swing.JPanel;
  6. import javax.swing.border.EmptyBorder;
  7. import javax.swing.JLabel;
  8. import javax.swing.ImageIcon;
  9. import java.awt.event.KeyAdapter;
  10. import java.awt.event.KeyEvent;

  11. public class BLOCK extends JFrame {

  12.         private JPanel contentPane;
  13.         private int x=64;
  14.         private int y=64;

  15.         /**
  16.          * Launch the application.
  17.          */
  18.         public static void main(String[] args) {
  19.                 EventQueue.invokeLater(new Runnable() {
  20.                         public void run() {
  21.                                 try {
  22.                                         BLOCK frame = new BLOCK();
  23.                                         frame.setVisible(true);
  24.                                 } catch (Exception e) {
  25.                                         e.printStackTrace();
  26.                                 }
  27.                         }
  28.                 });
  29.         }

  30.         /**
  31.          * Create the frame.
  32.          */
  33.         public BLOCK() {
  34.                 setTitle("\u79FB\u52D5\u6A19\u7C64");
  35.                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  36.                 setBounds(100, 100, 450, 300);
  37.                 contentPane = new JPanel();
  38.                 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  39.                 setContentPane(contentPane);
  40.                 contentPane.setLayout(null);
  41.                 JLabel block = new JLabel("");
  42.                 block.setIcon(new ImageIcon("C:\\Users\\redab\\Downloads\\box.png"));
  43.                 block.setBounds(x, y, 48, 48);
  44.                 contentPane.add(block);
  45.                
  46.                 block.addKeyListener(new KeyAdapter() {
  47.                         @Override
  48.                         public void keyPressed(KeyEvent arg0) {                               
  49.                                 if(arg0.getKeyCode()==KeyEvent.VK_LEFT)
  50.                                         x-=15;
  51.                                 if(arg0.getKeyCode()==KeyEvent.VK_RIGHT)
  52.                                         x+=15;
  53.                                 if(arg0.getKeyCode()==KeyEvent.VK_UP)
  54.                                         y-=15;
  55.                                 if(arg0.getKeyCode()==KeyEvent.VK_DOWN)
  56.                                         y+=15;
  57.                                 block.setLocation(x, y);
  58.                         }
  59.                 });
  60.                
  61.         }
  62. }
複製代碼

TOP

返回列表