- package bbs.istak.org.tw;
- import java.awt.BorderLayout;
- import java.awt.EventQueue;
- import java.awt.Image;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.border.EmptyBorder;
- import javax.swing.JLabel;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- public class Main extends JFrame {
- private JPanel contentPane;
- private int x=100, y=100;
- private ImageIcon icon_1 = new ImageIcon(Main.class.getResource("crab.png"));
- private ImageIcon icon_2 = new ImageIcon(Main.class.getResource("crab2.png"));
- private ImageIcon icon_3 = new ImageIcon(Main.class.getResource("crab3.png"));
- private ImageIcon icon_4 = new ImageIcon(Main.class.getResource("crab4.png"));
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- Main frame = new Main();
- ImageIcon icon = new ImageIcon(Main.class.getResource("icon.png"));
- Image img = icon.getImage().getScaledInstance(45, 45, java.awt.Image.SCALE_FAST);
- frame.setIconImage(img);
- frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- public Main() {
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(100, 100, 483, 359);
- contentPane = new JPanel();
- contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
- setContentPane(contentPane);
- contentPane.setLayout(null);
-
- ImageIcon icon = new ImageIcon(Main.class.getResource("crab2.png"));
- Image img = icon.getImage().getScaledInstance(150, 150, java.awt.Image.SCALE_FAST);
- ImageIcon temp = new ImageIcon(img);
-
- JLabel lblNewLabel = new JLabel(temp);
- lblNewLabel.setBounds(94, 86, 169, 142);
- contentPane.add(lblNewLabel);
- addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if(e.getKeyCode() == KeyEvent.VK_UP){
- y-=5;
- lblNewLabel.setIcon(icon_1);
- }
- if(e.getKeyCode() == KeyEvent.VK_DOWN){
- y+=5;
- lblNewLabel.setIcon(icon_3);
- }
- if(e.getKeyCode() == KeyEvent.VK_LEFT){
- x-=5;
- lblNewLabel.setIcon(icon_4);
- }
-
- if(e.getKeyCode() == KeyEvent.VK_RIGHT){
- x+=5;
- lblNewLabel.setIcon(icon_2);
- }
- lblNewLabel.setLocation(x, y);
- }
- });
- }
- }
複製代碼 |