0

lets say I have a folder called examples/basics/ In that folder I have a bunch of .asm files. What I would now like to do is to have those files automatically made into JMenuItems, without the .asm extension, placed inside a JMenu and have actionlisteners added to them, that do the following:

User clicks on JMenuItem genetated. A new, lets say a CodeArea object is created and the file examples/basics/what I clikced on is passed in as a new File.

How to achive this with the simplest means?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Makerimages
  • 384
  • 6
  • 27
  • What's your problem, it's not clear. You can't iterate all files in folder and create Menu dinamycally? or you can't create `ActionListener` that create new `File` from path? – alex2410 Nov 05 '13 at 13:26
  • Read all fileNames in that directory with the right extension and store them in an array or list. Iterate over that list and create one menuItem per iteration with the current name and add it to your menuBar and also add an actionListener. – HectorLector Nov 05 '13 at 13:27
  • How do I make the read loop? – Makerimages Nov 05 '13 at 13:35

1 Answers1

1

Simple example for your purposes:

    JFrame frame = new JFrame();
    frame.setSize(400,400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menu = new JMenuBar();
    frame.setJMenuBar(menu);

    JMenu mainMenu = new JMenu("Menu");
    menu.add(mainMenu);

    File f = new File(PATH_TO_FOLDER);
    if(f.exists()){
        File[] listFiles = f.listFiles();
        for(File file : listFiles){
            if(file.getAbsolutePath().endsWith(EXTENSION)){
                final JMenuItem m = new JMenuItem(file.getName());
                mainMenu.add(m);
                m.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        System.out.println(m.toString());
                    }
                });
            }
        }
    }

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

Here PATH_TO_FOLDER is path to your folder with files

EXTENSION is target extension of file for menus

alex2410
  • 10,904
  • 3
  • 25
  • 41