使用java swing使用箭头键移动标签/图像图标

mbzjlibv  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(254)

每次按下箭头键时,我都试图移动playerBL对象。我一直在尝试使用 repaint() 方法与 keyPressed() 方法。我不确定是否缺少要实现的方法。是我的 LayeredPane 导致问题的原因是什么?任何帮助都将不胜感激。
这是我的代码:board.java

import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Board {

    int x = 20;
    int y = 500;
    final int width = 150;
    final int height = 150;

    // Initializes a window to open
    Board() {

        // Create a game window
        JFrame frame = new JFrame("Game");
        JLayeredPane layers = new JLayeredPane();

        // Create a layered pane to add images on top of each other
        layers.setBounds(0, 0, 1010, 760);

        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 1010, 760);
        frame.setLayout(null);
        frame.setVisible(true);

        // Create background image
        JLabel backgroundLbl = new JLabel();
        ImageIcon background = new ImageIcon("sampleImage.png");

        // Set the labels picture and size
        backgroundLbl.setIcon(background);
        backgroundLbl.setBounds(0, 0, 1010, 760);

        // Get the player image and resize
        ImageIcon playerImage = new ImageIcon(new ImageIcon("character.jpg").getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT));
        JLabel playerLbl = new JLabel();

        // Add picture to label and locate starting position
        playerLbl.setIcon(playerImage);
        playerLbl.setBounds(x, y, width, height);

        // Add player image and background to Layer Panel
        layers.add(backgroundLbl, Integer.valueOf(0));
        layers.add(playerLbl, Integer.valueOf(1));

        frame.add(layers);

        // Add KeyListener
        frame.addKeyListener(new KeyListener() {

            // Checks what key was pressed
            public void keyPressed(KeyEvent e) {

                // get the key pressed
                int key  = e.getKeyCode();

                // If arrow key is pressed, redraw the image to new coordinates?
                if (key == KeyEvent.VK_LEFT) {
                    playerLbl.repaint(x--, y, width, height);
                }
                else if (key == KeyEvent.VK_RIGHT) {
                    playerLbl.repaint(x++, y, width, height);
                }
                else if (key == KeyEvent.VK_UP) {
                    playerLbl.repaint(x, y++, width, height);
                }
            }

            public void keyReleased(KeyEvent e) {

            }

            public void keyTyped(KeyEvent e) {

            }
        });
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题