How to dynamically add JMenus to JMenuBar

2019-08-06 00:39发布

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.

2条回答
Juvenile、少年°
2楼-- · 2019-08-06 01:04

Try calling repaint after

 frame.setVisible(true);

as

 frame.repaint();
查看更多
够拽才男人
3楼-- · 2019-08-06 01:07

After adding the extra menu in mb use:

mb.revalidate();

This causes the component to get replainted, after the newly added menu has been inserted into the component tree.

查看更多
登录 后发表回答