JulioQc
JulioQc

Reputation: 307

Get JMenuItems from JMenuBar

I'm trying to retrieve the JMenuItems in my JMenuBar from a class which receives the JFrame as an argument. Ive done some reading and I think I understand that the JMenuBar contains JMenu but those do not contain the JMenuItems directly, correct?

Here what I have so far (obviously, it doesn't work!):

JFrame mainWindow;

[...]

Component[] menus = mainWindow.getJMenuBar().getComponents();

So how could I obtain, lets say at best, an array of all the JMenuItems of my JFrame? I will then simply enable them one-by-one afterwards.

Thanks!

Upvotes: 1

Views: 1984

Answers (3)

JulioQc
JulioQc

Reputation: 307

Thanks a bunch! This turned out to work great and was easier then expected :)

          for (int i = 0; i < mainWindow.getJMenuBar().getMenuCount(); i++) {
                for (int j = 0; j < mainWindow.getJMenuBar().getMenu(i).getItemCount(); j ++) {
                    if (mainWindow.getJMenuBar().getMenu(i).getItem(j) != null) {
                        mainWindow.getJMenuBar().getMenu(i).getItem(j).setEnabled(true);
                    }
                }
            }

Upvotes: 0

Braj
Braj

Reputation: 46841

Yes you can get the JMenu and JMenuItem as well.

Use JMenuBar#getMenu() and JMenu#getMenuComponent() methods to get the desired output.

sample program:

JMenuBar menubar1 = getJMenuBar();
for (int i = 0; i < menubar1.getMenuCount(); i++) {
    JMenu menu1 = menubar1.getMenu(i);
    System.out.println("Menu:" + menu1.getText());
    for (int j = 0; j < menu1.getMenuComponentCount(); j++) {
        java.awt.Component comp = menu1.getMenuComponent(j);
        if (comp instanceof JMenuItem) {
            JMenuItem menuItem1 = (JMenuItem) comp;
            System.out.println("MenuItem:" + menuItem1.getText());
        }
    }
}

Upvotes: 5

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

The JMenu class has methods that its API will show that allow you to easily get the JMenuItems: getItemCount() and getItem(int pos). There's also getMenuElements() as well.

Upvotes: 2

Related Questions