Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default Unable to capture key pressed :((

    Hi,
    I was learning about capturing key presses via the web and I added it to one of my existing Test classes... the problem is it just does not work :(
    I have added color to the parts I think are important.

    My code:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import java.awt.GridBagLayout;
    import javax.swing.JLabel;
    import java.awt.GridBagConstraints;
    import javax.swing.JButton;
    import java.awt.Insets;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Date;
    
    import javax.swing.JRadioButton;
    
    
    public class Test extends JFrame implements Runnable,[COLOR="Red"]KeyListener [/COLOR]{
    
    	private JPanel contentPane;
    
    	/**
    	 * Launch the application.
    	 */
    	/*
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Test frame = new Test();
    					frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	} */
    
    	/**
    	 * Create the frame.
    	 */
    	public Test() {
    
    		
    		
    		
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    	[COLOR="Red"]	contentPane.addKeyListener(this);[/COLOR]
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		GridBagLayout gbl_contentPane = new GridBagLayout();
    		gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0};
    		gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
    		gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
    		gbl_contentPane.rowWeights = new double[]{0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
    		contentPane.setLayout(gbl_contentPane);
    	[COLOR="Red"]//addKeyListener( this );[/COLOR]
    		radio1 = new JRadioButton("Radio 1");
    		GridBagConstraints gbc_radio1 = new GridBagConstraints();
    		gbc_radio1.fill = GridBagConstraints.BOTH;
    		gbc_radio1.insets = new Insets(0, 0, 5, 5);
    		gbc_radio1.gridx = 1;
    		gbc_radio1.gridy = 1;
    		contentPane.add(radio1, gbc_radio1);
    		if(getRadioValue()==1){System.out.println("a");}else{System.out.println("b");}
    		JButton btnNewButton = new JButton("New button");
    		btnNewButton.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    				but1ActionPerformed(arg0);
    			}
    		});
    		
    		label1 = new JLabel("New label");
    		GridBagConstraints gbc_label1 = new GridBagConstraints();
    		gbc_label1.insets = new Insets(0, 0, 5, 0);
    		gbc_label1.gridx = 3;
    		gbc_label1.gridy = 4;
    		contentPane.add(label1, gbc_label1);
    		GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
    		gbc_btnNewButton.insets = new Insets(0, 0, 0, 5);
    		gbc_btnNewButton.gridx = 1;
    		gbc_btnNewButton.gridy = 6;
    		contentPane.add(btnNewButton, gbc_btnNewButton);
    	}
    [COLOR="Red"]
    	public void keyPressed( KeyEvent e )
    	 {
    		System.out.println("a "+e.getKeyText(e.getKeyCode()));
    	}
    	
    	 public void keyReleased( KeyEvent e )
    	 {
    		 System.out.println("b "+e.getKeyText(e.getKeyCode()));
    
     }
    	
    	 public void keyTyped( KeyEvent e )
    	 {
    		 System.out.println("b "+e.getKeyText(e.getKeyCode()));
    	 }[/COLOR]
    	 
    	 private javax.swing.JLabel label1;
    	 private JRadioButton radio1;
    	 
    	 private int getRadioValue() {
    		 boolean b;
    		 b = 	radio1.isSelected();
    		 
    		   if(b==true)
    	            return 1;
    	        else
    	            return 2;
    		}
    	 
    	 Thread runner;
    	 public void start()
    	    {while(runner==null){runner=new Thread(this);runner.start();}}
    
    	 
    	    public void run()
    	    {int i=0;
    	       while (true)
    	       {
    	           System.out.println(""+i);
    	           updateCounter();
    	           //label1.setText(""+i);
    	           try {Thread.sleep(1000);}
    	           catch(InterruptedException e){};
    	           i++;
    	       }
    	    }
    	    int iii=0;
    	    public void updateCounter(){
    	    	
    	    	label1.setText(""+iii);
    	    	iii++;
    	    }
    
    		private void but1ActionPerformed(ActionEvent arg0) {
    			//label1.setText("a");	
    			iii=0;
    		}
    }
    Last edited by N00Bie; 02-19-2011 at 04:54 AM.

  2. #2
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    In the end I want to capture the keyboard input of the numbers 1 to 7, but right now the first step is to make it damn give me a system.out.println() for every key pressed or release and I cant get that :((

    Where did I screwup?

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

    Default

    Where did I screwup?
    For one, please edit your first post and change your "quote" tags to "code" tags so we can read the code.

  4. #4
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Done :))...

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

    Default

    To use a KeyListener, the component doing the listening must have the focus. You've added your listener to the contentPane which likely does not have focus. What is the goal of your key listening anyway? What are you trying to achieve with this?

  6. #6
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    I'm still very much in the path of learning/(refreshing my knowledge) of Java.
    So instead of just doing the examples in the tutorials I am also making a side project for myself where I can practice what i have learned because I belive the best way of learning is to create something.

    So I have created a little game (I play the guitar) where a music note is displayed on the screen and I have to click one of 7 buttons to say which note it is. This works perfectly.
    But moving the mouse fast enough sometimes is a problem (I have a thread running with a timer that gives me only 2 seconds to click the right button before the music note changes) so once I run the program I want to be able to use the number pad as well.

    Sorry for the long explanation.

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

    Default

    Sorry for the long explanation.
    That's quite alright as it gives us some useful information on your problem. You may wish to explore using key bindings instead of a key listener, and you can find more about it here: how to use key bindings

    It may seem more daunting at first, but it has power and flexibility including being usable even if the component doing the binding doesn't have focus.

  8. #8
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Ok, will check it out... will write back if I run into a wall ;)

    Here's a pic of my little app so far:

    (Click to expand)

    And the Test class which I posted here is exactly that, a test class. Once things are working in the test class I make the changes in the other program that way I wont screw up something thats already working and spend time searching and undoing stuff.

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

    Default

    Also: If you don't mind using alt-key combinations, you could simply set the JButton's mnemonic to be alt-your number.

  10. #10
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    That key bindings thing is pretty long with no quick examples :(
    I did find this though:

    adding this
    tt.requestFocusInWindow();
    under my

    Test tt = new Test();
    tt.setVisible(true);
    seems to work for the most part but is also giving me some other output...

    For keyReleased() it gives me:
    Unknown keyCode: 0x0

  11. #11
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Also: If you don't mind using alt-key combinations, you could simply set the JButton's mnemonic to be alt-your number.
    AH!
    Thats a very good idea, will try that as well!

  12. #12
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Ok, just tried the "mnemonic " way.
    It works good (I don't mind the ALT) but when I try using the number pad... no joy :(

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

    Default

    Hm, let's see your code. I unfortunately don't have a number pad on my computer, but this worked for my laptop:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Test2 extends JPanel {
       public static final String[] BUTTON_STRINGS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
       private static final int GAP = 10;
       private static final Dimension APP_SIZE = new Dimension(1000, 300);
       
       public Test2() {
          JPanel btnPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
          int count = 1;
          for (String btnString : BUTTON_STRINGS) {
             String text = "" + count + ") " + btnString;
             JButton btn = new JButton(text);
             btn.setMnemonic(KeyEvent.VK_0 + count);  // ooh, this is cheating!
             btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                   System.out.println("button " + ae.getActionCommand() + " pressed");
                }
             });
             
             btnPanel.add(btn);
             count++;
          }
          
          setPreferredSize(APP_SIZE);
          setLayout(new GridBagLayout());
          add(btnPanel);
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Test2");
          frame.getContentPane().add(new Test2());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  14. #14
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Hmmm, a new problem.
    If I use the
    tt.requestFocusInWindow();
    method described on top then if i click the radio button and the frame loses focus then it does not work anymore :(

    so back i go to looking into key bindings :(

  15. #15
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Am on a laptop myself but it has a number pad.
    Your example code worked great on the normal numbers row but now with the number pad.

    Do you have a small program with keybindings? The online docs are a little overkill for me

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

    Default

    Here's an example with key bindings:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Test2KeyBindings extends JPanel {
       public static final String[] BUTTON_STRINGS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
       private static final int GAP = 10;
       private static final Dimension APP_SIZE = new Dimension(1000, 300);
       
       public Test2KeyBindings() {
          JPanel btnPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
          int count = 1;
          for (String btnString : BUTTON_STRINGS) {
             final String text = "" + count + ") " + btnString;
             //!! JButton btn = new JButton(text);
             //!! btn.setMnemonic(KeyEvent.VK_0 + count);  // ooh, this is cheating!
             
             AbstractAction action = new AbstractAction(text) {
                public void actionPerformed(ActionEvent e) {
                   System.out.println("button " + text + " pressed");
                }
             };
             final JButton btn = new JButton(action);
             
             // *** key bindings code ***
             
             // condition tells the input map how to handle the focus.  when in focused
             // window allows the input map to respond if the component with bindings 
             // is in a window that has focus.  The component itself doesn't have to have
             // focus.
             int condition = JComponent.WHEN_IN_FOCUSED_WINDOW; 
             InputMap inputMap = btn.getInputMap(condition);
             ActionMap actionMap = btn.getActionMap();
             inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_0 + count, 0), text);
             //!! actionMap.put(text, action);  // if you don't want the button to click
             
             // if you do want the button to click, use code below
             actionMap.put(text, new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                   btn.doClick();
                }
             });
             
             btnPanel.add(btn);
             count++;
          }
          
          setPreferredSize(APP_SIZE);
          setLayout(new GridBagLayout());
          add(btnPanel);
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Test2");
          frame.getContentPane().add(new Test2KeyBindings());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  17. #17
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Thank you so much!

    I can go to sleep now! Been up the whole night (its 7 am) will check it when i get up and report back if I run into problems.

    Cheers!

  18. #18
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Hey again!

    Works like a charm! And I think I understand the concept for the most part with some small murky areas such as why to use final in some places.

    It does not work with the number pad still, but I think I just have to search and find the number pad keys and bind that too (?).

    +rep'ed!

  19. #19
    N00Bie is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Number pad works!!!

    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_NU MPAD1 , 0), text);
    For anybody else having the same problem, first use Fubarables code then refer to this chart to get the mappings for the keys
    http://download.oracle.com/javase/1..../KeyEvent.html
    Last edited by N00Bie; 02-19-2011 at 05:30 PM. Reason: Added link

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

    Default

    Quote Originally Posted by N00Bie View Post
    Number pad works!!!
    For anybody else having the same problem, first use Fubarables code then refer to this chart to get the mappings for the keys
    KeyEvent (Java 2 Platform SE v1.4.2)
    Thanks for educating me. 1+ rep back atcha!

Page 1 of 2 12 LastLast

Similar Threads

  1. Detect the ENTER key being pressed
    By aaronfsimons in forum New To Java
    Replies: 12
    Last Post: 05-16-2009, 09:48 PM
  2. get key pressed
    By prashant in forum Networking
    Replies: 1
    Last Post: 03-26-2009, 10:10 PM
  3. Waiting for a button to be pressed
    By SomeGuyOverThere in forum New To Java
    Replies: 6
    Last Post: 08-21-2008, 10:30 PM
  4. can you help me with mouse pressed method please?
    By java_fun2007 in forum New To Java
    Replies: 4
    Last Post: 05-22-2008, 11:23 PM
  5. key pressed event
    By kavithas in forum New To Java
    Replies: 7
    Last Post: 12-10-2007, 03:01 PM

Posting Permissions

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