所以我试图让 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