Search code examples
javajmenujmenuitem

java - Automatically add a JMenuItem inside a JMenu


This is my main problem, how to make a working program that a for loop will automatically add a JMenuItem inside of a JMenu.

It's supposedly like this: When I insert a link to the program, it'll automatically put the link and the file name/folder to the JMenuItem inside the JMenu.

This is my code that I'm working on:

    int paths = 0;

    for(int a = 0; a < paths; a++) {

        int count = a + 1;

        itemPath = new JMenuItem(count + chooser.getAbsolutePath);

        menuPaths.add(itemPath);

    }

Solution

  • Provided I understand your question correctly...

    Do you want to add an infinite number of JMenuItem's into a JMenu?

    If this is the case then you should probably be asking yourself if this is absolutely necessary as your code will crash quickly.

    However, you can use a while loop as follows

        int paths = 0;
        while(true) {
            count++;
            itemPath = new JMenuItem(count + chooser.getAbsolutePath);
            menuPaths.add(itemPath);
    
        }
    

    If, however, you're wondering why your current code isn't working, I would recommend you look at your for loop where you're checking if a < paths where paths and a have both been initialized to 0 and therefore your loop isn't even executing.