By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,201 Members | 920 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,201 IT Pros & Developers. It's quick & easy.

KeyListener is not working after the window has been moved

twitch3729
P: 1
Basicaly, I have a frame with only a Canvas on it and a KeyListener. For some reason the keyListener stops registering my keys as soon as I have moved the Window from its starting position. I have tried several solution but none have worked. Heres the code
Expand|Select|Wrap|Line Numbers
  1. public class Test extends Canvas implements KeyListener
  2. {
  3.  
  4.     static final int     WIDTH      =700;
  5.     static final int     HEIGHT     =700;
  6.     static final String  TITLE      ="HelloWorld";
  7.  
  8.  
  9.     public static void main(String[]args)
  10.     {
  11.         Test test = new Test();
  12.     }
  13.  
  14.     public test()
  15.     {
  16.         JFrame frame = new JFrame(TITLE);
  17.         JPanel panel = (JPanel)frame.getContentPane();
  18.         setBounds(0,0,WIDTH,HEIGHT);
  19.         panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
  20.         panel.setLayout(null);
  21.         panel.add(this);
  22.         frame.setBounds(0,0,WIDTH,HEIGHT);
  23.         setIgnoreRepaint(true);
  24.         frame.setResizable(false);
  25.         frame.pack();
  26.         frame.addWindowListener(new WindowAdapter(){
  27.             public void windowClosing(WindowEvent e){
  28.                 System.exit(0);
  29.             }
  30.         });
  31.         frame.addKeyListener(this);
  32.         frame.setVisible(true);
  33.         requestFocus();
  34.     }
  35.  
  36.     public void keyPressed(KeyEvent event){
  37.         System.out.println("KeyPressed");
  38.     }
  39.     public void keyTyped(KeyEvent event){
  40.         System.out.println("KeyTpyed");
  41.     }
  42.     public void keyReleased(KeyEvent event){
  43.         System.out.println("KeyReleased");
  44.  
  45.     }
  46. }
  47.  

I have used this code on both Linux(Ubuntu) and Vista with the same problem on both operating systems. Any help?
Mar 21 '08 #1
Share this Question
Share on Google+
1 Reply


Expert 10K+
P: 11,448
A Canvas is a 'heavy weight' AWT component, i.e. it leaves it to the underlying
system to draw itself. Swing components (such as JFrames, JPanels, everything
starting with a capital J) don't like that and get confused by such an AWT component.
Make your class extend from a JPanel and all will be fine.

kind regards,

Jos
Mar 21 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.