Problem with KeyListener...
I want to create a small games, which requires continuous game loop for drawing game on screen. But I want to detect user key actions. Combined key actions like left + right arrow.
I tried the following code..
package com.main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import com.helper.Logger;
import com.helper.ThreadUtilities;
publicclass MenuScreenimplements KeyListener{
private GameWindow window =null;
public MenuScreen(GameWindow w)
{
this.window = w;
}
publicvoid init()
{
window.getWindow().setBackground(GameConstants.GAME_BG);
window.getFrame().addKeyListener(this);
Logger.log("Menu init()");
}
publicvoid dispose()
{
Logger.log("Menu Screen Dispose");
window.getFrame().removeKeyListener(this);
}
publicvoid runLoop()
{
while(true)
{
ThreadUtilities.safeThreadSleep(500);
}
}
publicvoid keyTyped(KeyEvent ke){
}
publicvoid keyPressed(KeyEvent ke){
Logger.log("KeyPressed:" + ke.getKeyCode());
}
publicvoid keyReleased(KeyEvent ke){
}
}
I have one Window (java.awt.Window) in full screen exclusive mode. This window object is passed to various game screens like Game Menu, Game Play etc., so the respective classes draw on this window.
The runLoop will be filled with any animation required. Now the problem is Key Listeners doesn't work ! Where am I missing out ?
# 4
I have given the relevant code. Any how the remaining code...
package com.main;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.helper.Logger;
public class GameWindow {
private Window window = null;
private JFrame frame = null;
public Window getWindow()
{
return window;
}
public JFrame getFrame()
{
return frame;
//Frame
}
public GameWindow(boolean fullScreen,int w,int h)
{
frame = new JFrame();
window = new Window(frame);
Logger.log("Game Window construct begin");
if(fullScreen)
{
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if(gd.isFullScreenSupported())
{
Logger.log("Full Screen ok !");
gd.setFullScreenWindow(window);
}
else
{
Logger.log("Full Screen failed !");
window.setSize(new Dimension(w,h));
}
}
else
{
Logger.log("Dimension Set");
window.setSize(new Dimension(w,h));
}
window.setFocusable(true);
window.setFocusableWindowState(true);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
window.setVisible(true);
}
});
}
public GameWindow()
{
this(true,800,600);
}
}
Even mouse action listener isn't working....
Message was edited by:
chaos_begins_here
# 7
setGlobalFocusedWindow(Window focusedWindow)
setGlobalActiveWindow(Window activeWindow)
Guess these 2 functions will help me.. Will try them and let u know.
@tjacobs01 : I do go to class once in a while ; )
@camickr : Isn't Key binding is supposed for Components? I need to focus a window, which is a Container?!