Write
a java program to accept directory name in TextField and display list of files
and subdirectories in List Control from that directory by clicking on Button.
import
javax.swing.*;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.io.File;
public class
DirectoryLister extends JFrame {
private JTextField directoryField;
private JButton listButton;
private JList<String> fileList;
public DirectoryLister() {
setTitle("Directory Lister");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
directoryField = new JTextField();
listButton = new JButton("List
Directory");
fileList = new JList<>();
listButton.addActionListener(new
ActionListener() {
@Override
public void
actionPerformed(ActionEvent e) {
listDirectoryContents();
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("Directory:
"));
panel.add(directoryField);
panel.add(listButton);
JScrollPane scrollPane = new
JScrollPane(fileList);
add(panel, "North");
add(scrollPane, "Center");
}
private void listDirectoryContents() {
String directoryPath =
directoryField.getText();
File directory = new
File(directoryPath);
if (directory.exists() &&
directory.isDirectory()) {
String[] contents =
directory.list();
fileList.setListData(contents);
} else {
fileList.setListData(new String[] {
"Directory not found." });
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new
Runnable() {
public void run() {
DirectoryLister directoryLister = new
DirectoryLister();
directoryLister.setVisible(true);
}
});
}
}