简体   繁体   English

如何动态地将JMenus添加到JMenuBar

[英]How to dynamically add JMenus to JMenuBar

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. 我要做的是单击菜单item1时将菜单添加到菜单栏中。 The line System.out.println(mb.getMenuCount()); 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. (当单击菜单item1时,它会打印2、3、4),但菜单不会显示在菜单栏中。

What should I do so that the menu items that are dynamically added get shown on the menubar? 我应该怎么做才能使动态添加的菜单项显示在菜单栏上? I'm using Java 1.6. 我正在使用Java 1.6。

After adding the extra menu in mb use: mb添加额外菜单后,使用:

mb.revalidate();

This causes the component to get replainted, after the newly added menu has been inserted into the component tree. 在新添加的菜单插入组件树之后,这将导致替换组件。

Try calling repaint after 尝试调用后重画

 frame.setVisible(true);

as

 frame.repaint();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM