I am making a two player game applet. Both players need to control their discs to keep the ball from colliding with the wall. One player controls his disc with mouse motion and other controls with Keyboard up and down. The problem is the second player can’t control his disc because keyboard keys doesn’t remain in focus because of MouseMotionListener. I don’t know how to solve this problem. Here is the code:
public void init()
{
handle = new HandlerClass();
addMouseMotionListener(handle);
addKeyListener(handle);
}
private class HandlerClass implements MouseMotionListener,KeyListener
{
public void mouseMoved(MouseEvent event)
{
MouseY=event.getY();
if(MouseY<=0)
MouseY=0;
else
if(MouseY>=getHeight()-radius*2-1)
MouseY=getHeight()-radius*2-1;
}
public void keyPressed(KeyEvent event)
{
switch(event.getKeyCode())
{
case KeyEvent.VK_UP:
if(keyboardY<=0)
{
keyboardY=0;
}
keyboardY=keyboardY+1;
break;
case KeyEvent.VK_DOWN:
System.out.println("down key pressed");
if(keyboardY>=getHeight()-radius*2-1)
{
keyboardY=getHeight()-radius*2-1;
}
keyboardY-=1;
break;
}
}
EDIT:
I solve the problem of losing focus for keyboard by adding setFocusable(true); but now the game flickers as hell. I can’t what is going on in the game.
Regards
Use Key Bindings over
KeyListener, it provides the ability to specify different focus contexts.In regard to you second question, it sounds like you’re painting directly onto a top level container. I’d post a separate question with example code.