jwo.utils.syntaxhighlighter
Class SyntaxHighlighter

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.text.JTextComponent
                  extended by javax.swing.JEditorPane
                      extended by javax.swing.JTextPane
                          extended by jwo.utils.gui.SmoothedTextPane
                              extended by jwo.utils.syntaxhighlighter.SyntaxHighlighter
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, EventListener, Accessible, DocumentListener, Scrollable, TokenTypes

public class SyntaxHighlighter
extends SmoothedTextPane
implements DocumentListener, TokenTypes

Displays text with syntax highlighting. Highlighting is carried out using a given language scanner. Large amounts of re-highlighting are carried out in small bursts to make sure the user interface doesn't freeze.

Version:
1.0, February, 2006 modified 2nd December, 2008.
Author:
Henk Muller, with some modifications, Jo Wood.
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JEditorPane
JEditorPane.AccessibleJEditorPane, JEditorPane.AccessibleJEditorPaneHTML, JEditorPane.JEditorPaneAccessibleHypertextSupport
 
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.KeyBinding
 
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
 
Fields inherited from class javax.swing.JEditorPane
HONOR_DISPLAY_PROPERTIES, W3C_LENGTH_UNITS
 
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
 
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 jwo.utils.syntaxhighlighter.TokenTypes
BRACKET, CHARACTER, COMMENT, END_COMMENT, END_TAG, IDENTIFIER, KEYWORD, KEYWORD2, LITERAL, MID_COMMENT, NUMBER, OPERATOR, PUNCTUATION, SEPARATOR, START_COMMENT, STRING, TAG, typeNames, UNRECOGNIZED, URL, WHITESPACE, WORD
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
SyntaxHighlighter(int height, int width, Scanner scanner)
          Creates a graphics component which displays text with syntax highlighting.
 
Method Summary
 void changedUpdate(DocumentEvent e)
          Ignore this method.
 void changeFont(Font font)
          Changes the component's font and changes the size of the component to match.
 void changeStyle(int type, Color colour, int fontStyle)
          Changes the style of a particular type of token, including adding bold or italic using a third argument of Font.BOLD or Font.ITALIC or the bitwise union Font.BOLD|Font.ITALIC.
 void changeStyle(int type, String styleText)
          Changes the style of a particular type of token assuming colour is defined by an rgb hex string. e.g.
 boolean hasChanged()
          Indicates whether or not any changes have occurred to the text held in this panel.
 void insertUpdate(DocumentEvent e)
          Ignore this method.
protected  void paintComponent(Graphics g)
          Ignore this method.
 void read(Reader in, Object desc)
          Reads new text into the component from a Reader.
 void removeUpdate(DocumentEvent e)
          Ignore this method.
 void resetChanges()
          Resets the change monitor.
 void setFontSize(float fontSize)
          Changes the font size to the given value.
 void setStyles(Properties props)
          Sets the styles associated with each token type from the given properties list.
 void setTabWidth(int numChars)
          Sets the tab stop width.
 void updateAll()
          Updates the entire contents to be displayed.
 
Methods inherited from class jwo.utils.gui.SmoothedTextPane
setSmoothText
 
Methods inherited from class javax.swing.JTextPane
addStyle, createDefaultEditorKit, getCharacterAttributes, getInputAttributes, getLogicalStyle, getParagraphAttributes, getStyle, getStyledDocument, getStyledEditorKit, getUIClassID, insertComponent, insertIcon, paramString, removeStyle, replaceSelection, setCharacterAttributes, setDocument, setEditorKit, setLogicalStyle, setParagraphAttributes, setStyledDocument
 
Methods inherited from class javax.swing.JEditorPane
addHyperlinkListener, createEditorKitForContentType, fireHyperlinkUpdate, getAccessibleContext, getContentType, getEditorKit, getEditorKitClassNameForContentType, getEditorKitForContentType, getHyperlinkListeners, getPage, getPreferredSize, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getStream, getText, read, registerEditorKitForContentType, registerEditorKitForContentType, removeHyperlinkListener, scrollToReference, setContentType, setEditorKitForContentType, setPage, setPage, setText
 
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, processInputMethodEvent, removeCaretListener, removeKeymap, removeNotify, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, write
 
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, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, 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, 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, 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, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, 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
 

Constructor Detail

SyntaxHighlighter

public SyntaxHighlighter(int height,
                         int width,
                         Scanner scanner)
Creates a graphics component which displays text with syntax highlighting.

Parameters:
width - Width of component measured in characters.
height - Height of component in characters
scanner - Language scanner to use.
Method Detail

setStyles

public void setStyles(Properties props)
Sets the styles associated with each token type from the given properties list.

Parameters:
props - Style properties list. If any given token type is not defined in the properties list, style defaults to plain black text.

resetChanges

public void resetChanges()
Resets the change monitor. After this method is called, the text will have to be changed before hasChanged() will indicate any changes have been made.


hasChanged

public boolean hasChanged()
Indicates whether or not any changes have occurred to the text held in this panel. Can be reset with resetChanges().

Returns:
True if changes to the text have been made since the last reset or creation of this object.

changeFont

public void changeFont(Font font)
Changes the component's font and changes the size of the component to match.

Parameters:
font - New font to use.

setFontSize

public void setFontSize(float fontSize)
Changes the font size to the given value. Will cap new font size between readable limits.

Overrides:
setFontSize in class SmoothedTextPane
Parameters:
fontSize - New size of font.

setTabWidth

public void setTabWidth(int numChars)
Sets the tab stop width.

Parameters:
numChars - Width of each tab stop expressed as number of characters.

read

public void read(Reader in,
                 Object desc)
          throws IOException
Reads new text into the component from a Reader. Overrides read in JTextComponent in order to highlight the new text.

Overrides:
read in class JTextComponent
Parameters:
in - Input stream from which to process text.
desc - Object describing the stream.
Throws:
IOException - if there is a problem getting text from the input stream.

changeStyle

public void changeStyle(int type,
                        String styleText)
Changes the style of a particular type of token assuming colour is defined by an rgb hex string. e.g. ee0033. Can also include comma separated styles bold and/or italic. e.g. ee0033,bold,italic.

Parameters:
type - Type of token to change.
styleText - New colour/style to be associated with token type.

changeStyle

public void changeStyle(int type,
                        Color colour,
                        int fontStyle)
Changes the style of a particular type of token, including adding bold or italic using a third argument of Font.BOLD or Font.ITALIC or the bitwise union Font.BOLD|Font.ITALIC.

Parameters:
type - Type of token to change.
colour - New colour to be associated with token type.
fontStyle - New font style to be associated with token type.

updateAll

public void updateAll()
Updates the entire contents to be displayed.


insertUpdate

public void insertUpdate(DocumentEvent e)
Ignore this method. Responds to the underlying document changes by re-highlighting.

Specified by:
insertUpdate in interface DocumentListener
Parameters:
e - Contains the document change.

removeUpdate

public void removeUpdate(DocumentEvent e)
Ignore this method. Responds to the underlying document changes by re-highlighting.

Specified by:
removeUpdate in interface DocumentListener
Parameters:
e - Contains the document change.

changedUpdate

public void changedUpdate(DocumentEvent e)
Ignore this method. Responds to the underlying document changes by re-highlighting.

Specified by:
changedUpdate in interface DocumentListener
Parameters:
e - Contains the document change (ignored in this case).

paintComponent

protected void paintComponent(Graphics g)
Ignore this method. Carries out a small amount of re-highlighting for each call to repaint.

Overrides:
paintComponent in class SmoothedTextPane
Parameters:
g - Graphics context.


Copyright Jo Wood, 1996-2009, last modified, 17th April, 2009