Search code examples
javaswingdirectoryjcomboboxpopulate

Populate a JComboBox with file names of a specific directory


I want to populate a JComboBox with file names of a directory. Then, if selected, each field has to show a JList. How can i implement this? Thanks


Solution

  • You can use File>>listFiles()

    http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html

    to get the array of Files in a particular directory (the one you initialized the File-object with).

    You can then use the individual File's getName() method to get the names, then use JComboBox's addItem() method to add those names:

    http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComboBox.html

    Finally, to do something when the user clicks one of those names you have to install an item-listener using the JComboBox's addItemListener()-method. There are tutorials on how to do this last part and in general it just calls your ItemListener, giving it an ItemEvent, which you can then use to check which name was clicked.