- package tw.kuas.edu.tw;
- import java.awt.BorderLayout;
- import java.awt.EventQueue;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.border.EmptyBorder;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- public class BLOCK extends JFrame {
- private JPanel contentPane;
- private int x=64;
- private int y=64;
- /**
- * Launch the application.
- */
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- BLOCK frame = new BLOCK();
- frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * Create the frame.
- */
- public BLOCK() {
- setTitle("\u79FB\u52D5\u6A19\u7C64");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(100, 100, 450, 300);
- contentPane = new JPanel();
- contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
- setContentPane(contentPane);
- contentPane.setLayout(null);
- JLabel block = new JLabel("");
- block.setIcon(new ImageIcon("C:\\Users\\redab\\Downloads\\box.png"));
- block.setBounds(x, y, 48, 48);
- contentPane.add(block);
-
- block.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent arg0) {
- if(arg0.getKeyCode()==KeyEvent.VK_LEFT)
- x-=15;
- if(arg0.getKeyCode()==KeyEvent.VK_RIGHT)
- x+=15;
- if(arg0.getKeyCode()==KeyEvent.VK_UP)
- y-=15;
- if(arg0.getKeyCode()==KeyEvent.VK_DOWN)
- y+=15;
- block.setLocation(x, y);
- }
- });
-
- }
- }
複製代碼 |