gpt4 book ai didi

Java Applet 游戏设计 : Keyboard focus

转载 作者:行者123 更新时间:2023-11-29 08:04:34 26 4
gpt4 key购买 nike

我将其发布在错误的位置 (GameDev) 并且没有得到任何回应。所以我在这里再次发布它。

我正在制作一个小程序游戏,它正在渲染,游戏循环正在运行,动画正在更新,但键盘输入不起作用。这是一个 SSCCE。

public class Game extends JApplet implements Runnable {

public void init(){
// Initialize the game when called by browser
setFocusable(true);
requestFocus();
requestFocusInWindow(); // Always returning false
GInput.install(this); // Install the input manager for this class
new Thread(this).start();
}

public void run(){
startGameLoop();
}

}

这是 GInput 类。

public class GInput implements KeyListener {

public static void install(Component c){
new GInput(c);
}

public GInput(Component c){
c.addKeyListener(this);
}

public void keyPressed(KeyEvent e){
System.out.println("A key has been pressed");
}

......

}

这是我的 GInput 类。当作为小程序运行时,它不起作用,而当我将 Game 类添加到框架时,它可以正常工作。

谢谢

现在解决了。查看我的解决方案

最佳答案

一种可能的解决方案是使用 JApplet 的 contentPane,将焦点设置在它而不是 JApplet 本身上。但我更喜欢使用键绑定(bind)。您可能需要使用 Swing Timer 才能工作:

我的SSCCE:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;

import javax.swing.*;

@SuppressWarnings("serial")
public class AppletKeyListen extends JApplet {
@Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setFocusable(true);

int timerDelay = 100;
Timer myTimer = new Timer(timerDelay , new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
boolean focusObtained = requestFocusInWindow();
System.out.println("focusObtained for JApplet: " + focusObtained);

Container contentPane = getContentPane();
contentPane.setFocusable(true);

focusObtained = contentPane.requestFocusInWindow();
System.out.println("focusObtained for contentPane: " + focusObtained);


}
});
myTimer.setRepeats(false);
myTimer.start();
// boolean focusObtained = requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);
//
// Container contentPane = getContentPane();
// contentPane.setFocusable(true);
//
// focusObtained = contentPane.requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);

}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}

关于Java Applet 游戏设计 : Keyboard focus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122286/

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