C H A P T E R F O U R
Ah, the poor JFileChooser. It’s probably not anybody’s favorite class in
Swing, and it’s quite likely the anti-favorite of many developers. Prior to Java
1.4, the Metal version had an “icon view” button that actually didn’t do any-
thing—not that it was worth writing home about once it was implemented.
Little glitches like this make JFileChooser the whipping boy of many Swing
developers. Apple’s Java guidelines for Mac OS X actually advocate giving
up on the
JFileChooser altogether and going back to the AWT FileDialog!
This chapter is here to…well, if not to praise the
JFileChooser, then cer-
tainly not to bury it either. This is Swing after all, and that means there are
all sorts of places that you can hack in and embellish functionality to give
the user more power, or to make a component smarter about the contents it
H A C K
Add a Right-Click Context Menu
to the JFileChooser Hack #28
Improve the native platform fidelity of the JFileChooser by adding a
contextual menu that lets the user create new folders and delete files.
The standard JFileChooser that comes with Swing is quite limited. It doesn’t
follow shortcuts or any other linked files. It doesn’t have image previews or
even a right-click menu. These are all features that users expect to see.
Worse, these are the kinds of details that continue to reinforce the belief that
Swing apps are inferior to native ones.
This hack will tackle the first limitation, the lack of a context menu. Some
platform file choosers—Windows Explorer in particular—provide users
with a context menu, also known as a right-click menu. This provides fast
access to commonly used functions like Delete and New Folder. Java 5.0
finally added a context menu to the file chooser, but if you want to target