Package adams.gui.core
Class TextEditorPanel
- java.lang.Object
-
- java.awt.Component
-
- java.awt.Container
-
- javax.swing.JComponent
-
- javax.swing.JPanel
-
- adams.gui.core.BasePanel
-
- adams.gui.core.TextEditorPanel
-
- All Implemented Interfaces:
TextSupporter
,TextSupplier
,ImageObserver
,MenuContainer
,Serializable
,Accessible
public class TextEditorPanel extends BasePanel implements TextSupplier
A panel that allows the editing of text, including undo/redo support.- Author:
- fracpete (fracpete at waikato dot ac dot nz)
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
TextEditorPanel.TextEditorArea
Specialized BaseTextArea.-
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.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
-
Field Summary
Fields Modifier and Type Field Description protected HashSet<ChangeListener>
m_ChangeListeners
the listeners for modification events.protected String
m_CurrentEncoding
the current file encoding.protected File
m_CurrentFile
the current file.protected TextFileChooser
m_FileChooser
for saving the content.protected boolean
m_IgnoreChanges
whether to ignore changes.protected String
m_LastFind
the last search string used.protected boolean
m_Modified
whether the content was modified.protected PopupMenuCustomizer<TextEditorPanel>
m_PopupMenuCustomizer
for customizing the popup menu.protected TextEditorPanel.TextEditorArea
m_TextArea
for displaying the text.protected UndoManager
m_Undo
for managing undo/redo.-
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_WINDOW
-
Fields inherited from class java.awt.Component
accessibleContext, 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
Constructors Constructor Description TextEditorPanel()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addChangeListener(ChangeListener l)
Adds the given change listener to its internal list.void
append(String str)
Appends the text at the end.boolean
canCopy()
Checks whether text can be copied at the moment.boolean
canCut()
Checks whether text can be cut at the moment.boolean
canPaste()
Checks whether text can be pasted at the moment.boolean
canRedo()
Checks whether a redo action is available.boolean
canUndo()
Checks whether an undo action is available.boolean
checkForModified()
Returns whether we can proceed with the operation or not, depending on whether the user saved the content or discarded the changes.void
clear()
Removes all content.void
copy()
Copies the currently selected text to the clipboard.void
cut()
Cuts the currently selected text and places it on the clipboard.void
find()
Initiates a search.void
findNext()
Finds the next occurrence.Caret
getCaret()
Fetches the caret that allows text-oriented navigation over the view.int
getCaretPosition()
Returns the current position of the cursor.String
getContent()
Returns the content to display.String
getCurrentEncoding()
Returns the current file encoding.File
getCurrentFile()
Returns the currently loaded file.String
getCustomSupplyTextMenuItemCaption()
Returns the text for the menu item.ExtensionFileFilter
getCustomTextFileFilter()
Returns a custom file filter for the file chooser.Document
getDocument()
Returns the underlying document of the text area.protected TextFileChooser
getFileChooser()
Returns the file chooser and creates it if necessary.String
getLastFind()
Returns the last search string.boolean
getLineWrap()
Returns whether line wrap is enabled.PopupMenuCustomizer<TextEditorPanel>
getPopupMenuCustomizer()
Returns the customizer in use.String
getSelectedText()
Returns the selected text contained in thisTextComponent
.int
getSelectionEnd()
Returns the selected text's end position.int
getSelectionStart()
Returns the selected text's start position.int
getTabSize()
Returns the tab size, i.e., the number of maximum width characters.String
getText()
Returns the text contained in thisTextComponent
.BaseTextArea
getTextArea()
Returns the underlying BaseTextArea element.Font
getTextFont()
Returns the font currently in use by the text area.boolean
getWrapStyleWord()
Gets the style of wrapping used if the text area is wrapping lines.protected void
initGUI()
For initializing the GUI.protected void
initialize()
For initializing members.boolean
isEditable()
Returns whether the text area is editable or not.boolean
isModified()
Returns whether the content has been modified.protected void
notifyChangeListeners()
Sends an event to all change listeners.boolean
open()
Pops up dialog to open a file.boolean
open(File file)
Opens the specified file and loads/displays the content.boolean
open(File file, String encoding)
Opens the specified file and loads/displays the content.void
paste()
Pastes the text from the clipboard into the document.void
printText()
Pops up a print dialog.void
redo()
Performs a redo, if possible.void
removeChangeListener(ChangeListener l)
Removes the given change listener from its internal list.void
save()
Pops up dialog to save the content in a file if no filename provided, otherwise saves the .protected void
save(File file, String encoding)
Saves the content under the specified file.void
saveAs()
Pops up dialog to save the content in a file.void
selectAll()
Selects all the text.void
selectFont()
Pops up a dialog for selecting the font.void
setCaret(Caret c)
Sets the caret to be used.void
setCaretPosition(int value)
Sets the position of the cursor.void
setContent(String value)
Sets the content to display.void
setEditable(boolean value)
Sets whether the text area is editable or not.void
setLineWrap(boolean value)
Enables/disables line wrap.void
setModified(boolean value)
Sets the modified state.void
setPopupMenuCustomizer(PopupMenuCustomizer<TextEditorPanel> value)
Sets the customizer to use.void
setSelectionEnd(int selectionEnd)
Sets the selection end to the specified position.void
setSelectionStart(int selectionStart)
Sets the selection start to the specified position.void
setTabSize(int value)
Sets the tab size, i.e., the number of maximum width characters.void
setText(String t)
Sets the text of thisTextComponent
to the specified text.void
setTextFont(Font value)
Sets the font of the text area.void
setWrapStyleWord(boolean word)
Sets the style of wrapping used if the text area is wrapping lines.protected void
showPopupMenu(MouseEvent e)
Shows the popup menu for the text area.String
supplyText()
Supplies the text.void
undo()
Performs an undo, if possible.-
Methods inherited from class adams.gui.core.BasePanel
afterHide, afterShow, beforeHide, beforeShow, closeParent, finishInit, getParentChild, getParentDialog, getParentFrame, getParentInternalFrame, getParentTitle, initFileChooser, main, printErrorMessage, printException, saveComponent, setEnabledCascade, setEnabledCascade, setParentTitle, setVisible
-
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, 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, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, 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, 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, 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
-
-
-
-
Field Detail
-
m_TextArea
protected TextEditorPanel.TextEditorArea m_TextArea
for displaying the text.
-
m_Modified
protected boolean m_Modified
whether the content was modified.
-
m_IgnoreChanges
protected boolean m_IgnoreChanges
whether to ignore changes.
-
m_FileChooser
protected transient TextFileChooser m_FileChooser
for saving the content.
-
m_Undo
protected UndoManager m_Undo
for managing undo/redo.
-
m_LastFind
protected String m_LastFind
the last search string used.
-
m_ChangeListeners
protected HashSet<ChangeListener> m_ChangeListeners
the listeners for modification events.
-
m_CurrentFile
protected File m_CurrentFile
the current file.
-
m_CurrentEncoding
protected String m_CurrentEncoding
the current file encoding.
-
m_PopupMenuCustomizer
protected PopupMenuCustomizer<TextEditorPanel> m_PopupMenuCustomizer
for customizing the popup menu.
-
-
Method Detail
-
initialize
protected void initialize()
For initializing members.- Overrides:
initialize
in classBasePanel
-
getFileChooser
protected TextFileChooser getFileChooser()
Returns the file chooser and creates it if necessary.- Returns:
- the file chooser
-
setModified
public void setModified(boolean value)
Sets the modified state. If false, all edits are discarded and the last search string reset as well.- Parameters:
value
- if true then the content is flagged as modified
-
isModified
public boolean isModified()
Returns whether the content has been modified.- Returns:
- true if the content was modified
-
setContent
public void setContent(String value)
Sets the content to display. Resets the modified state.- Parameters:
value
- the text
-
getContent
public String getContent()
Returns the content to display.- Returns:
- the text
-
append
public void append(String str)
Appends the text at the end.- Parameters:
str
- the text to append
-
setEditable
public void setEditable(boolean value)
Sets whether the text area is editable or not.- Parameters:
value
- if true then the text will be editable
-
isEditable
public boolean isEditable()
Returns whether the text area is editable or not.- Returns:
- true if the text is editable
-
setTextFont
public void setTextFont(Font value)
Sets the font of the text area.- Parameters:
value
- the font to use
-
getTextFont
public Font getTextFont()
Returns the font currently in use by the text area.- Returns:
- the font in use
-
getLastFind
public String getLastFind()
Returns the last search string.- Returns:
- the last search string, can be null if no search performed yet
-
getTextArea
public BaseTextArea getTextArea()
Returns the underlying BaseTextArea element.- Returns:
- the component
-
getDocument
public Document getDocument()
Returns the underlying document of the text area.- Returns:
- the document
-
setCaretPosition
public void setCaretPosition(int value)
Sets the position of the cursor.- Parameters:
value
- the position
-
getCaretPosition
public int getCaretPosition()
Returns the current position of the cursor.- Returns:
- the cursor position
-
setTabSize
public void setTabSize(int value)
Sets the tab size, i.e., the number of maximum width characters.- Parameters:
value
- the number of maximum width chars
-
getTabSize
public int getTabSize()
Returns the tab size, i.e., the number of maximum width characters.- Returns:
- the number of maximum width chars
-
setLineWrap
public void setLineWrap(boolean value)
Enables/disables line wrap.- Parameters:
value
- if true line wrap gets enabled
-
getLineWrap
public boolean getLineWrap()
Returns whether line wrap is enabled.- Returns:
- true if line wrap enabled
-
setWrapStyleWord
public void setWrapStyleWord(boolean word)
Sets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries. By default this property is false.- Parameters:
word
- indicates if word boundaries should be used for line wrapping- See Also:
getWrapStyleWord()
-
getWrapStyleWord
public boolean getWrapStyleWord()
Gets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (ie whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries.- Returns:
- if the wrap style should be word boundaries instead of character boundaries
- See Also:
setWrapStyleWord(boolean)
-
checkForModified
public boolean checkForModified()
Returns whether we can proceed with the operation or not, depending on whether the user saved the content or discarded the changes.- Returns:
- true if safe to proceed
-
open
public boolean open()
Pops up dialog to open a file.- Returns:
- true if successfully opened
-
open
public boolean open(File file)
Opens the specified file and loads/displays the content.- Parameters:
file
- the file to load- Returns:
- true if successfully opened
-
open
public boolean open(File file, String encoding)
Opens the specified file and loads/displays the content.- Parameters:
file
- the file to loadencoding
- the encoding to use, use null or empty string for default UTF-8- Returns:
- true if successfully opened
-
save
public void save()
Pops up dialog to save the content in a file if no filename provided, otherwise saves the .
-
saveAs
public void saveAs()
Pops up dialog to save the content in a file.
-
save
protected void save(File file, String encoding)
Saves the content under the specified file.- Parameters:
file
- the file to save the content inencoding
- the file encoding to use
-
clear
public void clear()
Removes all content. Does not reset the undos.
-
canUndo
public boolean canUndo()
Checks whether an undo action is available.- Returns:
- true if an undo action is available
-
undo
public void undo()
Performs an undo, if possible.
-
canRedo
public boolean canRedo()
Checks whether a redo action is available.- Returns:
- true if a redo action is available
-
redo
public void redo()
Performs a redo, if possible.
-
canCut
public boolean canCut()
Checks whether text can be cut at the moment.- Returns:
- true if text is available for cutting
-
cut
public void cut()
Cuts the currently selected text and places it on the clipboard.
-
canCopy
public boolean canCopy()
Checks whether text can be copied at the moment.- Returns:
- true if text is available for copying
-
copy
public void copy()
Copies the currently selected text to the clipboard.
-
canPaste
public boolean canPaste()
Checks whether text can be pasted at the moment.- Returns:
- true if text is available for pasting
-
paste
public void paste()
Pastes the text from the clipboard into the document.
-
selectAll
public void selectAll()
Selects all the text.
-
find
public void find()
Initiates a search.
-
findNext
public void findNext()
Finds the next occurrence.
-
printText
public void printText()
Pops up a print dialog.
-
selectFont
public void selectFont()
Pops up a dialog for selecting the font.
-
getCurrentFile
public File getCurrentFile()
Returns the currently loaded file.- Returns:
- the current file, null if none loaded
-
getCurrentEncoding
public String getCurrentEncoding()
Returns the current file encoding.- Returns:
- the current encoding, null if no file loaded
-
addChangeListener
public void addChangeListener(ChangeListener l)
Adds the given change listener to its internal list.- Parameters:
l
- the listener to add
-
removeChangeListener
public void removeChangeListener(ChangeListener l)
Removes the given change listener from its internal list.- Parameters:
l
- the listener to remove
-
notifyChangeListeners
protected void notifyChangeListeners()
Sends an event to all change listeners.
-
setPopupMenuCustomizer
public void setPopupMenuCustomizer(PopupMenuCustomizer<TextEditorPanel> value)
Sets the customizer to use.- Parameters:
value
- the customizer, null to unset
-
getPopupMenuCustomizer
public PopupMenuCustomizer<TextEditorPanel> getPopupMenuCustomizer()
Returns the customizer in use.- Returns:
- the customizer, null if none set
-
showPopupMenu
protected void showPopupMenu(MouseEvent e)
Shows the popup menu for the text area.- Parameters:
e
- the event that triggered the action
-
getCustomSupplyTextMenuItemCaption
public String getCustomSupplyTextMenuItemCaption()
Returns the text for the menu item.- Specified by:
getCustomSupplyTextMenuItemCaption
in interfaceTextSupplier
- Returns:
- the menu item text, null for default
-
getCustomTextFileFilter
public ExtensionFileFilter getCustomTextFileFilter()
Returns a custom file filter for the file chooser.- Specified by:
getCustomTextFileFilter
in interfaceTextSupplier
- Returns:
- the file filter, null if to use default one
-
supplyText
public String supplyText()
Supplies the text.- Specified by:
supplyText
in interfaceTextSupplier
- Specified by:
supplyText
in interfaceTextSupporter
- Returns:
- the text, null if none available
-
setText
public void setText(String t)
Sets the text of thisTextComponent
to the specified text. If the text isnull
or empty, has the effect of simply deleting the old text. When text has been inserted, the resulting caret location is determined by the implementation of the caret class.Note that text is not a bound property, so no
PropertyChangeEvent
is fired when it changes. To listen for changes to the text, useDocumentListener
.- Parameters:
t
- the new text to be set- See Also:
getText()
-
getText
public String getText()
Returns the text contained in thisTextComponent
. If the underlying document isnull
, will give aNullPointerException
. Note that text is not a bound property, so noPropertyChangeEvent
is fired when it changes. To listen for changes to the text, useDocumentListener
.- Returns:
- the text
- Throws:
NullPointerException
- if the document isnull
- See Also:
setText(java.lang.String)
-
getSelectedText
public String getSelectedText()
Returns the selected text contained in thisTextComponent
. If the selection isnull
or the document empty, returnsnull
.- Returns:
- the text
- Throws:
IllegalArgumentException
- if the selection doesn't have a valid mapping into the document for some reason
-
getSelectionStart
public int getSelectionStart()
Returns the selected text's start position. Return 0 for an empty document, or the value of dot if no selection.- Returns:
- the start position ≥ 0
-
setSelectionStart
public void setSelectionStart(int selectionStart)
Sets the selection start to the specified position. The new starting point is constrained to be before or at the current selection end.This is available for backward compatibility to code that called this method on
java.awt.TextComponent
. This is implemented to forward to theCaret
implementation which is where the actual selection is maintained.- Parameters:
selectionStart
- the start position of the text ≥ 0
-
getSelectionEnd
public int getSelectionEnd()
Returns the selected text's end position. Return 0 if the document is empty, or the value of dot if there is no selection.- Returns:
- the end position ≥ 0
-
setSelectionEnd
public void setSelectionEnd(int selectionEnd)
Sets the selection end to the specified position. The new end point is constrained to be at or after the current selection start.This is available for backward compatibility to code that called this method on
java.awt.TextComponent
. This is implemented to forward to theCaret
implementation which is where the actual selection is maintained.- Parameters:
selectionEnd
- the end position of the text ≥ 0
-
getCaret
public Caret getCaret()
Fetches the caret that allows text-oriented navigation over the view.- Returns:
- the caret
-
setCaret
public void setCaret(Caret c)
Sets the caret to be used. By default this will be set by the UI that gets installed. This can be changed to a custom caret if desired. Setting the caret results in a PropertyChange event ("caret") being fired.- Parameters:
c
- the caret- See Also:
getCaret()
-
-