gpt4 book ai didi

java - 键盘输入无法正常工作 KeyAdapter

转载 作者:行者123 更新时间:2023-12-01 23:38:18 26 4
gpt4 key购买 nike

我编写了一些应用程序并想向其中添加一些键盘输入。我的主类扩展了 JPanel,因此我可以将 keyAdapter 添加到构造函数中。keyAdapter 是一个名为“InputAdapter”的新类,它通过 keyPressed() 和 keyReleased() 方法扩展了 keyadapter。单击或释放时,控制台应打印一些字符串,例如这里“测试”

不知道为什么,控制台不会打印任何文本。另外,当我告诉它将 Sprite 可见性设置为 false 时,也没有任何反应。

所以我猜 KeyAdapter 无法正常工作,所以有人可以仔细查看我的代码行吗?

我想这个问题与我编写的其他实现的类无关,因为删除它们时,键盘输入不起作用的问题仍然存在。

包com.ochs.game;

public class Game extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;

public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static final int SCALE = 3;

public boolean isRunning;

public Game() {
addKeyListener(new InputAdapter());
setFocusable(true);
requestFocus();
start();
}

public void start() {
isRunning = true;
new Thread(this).start();
}

public void stop() {
isRunning = false;
}

public void run() {
init();
while(isRunning) {

update();
repaint();

try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Thread sleep failed.");
}
}
}

public void init() {

}

public void update() {

}

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;

}

public static void main(String[] args) {
Game gameComponent = new Game();
Dimension size = new Dimension(WIDTH*SCALE, HEIGHT*SCALE);

JFrame frame = new JFrame("Invaders");
frame.setVisible(true);
frame.setSize(size);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(gameComponent);
}
public class InputAdapter extends KeyAdapter {

@Override
public void keyPressed(KeyEvent arg0) {
System.out.println("Test");
}

@Override
public void keyReleased(KeyEvent arg0) {
System.out.println("Test");
}


}
}

最佳答案

你的代码对我有用:

java version "1.6.0_27"
OpenJDK Runtime Environment (IcedTea6 1.12.6) (6b27-1.12.6-1ubuntu0.12.04.2)
OpenJDK Client VM (build 20.0-b12, mixed mode, sharing)

提示1 - 我猜你应该重写paintComponent(Graphics g),而不是paint()

public void paintComponent(Graphics g){

super.paintComponent(g);
//...
}

提示 2 - 在 JPanel 上使用 addNotify():

public void addNotify(){

super.addNotify();
//start from here
new Thread(this).start();
}

提示 3 - 从 EDT 线程以这种方式启动您的应用(请参阅 What does SwingUtilities.invokeLater do?)

SwingUtilities.invokeLater(new Runnable() {

public void run(){

//your code

}
});

希望对你有帮助!

关于java - 键盘输入无法正常工作 KeyAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18322816/

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