Search code examples
javaswingfilenamesjcombobox

Filtering File objects in java to populate a jComboBox


Using the code below populates my JComboBox with the complete path. is there an easy way to filter it to only show the file name itself in the JComboBox.

    String path = "\\\\intdatserver1\\NY_files";
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    final JComboBox jList1 = new JComboBox(listOfFiles);

Solution

  • I think you could figure it out by yourself but if you insist...

    List<String> fileNames = new ArrayList<String>();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            fileNames.add(file.getName());
        } else if (file.isDirectory()) {
            // handle directory
        }
    }