所以我试图让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);
}
}
BTW抱歉编码不好:D
答案 0 :(得分:3)
您需要使用KeyBindings代替low_level KeyListener
播放器(确保所有JComponents) need to be setFocusable() for KeyListener,否则KeyListener
不起作用,需要在组件树中使用焦点