I want the program to draw the key that is pressed on the screen. When I press a key, nothing happens.
Class where the draw code is:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab5;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class KeyDemoFrame extends JPanel implements KeyListener{
private JPanel window;
private String myString = "";
public KeyDemoFrame(){
window = new JPanel();
window.setSize(400,400);
window.setVisible(true);
addKeyListener(this);
}
public void keyPressed(KeyEvent event){
myString = String.format("Pressed %s", KeyEvent.getKeyText( event.getKeyCode()));
repaint();
}
public void keyReleased( KeyEvent event){
myString = String.format("Released %s", KeyEvent.getKeyText( event.getKeyCode()));
repaint();
}
public void keyTyped (KeyEvent event){
myString = String.format("Typed %s", KeyEvent.getKeyText( event.getKeyChar()));
repaint();
}
@Override
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.red);
g.drawString(myString,100,100);
}
}
and my main class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab5;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class KeyDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame window = new JFrame("A Window");
KeyDemoFrame keyDemoFrame = new KeyDemoFrame();
window.add(keyDemoFrame, BorderLayout.CENTER);
window.setSize(400,500);
window.setVisible(true);
}
}