Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make use of the <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.html" rel="nofollow"><code>MenuListener</code></a> which should provide you information about the state of the menu.</p> <p>This simple example creates a new menu item each time the menu is opened...</p> <pre><code>import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; public class TestMenuBar { public static void main(String[] args) { new TestMenuBar(); } public TestMenuBar() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JMenuBar mb = new JMenuBar(); JMenu main = new JMenu("Test"); mb.add(main); main.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { System.out.println("Selected"); JMenu menu = (JMenu) e.getSource(); menu.add(new JMenuItem("I'm dynamiclly created")); } @Override public void menuDeselected(MenuEvent e) { System.out.println("deselected"); } @Override public void menuCanceled(MenuEvent e) { System.out.println("Canceled"); } }); JFrame frame = new JFrame("Testing"); frame.setJMenuBar(mb); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </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