Search code examples
javaswingcheckboxjframejcheckbox

Issue with creating multiple checkbox on a fly


I am trying to read all the file name from a specific folder and trying to create multiple checkbox in JFrame with the same name. So, if there are 5 files in the folder, application should show 5 checkboxes in the frame.

Here is my code.

    JFrame frame = new JFrame();
    File folder = new File("C://Tests");
    File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            System.out.println("File " + listOfFiles[i].getName());
          } else if (listOfFiles[i].isDirectory()) {
            System.out.println("Directory " + listOfFiles[i].getName());
          }
          JCheckBox checkbox[i] = new JCheckBox(listOfFiles[i].getName());

        }

But I am getting error "Type mismatch: cannot convert from JCheckBox to JCheckBox[]". Can someone please tell me what am I doing incorrect ?

Appreciate any help. Thanks


Solution

  • Define and initialise the array first...

    JCheckBox checkbox[] = new JCheckBox[listOfFiles.length];
    

    Then fill it...

    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            System.out.println("File " + listOfFiles[i].getName());
        } else if (listOfFiles[i].isDirectory()) {
            System.out.println("Directory " + listOfFiles[i].getName());
        }
        checkbox[i] = new JCheckBox(listOfFiles[i].getName());
    }
    

    If you want to be able to access the array later on your program, you will need to make the array an instance field...

    public class ... {
        //...
        private JCheckBox checkbox[];
    

    Then initialise it when you know how many files you have...

    File[] listOfFiles = folder.listFiles();
    checkbox[] = new JCheckBox[listOfFiles.length];
    

    Frankly, a simpler solution would be to use some kind List, like an ArrayList. See Collections Trail for more details