本帖最後由 黃茂勛 於 2018-5-26 11:21 編輯
- [code]package bbs.istak.org.tw;
- import java.awt.BorderLayout;
- import java.awt.EventQueue;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.border.EmptyBorder;
- import java.awt.Color;
- import javax.swing.border.LineBorder;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- public class Main extends JFrame {
- private JPanel contentPane;
- private JLabel lblNewLabel;
- /**
- * Launch the application.
- */
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- Main frame = new Main();
- frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * Create the frame.
- */
- public Main() {
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(100, 100, 495, 398);
- contentPane = new JPanel();
- contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
- setContentPane(contentPane);
- contentPane.setLayout(null);
-
- lblNewLabel = new JLabel("");
- lblNewLabel.setBounds(150, 75, 50, 50);
- lblNewLabel.setIcon(new ImageIcon(Main.class.getResource("/bbs/istak/org/tw/box.png")));
- contentPane.add(lblNewLabel);
- addKeyListener(new KeyAdapter() {
- @Override
- public void keyReleased(KeyEvent arg0) {
- int x=lblNewLabel.getLocation().x;
- int y=lblNewLabel.getLocation().y;
- RunPanel rp = new RunPanel(x,y,arg0.getKeyCode(),lblNewLabel);
- rp.start();
- }
- });
-
- }
- }
複製代碼- package bbs.istak.org.tw;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- public class RunPanel extends Thread{
-
- int x=0,y=0,keycode=0;
- JLabel lblNewLabel = null;
- RunPanel(int x, int y, int keycode, JLabel lblNewLabel)
- {
- this.x = x;
- this.y = y;
- this.keycode = keycode;
- this.lblNewLabel = lblNewLabel;
- }
- public void run()
- {
- switch(this.keycode)
- {
- case 38:
- y-=5;
- break;
- case 40:
- y+=5;
- break;
- case 37:
- x-=5;
- break;
- case 39:
- x+=5;
- break;
- default:
- break;
- }
- lblNewLabel.setLocation(this.x, this.y);
- }
- }
複製代碼 |