[英]Java Applet Game Design : Keyboard focus
我將其發布在錯誤的位置( GameDev
),並且在此沒有任何回應。 所以我再次在這里發布。
我正在制作一個applet游戲,它正在渲染,正在運行游戲循環,正在更新動畫,但是鍵盤輸入無效。 這是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類。 當作為applet運行時,它不起作用,並且當我將Game類添加到框架中時,它可以正常工作。
謝謝
現在解決。 看我的解決方案
一種可能的解決方案是使用JApplet的contentPane,將焦點放在它上而不是JApplet本身。 但是我更喜歡使用鍵綁定。 您可能需要使用Swing計時器才能起作用:
我的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();
}
}
}
如果您在瀏覽器中運行,則可能需要單擊小程序以使其聚焦。 出於安全原因,大多數瀏覽器不允許小程序在用戶未單擊的情況下僅抓住鍵盤焦點。
因此,我將添加一個鼠標偵聽器,而不是直接在init()
中進行焦點捕獲:
addMouseListener(new MouseAdapter() {
public void onMousePress(MouseEvent e) {
requestFocus();
}
});
現在我有兩個選擇,
現在,我試圖GApplet
一門名為GApplet
的新課程。 它將游戲加載到可從applet運行的新JFrame中。 現在,我也可以從網絡訪問全屏模式。 這是該課程的鏈接。
現在它像Webstart一樣工作,實際上是一個applet。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.