Page 1 of 2 12 LastLast
Results 1 to 20 of 23

Thread: key listeners

  1. #1
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default key listeners

    I am writing a program which needs keyboard events. I have tried googling, but none of the sites seem to be very clear. So how can I set up a key listener which will execute a block of code when a key is pressed?

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    One key question though is are you trying to capture keystrokes even if the application doesn't have focus, in other words a keylogger? If so, Java is not the tool for this job.

  4. #4
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    No I am not trying to create a keylistener.
    And thank for the link, but it gave no instructions on how to create a keylistener, and when I tried using relevant parts from the example code, I got an error.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    No I am not trying to create a keylistener.
    And thank for the link, but it gave no instructions on how to create a keylistener, and when I tried using relevant parts from the example code, I got an error.
    The links give all the general information on how to create key listeners and key bindings. My guess is that you're trying to use it wrong, but to be able to tell you more, we'd need to see your code. You would do well to give us a lot more information about your problem.
    Last edited by Fubarable; 11-18-2010 at 08:44 PM.

  6. #6
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Java Code:
     public class main implements KeyListener {
    typingArea = new JTextField(20);
    	typingArea.addKeyListener(this);
    Those two lines both yielded an error, asking me to create a class typing area.

    Java Code:
     public void keyTyped(KeyEvent e) {
    	System.out.println(e);
        }
    Also didnt work, although there was no error message

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    Java Code:
     public class main implements KeyListener {
    typingArea = new JTextField(20);
    	typingArea.addKeyListener(this);
    Those two lines both yielded an error, asking me to create a class typing area.
    No surprise: that's not viable Java code. This has nothing to do with Swing and all to do with proper Java. You're using a variable, typingArea before declaring it, and then you're trying to call methods on it outside of a method, constructor or similar block. You'll find tutorials on the basics of Java here: http://download.oracle.com/javase/tu...ybigindex.html

  8. #8
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Thanks for that, I am now not getting any errors. I have the following code:
    Java Code:
     public class ball {
    
    ...
    
    public ball (){
        ...
        JTextField typingArea = new JTextField(20);
            typingArea.addKeyListener(new KeyListener() {
    
                public void keyTyped(KeyEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }
    
                public void keyPressed(KeyEvent e) {
                    System.out.println(e);
                    //throw new UnsupportedOperationException("Not supported yet.");
                }
    
                public void keyReleased(KeyEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }
            });
    
        
    }
    I don't get any errors when I run, but nothing seems to happen when I press any keys

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I don't know why your code isn't working based on what you've posted, and you may need to create and post a minimal compilable runnable example (an SSCCE) that we can run, modify and correct to be able to help you. Please see the link.

    But more importantly, what functionality are you trying to give your program? KeyListener may not be the best fit depending on what you're trying to do.

  10. #10
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Java Code:
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    
    public class main {
    
        public static void main(String[] args) {
           JFrame win;
            Container contentPane;
            Graphics g;
    
            win = new JFrame("Clock");
            win.setSize(1200, 800);
            win.setLocation(0, 0);
            win.setVisible(true);
    
            contentPane = win.getContentPane();
            g = contentPane.getGraphics();
            
    
          JTextField typingArea = new JTextField(20);
            typingArea.addKeyListener(new KeyListener() {
    
                public void keyTyped(KeyEvent e) {
                    
                }
    
                public void keyPressed(KeyEvent e) {
                    System.out.println(e);
                    
                }
    
                public void keyReleased(KeyEvent e) {
                    
                }
            });
    
        }
    
    }
    The purpose of the key listeners is to use the arrow keys on the keyboard to move an object around the screen.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default

    1. Never never never use getGraphics() of a Component. Or at least not until you know as much about as Fubarable does (I don't, so I don't use it)

    2. A Component that isn't added to a hierarchy that's made visible doesn't receive events. Not keyboard events, not mouse events, not focus events, nada.

    db

  12. #12
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Ok, thanks for the advice
    Do you have any suggestions for what I should use instead?
    I have tried adding
    Java Code:
     contentPane.add(typingArea);
    on the 4th line from the bottom and still nothing happens.
    Last edited by zjames; 11-19-2010 at 05:32 PM.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    Ok, thanks for the advice
    Do you have any suggestions for what I should use instead?
    I have tried adding
    Java Code:
     contentPane.add(typingArea);
    on the 4th line from the bottom and still nothing happens.
    Use key bindings for this instead since they're a higher level construct, will work even if the component they are added to doesn't have the focus. The tutorials will show you how to use these.

    edit: for e.g., Checking for multiple keys pressed
    Last edited by Fubarable; 11-20-2010 at 12:14 PM.

  14. #14
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Thanks for that, it was very useful.
    Just one question:
    How do I create a javax.swing.Action?

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    Thanks for that, it was very useful.
    Just one question:
    How do I create a javax.swing.Action?
    An Action is an interface and in my experience when I've wanted an Action object I've usually extended the abstract class derived from this, AbstractAction. In fact my program in the link does just this.

  16. #16
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Ok, I've tried taking parts of that but really didn't understand what most of it did. I have already defined the method I want to be invoked when a key is pressed if that is any help.

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    Ok, I've tried taking parts of that but really didn't understand what most of it did. I have already defined the method I want to be invoked when a key is pressed if that is any help.
    Good for you, then you have a plan! ;)

    To better understand key bindings, you'll need to study the tutorials that have been linked above. If you don't understand what's in the tutorial, then please come on back and ask for clarification, and we'll be glad to help.

    Best of luck!

  18. #18
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Just to clarify:
    To create a javax.swing.Action do I create a separate class that extneds AbstractAction then override
    Java Code:
     public void actionPerformed(ActionEvent arg0)
    and put the code that I want to execute in that method?

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by zjames View Post
    Just to clarify:
    To create a javax.swing.Action do I create a separate class that extneds AbstractAction then override
    Java Code:
     public void actionPerformed(ActionEvent arg0)
    and put the code that I want to execute in that method?
    You could create a separate stand-alone class for this, yes, but if the code held in the class is small, then an alternative is to create a private inner class to call your method, or another way is to create an anonymous inner class, an object whose class has no name but is created "in-line" when needed. So assuming you have a method called, callMyMethod():

    Java Code:
       private void callMyMethod() {
          // TODO code that gets called on button push
          
       }


    A private inner class could look like so:
    Java Code:
       private class MyPrivateInnerClass extends AbstractAction {
    
          @Override
          public void actionPerformed(ActionEvent arg0) {
             callMyMethod();
          }
       }

    and then could be used like so:
    Java Code:
    myComponent.getActionMap().put("Some String that's used with InputMap", new MyPrivateInnerClass());


    Or to use an anonymous inner class with key binding:
    Java Code:
          myComponent.getActionMap().put("Some String that's used with InputMap", new AbstractAction() {
             public void actionPerformed(ActionEvent e) {
                callMyMethod();
             }
          });

    We often use anonymous inner classes when adding ActionListeners to JButtons:

    Java Code:
          JButton button = new JButton(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                callMyMethod();
             }
          });

  20. #20
    zjames is offline Member
    Join Date
    Nov 2010
    Posts
    20
    Rep Power
    0

    Default

    Am I correct in thinking that to make a key binding I need a component which I use getInputMap() and getActionMap() on?

Page 1 of 2 12 LastLast

Similar Threads

  1. Can't implement listeners
    By xael in forum New To Java
    Replies: 3
    Last Post: 09-02-2010, 06:33 PM
  2. Using weak referencing to gc listeners.
    By MartinR in forum New To Java
    Replies: 0
    Last Post: 05-29-2010, 11:37 PM
  3. Help with Listeners
    By Psyclone in forum AWT / Swing
    Replies: 8
    Last Post: 02-09-2010, 07:21 PM
  4. jTextField Listeners
    By user6123456 in forum AWT / Swing
    Replies: 6
    Last Post: 10-15-2009, 05:58 PM
  5. Seriously need help on my listeners!!
    By themburu in forum Java Applets
    Replies: 4
    Last Post: 05-26-2008, 10:41 AM

Posting Permissions

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