How easy is it to implement KeyListener?

public class MyPanel extends JPanel implements KeyListener { private char c = 'e'; public MyPanel() { this.setPreferredSize(new Dimension(500,500)); addKeyListener(this); } public void paintComponent(Graphics g) { super.repaint(); g.drawString("the key that pressed is" + c, 250,250); } public void keyPressed(KeyEvent e) { c=e.getKeyChar(); repaint(); } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { c=e.getKeyChar(); repaint(); } public static void main(String[] s) { JFrame f=new JFrame(); f.getContentPane().add(new MyPanel()); f.pack(); f.setVisible(true); } } 

I tried reading this one but couldn't figure out how easy it is to implement KeyListener. so what do i need to change for this?

+6
source share
1 answer

This is why this does not work:

  • JPanel does not have keyboard focus. (The frame has it.) You probably want requestFocus when the panel is added to the screen.

  • You need to call repaint when the image needs to change.

  • You should not call repaint in the paintComponent method.

  • You need to clear the drawing area before drawing the line again (otherwise all characters will be located one above the other).

Here is a complete working example:

 class MyPanel extends JPanel implements KeyListener { private char c = 'e'; public MyPanel() { this.setPreferredSize(new Dimension(500, 500)); addKeyListener(this); } public void addNotify() { super.addNotify(); requestFocus(); } public void paintComponent(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); g.drawString("the key that pressed is " + c, 250, 250); } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { c = e.getKeyChar(); repaint(); } public static void main(String[] s) { JFrame f = new JFrame(); f.getContentPane().add(new MyPanel()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } } 

Oh, and you can add f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) so that the application terminates when the window f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

+9
source

Source: https://habr.com/ru/post/908738/


All Articles