Output letter with KeyListener in Java?
I want to display the pressed letter in a window using drawString. Unfortunately, I don't know how to display the information from e.getKeyChar() using drawString.
Here is the Java code:
public class Test extends JPanel implements KeyListener { String a; Random r = new Random(); int x = r.nextInt(6) + 1; int y = r.nextInt(6) + 1; Test() { addKeyListener(this); setFocusable(true); requestFocusInWindow(); } @Override public void keyPressed(KeyEvent e) { a = e.getKeyChar(); repaint(); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.blue); g.drawString(a, x, y); } @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} public static void main(String[] args) { JFrame m = new JFrame("Letters"); Test neu = new Test(); m.setContentPane(neu); m.setVisible(true); m.setSize(400, 400); m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
KeyEvent.getKeyChar() does not return a string, but a char.
You can make a string with String.valueOf().
You can also work with KeyEvent.getKeyCode() and .getKeyText(): you can also output “unprintable” keys like Shift. Try it out.
Thank you. I’m new to programming, so I didn’t know 🙂