CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2008
    Posts
    49

    KeyListener wont work for me... please help.

    starting from the ground up on a project for university, but i need to start with a keyListener, which i just cant get to work...

    heres the demo i have put together of a key listener...

    i get the following error :

    "addKeyListener(java.awt.event.KeyListener) in java.awt.Component cannot be applied to ()..."

    Code:
    import java.awt.event.*;
    import javax.swing.*;
    
    public class keyListenerDemo implements KeyListener
    {
    
    	public static void main(String [] args)
    	{
    		javax.swing.SwingUtilities.invokeLater(new Runnable()
    		{
    			public void run()
    			{
    				createGUI();
    			}
    		});
    	}
    	
    	public static void createGUI()
    	{
    		JFrame frame = new JFrame("hello");
    			
    		frame.addKeyListener(this); //ERROR ON THIS LINE!
    		frame.setSize(700,700);
    		frame.setVisible(true);
    	}
        
        
        public void keyTyped(KeyEvent e)
        {
        	System.out.println("got here");
        }
        
        public void keyPressed(KeyEvent e)
        {
        	System.out.println("got here");
        }
        
        public void keyReleased(KeyEvent e)
        {
        	System.out.println("got here");
        }
        
    }
    i really need help with this... thanks in advance

  2. #2
    Join Date
    Feb 2008
    Posts
    966

    Re: KeyListener wont work for me... please help.

    I think the problem is that you are trying to add (this) to the action listener but an actual instance of "this" hasn't been created.

    Inside of run() try putting:

    keyListenerDemo kld = new keyListenerDemo();
    kld.createGUI();

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured