2

I'm a beginner to Java, so if I'm making some derp mistake, please forgive me...

I have a JComboBox assigned to an array called fileNames. My goal is to make the JComboBox display all of the filenames in a certain directory. So far I have worked out the code to assign all of the files in the directory to a single String called files.
Code:

package modmaker;

public class GuiBlocks2 extends JFrame {
    /**  
* 
*/
private static final long serialVersionUID = 1L;
public JFileChooser filePath;
FileEditor fileeditor = new FileEditor();
/**
 * Launch the application.
 */
static String files;
static String[] fileNames={files};
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GuiBlocks2 frame = new GuiBlocks2();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    // Directory path here
    String path = "."; 
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles(); 

    for (int i = 0; i < listOfFiles.length; i++) 
    {

    if (listOfFiles[i].isFile()) 
    {
        files = listOfFiles[i].getName();
        if (files.endsWith(".png") || files.endsWith(".PNG"))
        {
            System.out.println(files);
        }
    }
}
} 

After this there's another method that adds the combobox assigned to the fileNames array. My question: How to assign all of the files to the array.

Jeff
  • 95
  • 1
  • 1
  • 3
  • 1
    Why the static variables? Why not do everything but your class initialization code (in the invokeLater block) in instance methods? Consider not using an Array but rather a DefaultComboBoxModel and add your file names to this model as you identify them in the for loop. – Hovercraft Full Of Eels Sep 02 '11 at 00:56

1 Answers1

0

if you want an array of all the files in the current directory, you can simply create a String object and add each fileName(in the loop) to it. you should add a separator like ":" between them.

I change your code like this:

String fileList ="";
for (int i = 0; i < listOfFiles.length; i++) 
{

if (listOfFiles[i].isFile()) 
{
    files = listOfFiles[i].getName();
    fileList += files + ":";
    if (files.endsWith(".png") || files.endsWith(".PNG"))
    {
        System.out.println(files);
    }
}

now if you want get an array of all file names, you can simply use split method. I assign the array to a new String array named allFile;

String[] allFile = fileList.split(":");
Isa Hekmat
  • 758
  • 1
  • 7
  • 19