Results 1 to 20 of 21
- 02-19-2011, 03:29 AM #1
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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 03:54 AM.
- 02-19-2011, 03:31 AM #2
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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?
-
For one, please edit your first post and change your "quote" tags to "code" tags so we can read the code.Where did I screwup?
- 02-19-2011, 03:54 AM #4
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
Done :))...
-
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?
- 02-19-2011, 04:13 AM #6
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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.
-
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 bindingsSorry for the long explanation.
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.
- 02-19-2011, 04:28 AM #8
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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.
-
Also: If you don't mind using alt-key combinations, you could simply set the JButton's mnemonic to be alt-your number.
- 02-19-2011, 04:56 AM #10
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
That key bindings thing is pretty long with no quick examples :(
I did find this though:
adding this
under mytt.requestFocusInWindow();
seems to work for the most part but is also giving me some other output...Test tt = new Test();
tt.setVisible(true);
For keyReleased() it gives me:
Unknown keyCode: 0x0
- 02-19-2011, 04:59 AM #11
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
- 02-19-2011, 05:01 AM #12
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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 :(
-
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(); } }); } }
- 02-19-2011, 05:04 AM #14
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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 :(
- 02-19-2011, 05:07 AM #15
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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
-
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(); } }); } }
- 02-19-2011, 05:41 AM #17
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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!
- 02-19-2011, 04:11 PM #18
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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!
- 02-19-2011, 04:28 PM #19
Senior Member
- Join Date
- Feb 2011
- Posts
- 107
- Rep Power
- 0
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 keysinputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_NU MPAD1 , 0), text);
http://download.oracle.com/javase/1..../KeyEvent.htmlLast edited by N00Bie; 02-19-2011 at 04:30 PM. Reason: Added link
-
Similar Threads
-
Detect the ENTER key being pressed
By aaronfsimons in forum New To JavaReplies: 12Last Post: 05-16-2009, 08:48 PM -
get key pressed
By prashant in forum NetworkingReplies: 1Last Post: 03-26-2009, 09:10 PM -
Waiting for a button to be pressed
By SomeGuyOverThere in forum New To JavaReplies: 6Last Post: 08-21-2008, 09:30 PM -
can you help me with mouse pressed method please?
By java_fun2007 in forum New To JavaReplies: 4Last Post: 05-22-2008, 10:23 PM -
key pressed event
By kavithas in forum New To JavaReplies: 7Last Post: 12-10-2007, 02:01 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks