具有焦点的KeyListener无法正常工作

具有焦点的KeyListener无法正常工作

我在代码中添加了一个关键侦听器,但是它没有响应。我不知道这个问题是否多余,但是关于类似问题的其他问题都说我应该专注于组件。但是,正如您在此处看到的那样,我已经尝试过这样做,但是它不起作用。我也正在运行一个线程来渲染我的游戏(非常糟糕),这可能是个问题,但是同样,我只是不知道。



private GamePanel() {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //get screen dimensions.

        myImage = new BufferedImage((int) screenSize.getWidth(), (int) screenSize.getHeight(), BufferedImage.TYPE_INT_RGB);
        myBuffer = myImage.getGraphics();
        Player p = new Player(400, 500);
        p.draw(myBuffer);
        abc = new Player(400, 500);
        this.addKeyListener(new Key());
        setFocusable(true);
        this.requestFocus();

    }
public void init() {
    JFrame frame = new JFrame("im bad at coding");
    frame.setLocation(0, 0);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(this);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setUndecorated(false);
    frame.setVisible(true);
    //ive tried to request focus and set focusable here, but no results
    new Thread(this).start();

}

最佳答案

我相信这可能是由于

A) Not initializing your Game object at all when creating the JFrame
B) Not properly embedding your key listener


尝试这个:

public static void main(String[] args) {
    GamePanel panel = new GamePanel(); //Call your init methods to initialize the panel only, not the jframe
    //Initialize the key listener object either implemented in the game panel itself, or initialized inside of the panel
    new Thread(panel).start();
    JFrame frame = new JFrame("im actually not that bad at coding");
    frame.setLocation(0, 0);
    frame.add(panel);
    frame.addKeyListener(panel.getKeyListener()); //Or addListener, i am doing this not on an IDE
    frame.setDefaultCloseOperation(JFrame.BLOW_UP_SYSTEM_ON_EXIT);
    //Optional, just click the frame: frame.setFocus(true);
    frame.pack();
    frame.setVisible(true);
}

关于java - 具有焦点的KeyListener无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49911072/

10-09 08:01