I need to implement file browsing feature in my app and while I am aware of possibility of making a JList item and doing it manually I had an idea to just implement JFileChooser for this. I managed to reduce the JFileChooser just to list of directories and files but I wasn't able to override some of it's functionalities. I have been going through source code but no luck. My idea is for it to handle as following: On the top of the list to have a /... directory so when clicked on it it returns to parent folder. Also when double clicked on directory it sets it as current directory. When double clicked on file it returns the file as selected.
This is the code I used so far:
final JFileChooser fc = new JFileChooser();
fc.setControlButtonsAreShown(false);
fc.setCurrentDirectory(paths[list.getSelectedIndex()]);
/*remove unwanted components*/
for(int i = 0; i < fc.getComponentCount(); i++) {
fc.getComponent(0).setVisible(false);
fc.getComponent(1).setVisible(false);
fc.getComponent(3).setVisible(false);
}
add(fc, BorderLayout.CENTER);
I tried adding custom MouseListener to the JFileChooser but it didn't work.
This is the result I have so far:
Any idea which classes or listeners to overwrite/replace so I can achieve 2 desired effects?
This is what I am looking for in visual terms:
JFileChooser
has method with namechangeToParentDirectory()
. So you could simply add a Button and call that method.You can set a
PropertyChangeListener
to listen forJFileChooser.DIRECTORY_CHANGED_PROPERTY
property that is fired whenever the current directory has changed using double click or the internal commands.You can set an
ActionListener
to listen forJFileChooser.APPROVE_SELECTION
action that is fired whenever a file is chosen by double click.EDIT:
This could be achieved by using a manipulated
FileSystemView
with theJFileChooser
that is responsible for interacting with the content of the filesystem. My implementation manipulates thegetFiles
method to smuggle a specialFile
in the list that has a defined name and points to the parent directory.I'm not quite sure if this is a very good idea, since this is really not meant to be in the
JFileChooser
Code but here we go.EDIT2:
There are two possibilities. The simple one is to change the style of your
JFileChooser
to theDetails View
by adding this code:The more complex one is to change the
LayoutOrientation
of the file viewJList
that is a component ofsun.swing.FilePane
that is theComponent
withID:2
in theJFileChooser
.One problem here is that
FilePane
is not part of the Java Library but part of the Core Library and not accessible by default. But you can use Reflection to get the fieldprivate JList list;
in theFilePane
and change itsLayoutOrientation
toJList.VERTICAL
with this code: