net.lucidviews.util.gui.swing
Class JFileSaver

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JPanel
                  extended by net.lucidviews.util.gui.swing.JFileSaver
All Implemented Interfaces:
ActionListener, ImageObserver, MenuContainer, Serializable, EventListener, Accessible

public class JFileSaver
extends JPanel
implements ActionListener

A panel that allows the user to choose a file and, optionally edit its path before hitting the save button.
The main benefit of this method of choosing a file is that the user needs only too choose a folder (or an initial file). If the name of the file can be programmatically generated then the user does not need to browser or enter a new file name, just keep hitting the save button.

Since:
1.3
Version:
$Revision: 1.1.2.1 $
Author:
Stephen Battey
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanel
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
protected  JButton chooseButton
          Button that opens the file chooser dialog.
protected  JTextField path
          The text field used to display/input the file path.
static String SAVE_COMMAND
          The command associated with save events.
static int SAVE_ID
          The id of save events.
protected  JButton saveButton
          Button that triggers the file to be saved.
protected  ActionListener saveListener
          The listener that will react to the save button being pressed, or null if no listener is registered.
private static long serialVersionUID
          Serialisation version id.
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JFileSaver(String filePath)
          Create a file chooser panel, defaulting to the given file location.
 
Method Summary
 void actionPerformed(ActionEvent e)
          
 int chooseFile()
          Open a dialog to allow the user to choose a file.
static boolean ensureParentFolderExists(File file, Component component)
          Ensure the parent folder for a given file exists.
 File getFile()
          Get the chosen file.
 boolean isValidFile()
          Check if the current file chosen is valid.
 void saveFile()
          Trigger the file to be saved.
 void setEditable(boolean editable)
          Decide whether the user can hand-edit the file path.
 void setFile(File file)
          Set the file chosen.
 void setFileName(String fileName)
          Change the name of the file chosen.
 void setSaveListener(ActionListener listener)
          Set the save listener.
 boolean validateFile()
          Check the file path entered is valid.
 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, 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, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, 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, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods 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, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods 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, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, 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, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

SAVE_ID

public static final int SAVE_ID
The id of save events.

See Also:
Constant Field Values

SAVE_COMMAND

public static final String SAVE_COMMAND
The command associated with save events.

See Also:
Constant Field Values

serialVersionUID

private static final long serialVersionUID
Serialisation version id.

See Also:
Constant Field Values

path

protected JTextField path
The text field used to display/input the file path.


chooseButton

protected JButton chooseButton
Button that opens the file chooser dialog.


saveButton

protected JButton saveButton
Button that triggers the file to be saved.


saveListener

protected ActionListener saveListener
The listener that will react to the save button being pressed, or null if no listener is registered.

Constructor Detail

JFileSaver

public JFileSaver(String filePath)
Create a file chooser panel, defaulting to the given file location.

Parameters:
filePath - the initial path
Method Detail

setEditable

public void setEditable(boolean editable)
Decide whether the user can hand-edit the file path.

Parameters:
editable - true if the path can be edited, false if the user must use the file chooser

setSaveListener

public void setSaveListener(ActionListener listener)
Set the save listener.

Parameters:
listener - the listener that will save the file
See Also:
saveListener

getFile

public File getFile()
Get the chosen file.

Returns:
the file that has been chosen, which may not exist or may point to a folder

isValidFile

public boolean isValidFile()
Check if the current file chosen is valid.

Returns:
true if the file returned from getFile can be written to

setFile

public void setFile(File file)
Set the file chosen.

Parameters:
file - the file to be chosen

setFileName

public void setFileName(String fileName)
Change the name of the file chosen.
Nominally, the new file will be in the same folder as the current file. This allows the file name to be changed, while keeping the user's chosen folder.

Parameters:
fileName - the name of the file

chooseFile

public int chooseFile()
Open a dialog to allow the user to choose a file.

Returns:
JFileChooser.APPROVE_OPTION if the user confirmed a new file location

validateFile

public boolean validateFile()
                     throws IOException
Check the file path entered is valid.
The path in the UI will be changed to ensure a file can be written to that location, provided the user agrees to those changes.

Returns:
true if the file path is now valid, will be false if the user has chosen to cancel the changes needed to make the file path valid
Throws:
IOException - if the file path could not be validated

saveFile

public void saveFile()
Trigger the file to be saved.
The file path entered into the UI will be validated before any listeners are asked to perform the save. If validation fails the file will not be saved.


actionPerformed

public void actionPerformed(ActionEvent e)

Specified by:
actionPerformed in interface ActionListener

ensureParentFolderExists

public static boolean ensureParentFolderExists(File file,
                                               Component component)
Ensure the parent folder for a given file exists.
If it does not the user is asked whether it should be created.

Parameters:
file - the target file
component - the UI component used to associate question dialogs
Returns:
true if the parent folder for the given file exists