Note that there are some explanatory texts on larger screens.

plurals
  1. POStopping JPopupMenu stealing the focus
    primarykey
    data
    text
    <p>I have a <code>JTextField</code> for which I'm hoping to suggest results to match the user's input. I'm displaying these suggestions in a <code>JList</code> contained within a <code>JPopupMenu</code>.</p> <p><strong>However</strong>, when opening the popup menu programmatically via <a href="http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JPopupMenu.html#show%28java.awt.Component,%20int,%20int%29" rel="noreferrer"><code>show(Component invoker, int x, int y)</code></a>, the focus is getting taken from the <code>JTextField</code>.</p> <p>Strangely enough, if I call <code>setVisible(true)</code> instead, the focus is not stolen; but then the <code>JPopupMenu</code> is not attached to any panel, and when minimizing the application whilst the box is open, it stays painted on the window.</p> <p>I've also tried to reset the focus to the <code>JTextField</code> using <code>requestFocus()</code>, but then I have to restore the caret position using <code>SwingUtilities.invokeLater()</code>, and the <em>invoke later</em> side of things is giving the user a slight margin to mess around with the existing contents / overwrite it / or do other unpredictable things.</p> <p>The code I've got is effectively:</p> <pre><code>JTextField field = new JTextField(); JPopupMenu menu = new JPopupMenu(); field.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { JList list = getAListOfResults(); menu.add(list); menu.show(field, 0, field.getHeight()); } }); </code></pre> <p>Can anyone suggest the best avenue to go down to show the <code>JPopupMenu</code> programmatically whilst preserving the focus on the <code>JTextField</code>?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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