Shifting Focus Problem

Hello!!

Below is the code of an applet where i have mapped the directional keys to increase and decrease the circles and image position and play a sound clip.

The applet ran well but whenever i am adding any component like textbox,button or label the key events are not working.Th focus remains on the component and even if i try to disable the focus using setFocusable(false) it still doesn't work. How to make it work?

Code :

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class a extends Applet
implements KeyListener,FocusListener
{
int X=20,Y=30,xr=100,xy=100,r=70,r1=r,ix=200,iy=200,i;
Image image;
AudioClip audio;
String msg="key pressed";
//TextField t;
Button b;
public void init()
{

//requestFocusInWindow();
//setLayout(null);
addKeyListener(this);
//requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
image = getImage(getDocumentBase(), "image22.jpg");
audio = getAudioClip(getDocumentBase(), "chicken.au");
//t=new TextField();
//add(t);
//t.setBounds(500, 500, 100, 100);
b= new Button();
add(b);

b.setFocusable(false);

}



public void keyPressed(KeyEvent k)
{

showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
//showStatus("Move to Up");
//t.setFocusable(false);

audio.play();
msg = msg + "";
r=r+6;
iy++;
break;
case KeyEvent.VK_DOWN:
//showStatus("Move to Down");
//t.setFocusable(false);
audio.play();
msg += "";
r=r-6;
iy--;
break;
case KeyEvent.VK_RIGHT:
//showStatus("Move to Down");
//msg += "";
ix++;
break;
case KeyEvent.VK_LEFT:
//showStatus("Move to Down");
//msg += "";
ix--;
break;

}
repaint();
}
public void keyReleased(KeyEvent k)
{
//audio.stop();
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
//t.setFocusable(false);
}
public void paint(Graphics g)
{
//g.drawString(msg,X,Y);
// g.drawOval(xr-(r/2), xr-(r/2), r, r);
g.fillOval(xr-(r/2), xr-(r/2), r, r);
g.drawOval(xr-(r1/2+5), xr-(r1/2+5), r1+10, r1+10);
g.drawImage(image, ix, iy, this);


}

}

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories