Following is my code.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MenuBarProblem {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(300, 400));
JMenu menu1 = new JMenu("First");
JMenuItem item = new JMenuItem("Add menu");
menu1.add(item);
final JMenuBar mb = new JMenuBar();
mb.add(menu1);
frame.setJMenuBar(mb);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JMenu menu1 = new JMenu("First");
JMenuItem item = new JMenuItem("Add menu");
menu1.add(item);
mb.add(menu1);
System.out.println(mb.getMenuCount());
}
});
frame.setVisible(true);
}
}
What I want to do is to add menus to the menubar when the menu item1 is clicked. The line System.out.println(mb.getMenuCount());
prints that the menu items are being added. (It prints 2,3,4 when the menu item1 is clicked) but the menus don't show up in the menu bar.
What should I do so that the menu items that are dynamically added get shown on the menubar? I'm using Java 1.6.
Try calling repaint after
as
After adding the extra menu in
mb
use:This causes the component to get replainted, after the newly added menu has been inserted into the component tree.