Problem with KeyListener
Hello!I have tried to get a JPanel implement the KeyListener interface but I can't get it to work. It does not indicate any keystrokes at all.
Below is the full code and my opinion is that I would get different output when I press, type or release a key. But nothing happens.
Any suggestions are welcome.
Best regards
Fredrik
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame
{
MyPanel myPanel = new MyPanel();
public Main()
{
super("KeyListener Tester");
setSize(300, 300);
getContentPane().add(myPanel);
show();
}
public static void main(String[] args)
{
new Main();
}
}
class MyPanel extends JPanel implements KeyListener
{
public MyPanel()
{
setBackground(Color.red);
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
System.out.println("keyPressed");
}
public void keyReleased(KeyEvent ke)
{
System.out.println("keyReleased");
}
public void keyTyped(KeyEvent ke)
{
System.out.println("keyTyped");
}
}
