gpt4 book ai didi

java - 具有焦点的 KeyListener 不起作用

转载 作者:行者123 更新时间:2023-12-02 11:21:13 25 4
gpt4 key购买 nike

我正在向我的代码添加一个关键监听器,但它没有响应。我不知道这个问题是否多余,但有关类似问题的其他问题都说我应该关注该组件。然而,正如你在这里看到的,我已经尝试这样做,但没有成功。我还运行了一个线程来渲染我的(非常糟糕的)游戏,这可能是一个问题,但同样,我只是不知道。

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/

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