I am trying to build a JMenu dynamically right when clicking in it (I’m only getting an empty menu), below is my code.
final JMenu JMWindows = new JMenu("Opened Windows");
JMWindows.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(JInternalFrame ji : desktop.getAllFrames())
{
JMWindows.add(ji.getTitle());
}
}
});
I’ve realized that the actionperformed is never called, the JMenu is inside a JMenuBar. What could be the problem ?
You add
ActionListenertoJMenuthis cannot be done forJMenuuseMenuListenerand set it viaJMenu#addMenuListener(..)Also you need to call
revalidate()andrepaint()onJMenuinstance after adding/removing components from it or the changes will not be reflected (we could also call this on the containers instance i.eJMenuBarorJFrame, but we know only 1 specificJMenuwill change so no need IMO).Please watch your variable naming schemes
JMWindowshould bejmWindow/jMWindowvariables always begin with no caps and the 1st letter of every new word thereafter gets capitalized (besides for constants andenums).Here is an example using
MenuListener: