views:

99

answers:

1

I'm trying to move the menu structure from a JMenu into a JMenuBar. The above code shows different menus depending on TEST. For TEST==1 i expect aa bb in the menu bar, but only aa is shown ? The code shows the problem, it is not my real code ....

public class Test {

    public static void main(String[] args) {

        int TEST = 1; // or 2

        JMenu menu = new JMenu("a");

        JMenu menu2 = new JMenu("aa");
        menu.add(menu2);

        menu2 = new JMenu("bb");
        menu.add(menu2);

        JMenuBar mbar = new JMenuBar();

        if (TEST == 1) {
            for (int i = 0; i < menu.getItemCount(); i++) {
                mbar.add(menu.getItem(i));
            }
        }

        if (TEST == 2) {
            mbar = new JMenuBar();
            mbar.add(menu);
        }

        JFrame frame = new JFrame();
        frame.setJMenuBar(mbar);
        frame.setSize(400, 200);
        frame.setVisible(true);
    }
}
A: 

Hehe, tricky one. By executing

mbar.add(menu.getItem(i));

the menu that you just added to mbar is removed from menu. On the next iteration menu.getItemCount() returns 1 and you for loop is over. This one will work:

if (TEST == 1) {
    int m = menu.getItemCount();
    for (int i = 0; i < m; i++) {
         mbar.add(menu.getItem(0));
    }
}
Bombe
Dammned ! I think i had this years before and cannot remember. Thank you !
PeterMmm