fork download
  1. import java.awt.Color;
  2. import java.awt.event.KeyAdapter;
  3. import java.awt.event.KeyEvent;
  4.  
  5. import javax.swing.JFrame;
  6. import javax.swing.JPanel;
  7.  
  8.  
  9. public class ListenerExample {
  10.  
  11.  
  12. public static void main(String[] args) {
  13. JFrame frame = new JFrame("Example");
  14. JPanel panel = new JPanel();
  15. frame.getContentPane().add(panel);
  16. frame.setVisible(true);
  17. panel.setVisible(true);
  18. panel.setSize(300, 300);
  19. frame.setSize(300, 300);
  20. frame.addKeyListener(new KeyListener(panel));
  21.  
  22.  
  23. }
  24.  
  25. private static class KeyListener extends KeyAdapter{
  26. private JPanel panel;
  27.  
  28. public KeyListener(JPanel panel1) {
  29. panel = panel1;
  30. }
  31.  
  32. public void keyPressed(KeyEvent e) {
  33. char ch = e.getKeyChar();
  34. int code = e.getKeyCode();
  35. if (ch == 'a'){
  36. panel.setBackground(Color.red);
  37. }
  38. if (ch == 's'){
  39. panel.setBackground(Color.yellow);
  40. }
  41. if (ch == 'd'){
  42. panel.setBackground(Color.blue);
  43. }
  44. panel.repaint();
  45. }
  46. }
  47. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:9: error: class ListenerExample is public, should be declared in a file named ListenerExample.java
public class ListenerExample {
       ^
1 error
stdout
Standard output is empty