Package com.coswald.jtalker.gui
Class ColoredTextPane
- java.lang.Object
-
- java.awt.Component
-
- java.awt.Container
-
- javax.swing.JComponent
-
- javax.swing.text.JTextComponent
-
- javax.swing.JEditorPane
-
- javax.swing.JTextPane
-
- com.coswald.jtalker.gui.ColoredTextPane
-
- All Implemented Interfaces:
ImageObserver
,MenuContainer
,Printable
,Serializable
,Accessible
,Scrollable
public class ColoredTextPane extends JTextPane implements Printable
A
JTextPane
that supports ANSI colors. This pane adds anappend
method that will append a given string to the pane; however, it will also understand certain ANSI color codes and manipulate the pane to these colors. See theconstants
class to see what codes have been interpreted by this pane. This also makes the pane ignore word wrap.The method for which ANSI color codes can be derived was mainly received by this stack overflow question. However, we have since improved on it. When you display the pane, it will look like this:
- Since:
- JTalker 0.1.5
- Version:
- 0.0.1
- Author:
- C. William Oswald
- See Also:
ANSIColorConstants
, 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.DropLocation, 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.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
-
Field Summary
Fields Modifier and Type Field Description protected Color
currentColor
The current color we are using when we are scanning.protected boolean
isBackground
Whether the current color is a background color.protected StringBuffer
typed
A history of what has beenappended
.-
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
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
-
Fields inherited from interface java.awt.print.Printable
NO_SUCH_PAGE, PAGE_EXISTS
-
-
Constructor Summary
Constructors Constructor Description ColoredTextPane()
Constructs aColoredTextPane
.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
append(String s)
Appends the given text to the pane.protected void
append(String s, Color c, boolean background)
Appends the text to the pane using the given color.boolean
getColorMode()
Returns whether colors have been enabled with the text pane.String
getHistory()
Returns all of the text that has been appended to this pane.boolean
getScrollableTracksViewportWidth()
Returnstrue
if a viewport should always force the width of thisScrollable
to match the width of the viewport.int
print(Graphics g, PageFormat format, int pageIndex)
Prints the given page.void
setColorMode(boolean colorMode)
Sets the new color mode.void
setText(String text)
Sets the text of thisColoredTextPane
, which is expected to be in the format of the content type of this editor.-
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, getStream, getText, read, registerEditorKitForContentType, registerEditorKitForContentType, removeHyperlinkListener, scrollToReference, setContentType, setEditorKitForContentType, setPage, setPage
-
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, modelToView2D, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, viewToModel2D, 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, 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, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, 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, 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, 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, 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, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
-
-
-
Field Detail
-
currentColor
protected Color currentColor
The current color we are using when we are scanning. This is an instance variable because theappend
method needs a variable to store where it is at while scanning the string. This can be a background color or a foreground color, as determined byisBackground
.
-
isBackground
protected boolean isBackground
Whether the current color is a background color. This is an instance variable because theappend
method needs a variable to store whether the current color is a background color while scanning the string.
-
typed
protected StringBuffer typed
A history of what has beenappended
.
-
-
Method Detail
-
getScrollableTracksViewportWidth
public boolean getScrollableTracksViewportWidth()
Returnstrue
if a viewport should always force the width of thisScrollable
to match the width of the viewport.- Specified by:
getScrollableTracksViewportWidth
in interfaceScrollable
- Overrides:
getScrollableTracksViewportWidth
in classJEditorPane
- Returns:
false
if theComponentUI
's preferred width is less than or equal to the parents width,true
otherwise.
-
print
public int print(Graphics g, PageFormat format, int pageIndex)
Prints the given page. This will use the current graphics on the pane and draw them on a buffered image, which will be sent to the printer service. This will not print everything that has been appended to the colored text pane; it will only print what is currently displayed.
-
setText
public void setText(String text)
Sets the text of thisColoredTextPane
, which is expected to be in the format of the content type of this editor. To see the exact exact documentation, visitthis
link. We needed to override this method due to our coloring of the pane. With this in mind, we do callsuper.setText(text)
at the end of oursetText
method. However, we have to ensure that the color state is only preserved to our current state of color (not what our selection contains).- Overrides:
setText
in classJEditorPane
- Parameters:
text
- The new text to be set; ifnull
the old text will be deleted.
-
append
public void append(String s)
Appends the given text to the pane. This string may contain ANSI color codes; we interpret them and change the pane accordingly.- Parameters:
s
- The string that may contain ANSI color codes.
-
getColorMode
public boolean getColorMode()
Returns whether colors have been enabled with the text pane.- Returns:
- Whether colors have been enabled with the text pane.
-
getHistory
public String getHistory()
Returns all of the text that has been appended to this pane. This is stored within aStringBuffer
, and text is added to this buffer whenever theappend
method is called. This will save any ANSI escape codes sent to it.- Returns:
- All of the text that has been appended to this pane.
- See Also:
StringBuffer
-
setColorMode
public void setColorMode(boolean colorMode)
Sets the new color mode. If this isfalse
, this will disable any colors that have been drawn. It will also redraw the text as it came in the pane (if the mode has been changed).- Parameters:
colorMode
- The new color mode (true
for colors enabled).
-
append
protected void append(String s, Color c, boolean background)
Appends the text to the pane using the given color. This is the main backbone to theappend
method. This will use the given color (and whether it is a background color) and the currentAttributeSet
to draw the given text.- Parameters:
s
- The text to draw.c
- The color of the text.background
- Whether this is a background or foreground color.
-
-