
150
|
Chapter 4, File Choosers
#28 Add a Right-Click Context Menu to the JFileChooser
HACK
the millions of users out there with older versions of Java, then you need
your own implementation. This hack creates a right-click menu on the
JFileChooser
to give the user those missing features.
The goal of this task is to create a contextual menu. This means it’s a menu
that pops up when you hit the right mouse button (or Control-click on one-
button mice). It also is contextual, or context sensitive. This means the menu
changes—or does something different—depending on what you currently
have selected. In this case, there will be two actions: Delete will delete the
currently selected file or directory, if one is selected; New Folder will create
a new folder (called, not surprisingly, New Folder) in the current directory.
Both of these actions depend on the current state of the file selection, so
they are considered context sensitive.
The Problem
For the most part, Swing is quite extensible, but often only in ways that the
Swing team thought of beforehand. The
JFileChooser has ways to change
the rendering of file icons, filtering the file list, adding components, and
changing the text. It does not have any way to add pop-up menus, though.
In short, we’ll have to hack it, and there’s no better way to start than by
reusing another hack.
Chapter 8 has a hack for adding pop-up menu support to any frame; see
“Create ...