Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>How would I fix this bug?</p> </blockquote> <p>Not really a bug as much as incompatiblity.</p> <blockquote> <p>If there is an alternative to KeyListener that will do the same thing, please let me know and preferably provide an example of how it would work.</p> </blockquote> <p>Dont use <code>KeyListener</code>/<code>KeyAdapter</code> for Swing components as there is focus issues, which can be gotten around by calling <code>requestFocusInWindow()</code> on the component after its visible to make sure it has focus and of course <code>setFoucsable(true);</code> must be called if component is not <em>focusable</em> like a <code>JLabel</code>.</p> <p>Swing components should use <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html" rel="nofollow"><code>KeyBinding</code>s</a>, which overcomes the above mentioned problems by automatically calling <code>setFocusable(true)</code> on the component to which <code>KeyBinding</code> is added etc.</p> <p>Here is a small example:</p> <pre><code>void addKeyBinding(JComponent jc) { jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "A pressed"); jc.getActionMap().put("esc pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("A pressed"); } }); jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "A released"); jc.getActionMap().put("A released", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("A released"); } }); } </code></pre> <p>you would call this method with the instance of the <code>JComponent</code> i.e <code>JPanel</code> etc that you want to add the <code>Keybinding</code> too:</p> <pre><code>JPanel p=new JPanel(); addKeyBinding(p); </code></pre> <p><strong>Other suggestions on code:</strong></p> <ul> <li><p>Always create Swing components on <code>Event Dispatch Thread</code> via <code>SwingUtilities.invokeXXX</code> block</p></li> <li><p>Dont implement an <code>Listener</code> like <code>ActionListener</code> on the class itself unless this class will be used as a <code>Listener</code> <strong>only</strong>, or you want to expose the implementing classes/<code>Listeners</code> methods to other classes.</p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload