0
class Panelz extends JPanel{
	public String test;
	Panelz(KeyListener ky){
		addKeyListener(ky);
		test = "Empty";
	}
	public void paint(Graphics g){
		g.drawString(test, 10, 10);
	}
}

public class Begh extends JFrame implements KeyListener{
	Panelz a = new Panelz(this);
	Begh(){
		super("Press");
		setLocationRelativeTo(null);
		add(a);
		setSize(500, 500);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		new Begh();

	}
	public void keyPressed(KeyEvent e) {
		a.test = "Pressed";
		a.repaint();
	}
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		a.test = "Released";
		a.repaint();
	}
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		a.test = "Typed";
		a.repaint();
	}

}

this is pretty simple but it doesn't work :(
what do I miss?

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by henks
0

In what way doesn't it work, exactly?
Maybe the panel doesn't have focus, so its not getting the key events - try adding the same listener to the jframe in Begh()

0

Yes it works if I add the listener to Begh :)

addKeyListener(this);

and the way I compare the event was wrong
should be this way :

if(e.getKeyChar()== 'a')

thanks...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.