Printing Directory Listing
Hi everyone,
I have a very simple GUI that opens up and shows a list of directories. It just uses the fileChooser class to do so, limiting the scope to only directories.
What I need the program to do is when a user has selected a particular directory, a list of directories in that directory must be printed to a text box in the gui, but also be written to the users clipboard. (As if they had selected what was in the text box and pressed CTRL+C).
Does anyone have any clue of how to do this, or even if it's possible?
At the moment I have a program that opens a directory listing and thats it. I have no idea of how to continue with it.
Thanks in advance,
N
[703 byte] By [
neosenate] at [2007-9-30 21:14:31]

An example:import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField field;
private JTextArea area;
public Test () {
setDefaultCloseOperation (DISPOSE_ON_CLOSE);
setTitle ("Test");
getContentPane ().setLayout (new BorderLayout ());
getContentPane ().add (createFieldPanel (), BorderLayout.NORTH);
getContentPane ().add (createArea ());
pack ();
setLocationRelativeTo (null);
show ();
}
private JPanel createFieldPanel () {
field = new JTextField ("c:\\winnt");
field.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent event) {
java.util.List subdirs = getSubdirs (field.getText ());
area.setText (subdirs.toString ());
StringSelection selection = new StringSelection (subdirs.toString ());
Toolkit.getDefaultToolkit ().getSystemClipboard ().setContents (selection, selection);
}
private java.util.List getSubdirs (String dir) {
File[] files = new File (dir).listFiles ();
java.util.List subdirs = new ArrayList ();
for (int i = 0, n = (files == null) ? 0 : files.length; i < n; i ++) {
if (files[i].isDirectory ()) {
subdirs.add (files[i].getAbsolutePath ());
}
}
return subdirs;
}
});
JPanel panel = new JPanel (new BorderLayout ());
panel.add (new JLabel ("Dir:"), BorderLayout.WEST);
panel.add (field);
return panel;
}
private JScrollPane createArea () {
area = new JTextArea (20, 40);
area.setLineWrap (true);
area.setWrapStyleWord (true);
return new JScrollPane (area);
}
public static void main (String[] parameters) {
new Test ();
}
}
(note that this isn't the best code I've ever written - it does what you want though)
Kind regards,
Levi
>> Thankyou SO much, that was exactly what I wanted.
You're welcome.
>> Cause i'm a dunce, I have a little problem though; I can't seem to read the CD drive. It just comes up with
>> [].
>>
>> Any ideas?
Your CD drive should work just as the rest of the drives. If I were you, I'd play around with the file class and its (static) listRoots and listFiles methods. Very soon you'll get a feel for it.
Good luck,
Levi