Package ca.corbett.extras.dirtree
Class DirTree
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
ca.corbett.extras.dirtree.DirTree
- All Implemented Interfaces:
ImageObserver,MenuContainer,Serializable,EventListener,Accessible,TreeSelectionListener
A component that renders directories in the file system as a navigable tree view.
The DirTree can be "locked" to a specific directory, in which case it will only display
subdirectories of that directory. When "unlocked", the DirTree will display all
filesystem roots (e.g. "/" on Linux-based systems, or all available drives on Windows).
- Since:
- 2017-11-09
- Author:
- scorbo2
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanelNested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionaddDirTreeListener(DirTreeListener listener) Registers a DirTreeListener with this DirTree.static DirTreeDeprecated, for removal: This API element is subject to removal in a future version.Use the constructor instead.static DirTreecreateDirTree(File dir) Deprecated, for removal: This API element is subject to removal in a future version.Use the constructor instead.booleanIndicates whether this DirTree allows locking (chrooting).booleanIndicates whether this DirTree allows unlocking (de-chrooting).Returns the currently selected directory, or null if nothing is selected.Returns the current FileFilter used to restrict which files are shown.static File[]Returns all filesystem roots for the current platform.Returns the current lock directory, if the tree is locked, otherwise null.booleanIndicates whether files are shown in this DirTree.booleanIndicates whether hidden items (directories and files) are shown in this DirTree.booleanDeprecated.UsegetShowHidden()instead.Provides access to theTreeCellRendererin the underlyingJTree.booleanisLocked()Indicates whether this DirTree is "locked" to a specific subdirectory (similar to chroot).void"Locks" this DirTree to the given directory, meaning that only subdirectories of the given directory will be shown.voidreload()Reloads this DirTree.removeDirTreeListener(DirTreeListener listener) Unregisters a DirTreeListener from this instance.booleanselectAndScrollTo(File dir) Selects and scrolls to the given directory.setAllowLock(boolean allow) Enables or disables locking within this DirTree (chrooting).setAllowUnlock(boolean allow) Enables or disables unlocking within this DirTree (chrooting).voidsetBackground(Color color) This is overridden so that we can ensure the underlying JTree will pick up the desired background color.voidsetEnabled(boolean enabled) Calls to setEnabled are not forwarded from parent components to child components.setFileFilter(FileFilter fileFilter) Sets an optional FileFilter to restrict which files are shown in the tree.setShowFiles(boolean showFiles) Controls whether files are shown in this DirTree.setShowHidden(boolean showHidden) Controls whether hidden items (directories and files) are shown in this DirTree.setShowHiddenDirs(boolean showHiddenDirs) Deprecated.UsesetShowHidden(boolean)instead.setTreeCellRenderer(TreeCellRenderer renderer) Allow setting a customTreeCellRendereron the underlyingJTree.voidunlock()Unlocking the DirTree reverts it back to showing all filesystem roots.voidOverridden from TreeSelectionListener, so we can listen for selection events within our JTree and notify our own listeners that the selection has changed.Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUIMethods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Constructor Details
-
DirTree
public DirTree()Creates a DirTree in "unlocked" mode, showing all filesystem roots. You can then use the lock() method to lock (chroot) the DirTree to a specific subdirectory. -
DirTree
Creates a new DirTree instance chrooted to the specified directory.
-
-
Method Details
-
createDirTree
Deprecated, for removal: This API element is subject to removal in a future version.Use the constructor instead. This factory method may be removed in a future release.Creates a defaulted DirTree instance for viewing the first available filesystem root. Don't use this! It dates back to when DirTree was heavily linux-specific. On Windows, this will only show the first available drive, which is probably not what you want. The no-args constructor is the safest way to instantiate a DirTree in a platform-independent way.- Returns:
- The new DirTree instance.
-
createDirTree
@Deprecated(since="swing-extras 2.7", forRemoval=true) public static DirTree createDirTree(File dir) Deprecated, for removal: This API element is subject to removal in a future version.Use the constructor instead. This factory method may be removed in a future release.Creates a DirTree instance chrooted to the specified directory. As of swing-extras 2.7, this is exactly equivalent to new DirTree(dir).- Parameters:
dir- The directory to which to lock this DirTree (use unlock() to unlock it).- Returns:
- The new DirTree instance.
-
getTreeCellRenderer
Provides access to theTreeCellRendererin the underlyingJTree. By default, the renderer is whatever the current Look and Feel installs on the tree. During construction, if that default renderer is aDefaultTreeCellRenderer,DirTreeclears its icons (sets them tonull) to avoid showing per-node icons.- Returns:
- The
TreeCellRendererused by the underlyingJTree.
-
setTreeCellRenderer
Allow setting a customTreeCellRendereron the underlyingJTree. By default,DirTreeuses the renderer installed by the current Look and Feel and, if that renderer is aDefaultTreeCellRenderer, it clears its icons (sets them tonull) to avoid showing per-node icons. If you replace the renderer and still want an iconless appearance, you should configure your custom renderer accordingly (for example, by setting icons tonullon aDefaultTreeCellRenderer).- Parameters:
renderer- TheTreeCellRendererto use for rendering tree nodes.- Returns:
- This
DirTreeinstance, for chaining.
-
setBackground
This is overridden so that we can ensure the underlying JTree will pick up the desired background color. If you've changed the background, and you want to revert to letting the current Look and Feel choose the color selection for you, you can use LookAndFeelManager.getLafColor() with "Tree.background" as the key name.- Overrides:
setBackgroundin classJComponent- Parameters:
color- the desired backgroundColor.
-
getFilesystemRoots
Returns all filesystem roots for the current platform. On Unix-like systems, this typically returns a single root ("/"). On Windows, this returns all available drives.- Returns:
- Array of all filesystem roots.
-
getLockDir
Returns the current lock directory, if the tree is locked, otherwise null.- Returns:
- The current lock directory, or null if not locked.
-
getCurrentDir
Returns the currently selected directory, or null if nothing is selected.- Returns:
- The current directory, or null if nothing selected.
-
addDirTreeListener
Registers a DirTreeListener with this DirTree.- Parameters:
listener- The DirTreeListener which will receive events from us.
-
removeDirTreeListener
Unregisters a DirTreeListener from this instance.- Parameters:
listener- The DirTreeListener to unregister.
-
setEnabled
public void setEnabled(boolean enabled) Calls to setEnabled are not forwarded from parent components to child components. So, if someone invokes setEnabled on this DirTree, we have to forward that message to our contained JTree and scroll pane.- Overrides:
setEnabledin classJComponent
-
isLocked
public boolean isLocked()Indicates whether this DirTree is "locked" to a specific subdirectory (similar to chroot). Use unlock() to revert to the default display where all directories will be shown.- Returns:
- Whether our display is filtered to a specific subdirectory (see getRootDirectory()).
-
getAllowLock
public boolean getAllowLock()Indicates whether this DirTree allows locking (chrooting). Default is true.- Returns:
- Whether this DirTree allows locking.
-
getAllowUnlock
public boolean getAllowUnlock()Indicates whether this DirTree allows unlocking (de-chrooting). Default is true.- Returns:
- Whether this DirTree allows unlocking.
-
setAllowLock
Enables or disables locking within this DirTree (chrooting). Passing false will unlock the DirTree if it is currently locked, and will prevent the "lock" menu item from appearing in the popup menu. Disallowing a tree lock will also disallow unlocking.- Parameters:
allow- Whether to enable locking.
-
setAllowUnlock
Enables or disables unlocking within this DirTree (chrooting). Disabling this will prevent the "unlock" menu item from appearing in the popup menu.- Parameters:
allow- Whether to enable unlocking.
-
getShowHiddenDirs
Deprecated.UsegetShowHidden()instead.Indicates whether hidden directories are shown in this DirTree. Default is true. -
getShowHidden
public boolean getShowHidden()Indicates whether hidden items (directories and files) are shown in this DirTree. Default is true. -
setShowHiddenDirs
Deprecated.UsesetShowHidden(boolean)instead.Controls whether hidden directories are shown in this DirTree. Default is true. What constitutes a "hidden" directory is platform-dependent. -
setShowHidden
Controls whether hidden items (directories and files) are shown in this DirTree. Default is true. What constitutes a "hidden" item is platform-dependent. -
getShowFiles
public boolean getShowFiles()Indicates whether files are shown in this DirTree. Default is false. When enabled, files are shown as leaf nodes within directories. -
setShowFiles
Controls whether files are shown in this DirTree. Default is false. When enabled, files are shown as leaf nodes within directories.- Parameters:
showFiles- Whether to show files in the tree.
-
getFileFilter
Returns the current FileFilter used to restrict which files are shown. Returns null if no filter is set (all files are shown). -
setFileFilter
Sets an optional FileFilter to restrict which files are shown in the tree. Only relevant whenshowFilesis enabled. If null, all files are shown.- Parameters:
fileFilter- The FileFilter to apply, or null to show all files.
-
reload
public void reload()Reloads this DirTree. When the reload is complete, the currently selected directory (if any) will be re-selected. -
lock
"Locks" this DirTree to the given directory, meaning that only subdirectories of the given directory will be shown. This is similar to chrooting. If the given directory does not exist, or is null, this method does nothing.- Parameters:
newRootDir- The new root directory.
-
unlock
public void unlock()Unlocking the DirTree reverts it back to showing all filesystem roots. -
selectAndScrollTo
Selects and scrolls to the given directory. Does nothing if the directory doesn't exist.- Parameters:
dir- The directory to select.
-
valueChanged
Overridden from TreeSelectionListener, so we can listen for selection events within our JTree and notify our own listeners that the selection has changed.- Specified by:
valueChangedin interfaceTreeSelectionListener- Parameters:
e- The TreeSelectionEvent.
-