Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should follow the behavior that is already defined for the system. E.g. on Windows popups are opened on right click and closed on left click. Re-opening the popup for another right click is not a fault, it’s the default behavior here. Achieving the correct behavior regarding the system’s guidelines is easiest if not implemented by hand. Below is an example of a popup which is automatically opened and closed in a system-conforming way.</p> <p>The popup shows a color chooser which allows to change the background of the textfield. Note how easy everything can be if you don’t do it by hand. The popup will also open if the user presses the <code>Menu</code> key on the keyboard, something you might not have thought about.</p> <p>Use what others already have done for you…</p> <pre><code>import java.awt.BorderLayout; import java.beans.EventHandler; import javax.swing.*; import javax.swing.event.ChangeListener; public class Popups { public static void main(String[] args) { JFrame f=new JFrame("popup"); JTextField tf = new JTextField(30); JPopupMenu popup = new JPopupMenu(); JColorChooser cc = new JColorChooser(); cc.getSelectionModel().addChangeListener(EventHandler.create( ChangeListener.class, tf, "background", "source.selectedColor")); popup.add(cc); tf.setComponentPopupMenu(popup); f.getContentPane().add(tf, BorderLayout.NORTH); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { // if this fails life with the default L&amp;F } } } </code></pre>
 

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