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?

Recommended Answers

All 2 Replies

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()

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...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.