gpt4 book ai didi

java - 无法使用箭头键移动 JLabel

转载 作者:行者123 更新时间:2023-11-30 08:29:51 25 4
gpt4 key购买 nike

因此,我试图让 JLabel(“玩家”)在我选择的方向上移动 10 像素,如下面的代码所示,但我无法让它工作。我已经运行它并按了一个箭头键,但没有任何反应,所以我希望你们能帮助我 ^^。

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

public class Main extends JFrame {

JLabel player = new JLabel();
JLabel separator = new JLabel();
JLabel object = new JLabel();

public Main() {

setSize(400, 500);
setLayout(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("BenTY");

separator.setOpaque(true);
separator.setBackground(Color.black);
separator.setBounds(0, 400, 400, 1);
add(separator);

player.setBackground(Color.black);
player.setOpaque(true);
player.setBounds(195, 390, 10, 10);
player.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_DOWN)
{
player.setBounds(player.getX(), player.getY()+10, 10, 10);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_UP)
{
player.setLocation(player.getX(), player.getY() - 10);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
player.setLocation(player.getX()-10,player.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
player.setLocation(player.getX()+10,player.getY());
repaint();
}
}
});
add(player);

Random random = new Random();
int oLocationX = random.nextInt(40) * 10;
int oLocationY = random.nextInt(40) * 10;
object.setBackground(Color.red);
object.setOpaque(true);
object.setBounds(oLocationX, oLocationY, 10, 10);
add(object);

}

public static void main(String[] args) {

Main ui = new Main();
ui.setVisible(true);

}

}

顺便说一句,很抱歉编码不好 :D

最佳答案

关于java - 无法使用箭头键移动 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19006833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com