- All Implemented Interfaces:
ImageObserver
,MenuContainer
,Serializable
,Appendable
Appendable
interface, which allows text to be added. The class
AppendableWriter
can be used to create a
Writer
that in turn can be used to create a
PrintWriter
that will simplify creating
formatted text:
SimpleConsole console = new SimpleConsole();
// .... add this component to a frame
PrintWriter w = new PrintWriter(new AppendableWriter(console));
The class SwingErrorMessage
can be used to create error messages
and can be configured to pass those messages to an instance of
this class. The methods that SwingErrorMessage
provides are all
static methods so that error-printing code does not have to keep
explicitly keep track of where a message should be displayed.
For use with a GUI, the following code will create a menu item that
will make a console visible:
This code will create a menu named "Tools" with an item named "Open Console", which will open a window whose title is "Console" with a width of 800 pixels and a height of 600 pixels. The console window can be resized. The SimpleConsole component itself includes a button to clear the contents of the console. The linesJFrame frame = new JFrame("Application Frame"); menubar = new JMenuBar(); menu = new JMenu("Tools"); ... SimpleConsole console = new SimpleConsole(); JMenuItem consoleMenuItem = console.createMenuItem("Open Console", "Console", 800, 600); menu.add(consoleMenuItem); ... menubar.add(menu); frame.setJMenuBar(menubar); frame.setSize(...,...); frame.setVisible(true); SwingErrorMessage.setAppendable(console); SwingErrorMessage.setComponent(frame);
SwingErrorMessage.setAppendable(console);
SwingErrorMessage.setComponent(frame);
result in SwingErrorMessage output going to the console, and with messages
that should be shown in a dialog box being displayed in a dialog box
centered on the application frame. When SwingErrorMessage is used, one
will most likely add a menu item to turn stack traces for exceptions
on and off:
JMenuItem stackTraceMenuItem =
new StackTraceMenuItem("Show Stacktrace");
menu.add(stackTraceMenuItem);
This class makes use of the static method
SwingUtilities.invokeLater(Runnable)
internally. One should
avoid the use of synchronized methods that call methods in this
class when those synchronized methods might be called from tasks
waiting on the AWT event dispatch queue, as there is a possibility
of deadlock: If for some class methods m1 and m2 are synchronized
and call one of the methods in this class, and m1 is called, a call
to SwingUtilities.invokeLater(Runnable)
may process other
entries on its event queue first, causing m2 to be called, but m2
will wait until m1 returns, which cannot occur until m2 returns.
While the SimpleConsole class has Java Swing components
associated with it, the newFramedInstance methods are thread safe -
their use is not restricted to the event dispatch
thread. Consequently, it is easy to create a command-line program
that will open a window to display its output and exit when that
window is closed. Unlike AnimatedPanelGraphics
and
PanelGraphics
, the constructors for this class, and the
method createMenuItem(String,String,int,int)
,
are not thread safe: these methods must be run on the event
dispatch thread as is the standard requirement for Java Swing
components.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
Class to determine how an application can exit, even when a security manager is installed, given a window created withnewFramedInstance(int,int,String,boolean,ExitAccessor)
is closed.static enum
Mode determining what happens when a frame created bynewFramedInstance(int,int,String,boolean,SimpleConsole.ExitMode)
closes.static class
SimpleJTextPane runtime-exception class.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 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 -
Method Summary
Modifier and TypeMethodDescriptionvoid
addCloseAccelerator
(int keycode, int modifiers, int mask) Add a keyboard accelerator that will close a console window.void
Add a separator.void
Add separator if needed.append
(char c) Append a character to the end of the component's document.append
(CharSequence csq) Append text to the end of the component's document.append
(CharSequence csq, int start, int end) Append text to the end of the component's document.createMenuItem
(String label, String title, int width, int height) Create a new menu item that will open a frame containing this console.Get the background color for the console.Get the text pane used for this console.getFrame()
Get this console's frame.Get the color for a separator.Get the background color for subsequently inserted or appended text.Get the color of subsequently inserted or appended text.boolean
Determine if there is new text to display since the the last separator was added.boolean
isBold()
Determine if newly inserted text will use a bold font.boolean
isItalic()
Determine if newly inserted text will be in italics.static SimpleConsole
newFramedInstance
(int width, int height, String title, boolean visibility) Create a console with a surrounding frame.static SimpleConsole
newFramedInstance
(int width, int height, String title, boolean visibility, SimpleConsole.ExitAccessor accessor) Create a console with a surrounding frame and option to exit based on an exit accessor.static SimpleConsole
newFramedInstance
(int width, int height, String title, boolean visibility, SimpleConsole.ExitMode exit) Create a console with a surrounding frame, specifying an exit policy.void
Run a sequence of operations atomically.void
setBackground
(Color bg) Set the background color for the console.void
setBold
(boolean value) Set the font weight for subsequently inserted text to either normal or bold.void
setItalic
(boolean value) Set the font slant for subsequently inserted text.void
Set the color for the separator.void
Set the background color for new text.void
Set the text color for new text.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, getUI, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, 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, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
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, getAccessibleContext, 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
-
SimpleConsole
public SimpleConsole()Constructor.
-
-
Method Details
-
getConsole
Get the text pane used for this console. This text pane is needed occassionally for purposes such as installing a key listener.- Returns:
- the text pane
-
addCloseAccelerator
public void addCloseAccelerator(int keycode, int modifiers, int mask) Add a keyboard accelerator that will close a console window. This method will not have any effect if called before a console is associated with a window (e.g., by callingcreateMenuItem(String,String,int,int)
).It should be used if an accelerator is desired when the window containing the console was created with
createMenuItem(String,String,int,int)
. It should not be necessary if the window containing theSimpleConsole
has a suitable menu item, with an accelerator, installed.- Parameters:
keycode
- the keycodemodifiers
- the modifiersmask
- the mask- See Also:
-
perform
Run a sequence of operations atomically. The argument c is typically a lambda express that will be called with its single argument set to the SimpleJTextPane that this console uses to display its output. Because this method is run on the event dispatch queue, the operations the lambda expression performs will not be interleaved with calls from other threads. Alternatively, one can implement the consumer's accept method instead of using a lambda expression. Any changes to this console's attributes will be restored when this method exits.This method is thread safe.
- Parameters:
c
- the consumer
-
append
Append a character to the end of the component's document.This method is thread safe.
- Specified by:
append
in interfaceAppendable
- Parameters:
c
- the character to append- Returns:
- the current object cast as an Appendable
-
append
Append text to the end of the component's document.This method is thread safe.
- Specified by:
append
in interfaceAppendable
- Parameters:
csq
- the text to append- Returns:
- the current object cast as an Appendable
-
append
Append text to the end of the component's document.This method is thread safe.
- Specified by:
append
in interfaceAppendable
- Parameters:
csq
- a CharSequence containing the text to appendstart
- the offset to the start of the text in csqend
- the position just past the end of the text to in csq to append- Returns:
- the current object cast as an Appendable
-
hasNewTextToDisplay
public boolean hasNewTextToDisplay()Determine if there is new text to display since the the last separator was added.This method is thread safe.
- Returns:
- true if there is text after the last separator; false if there is no text after the last separator
-
addSeparatorIfNeeded
public void addSeparatorIfNeeded()Add separator if needed.This method is thread safe.
-
getSeparatorColor
Get the color for a separator.This method is thread safe.
- Returns:
- the color for the separator
-
setSeparatorColor
Set the color for the separator.This method is thread safe.
- Parameters:
c
- the color
-
addSeparator
public void addSeparator()Add a separator. -
getFrame
Get this console's frame.If
createMenuItem(String,String,int,int)
is used, a frame will be created if necessary (with restrictions). The main reason to call this method otherwise is to programmatically resize a frame or so thatWindow.setIconImages(java.util.List<? extends java.awt.Image>)
can be called.- Returns:
- the console's frame; null if it does not have one.
-
newFramedInstance
public static SimpleConsole newFramedInstance(int width, int height, String title, boolean visibility) Create a console with a surrounding frame. When the frame is closed, it will no longer be visible. This method must be called on the event dispatch thread. Its documented behavior could be altered if the caller adds additional window listeners.- Parameters:
width
- the width of the console in pointsheight
- the height of the console in pointstitle
- the title of the framevisibility
- true if the frame is initially visible; false otherwise.- Returns:
- a console whose pane is a component of a JFrame.
- See Also:
-
newFramedInstance
public static SimpleConsole newFramedInstance(int width, int height, String title, boolean visibility, SimpleConsole.ExitMode exit) Create a console with a surrounding frame, specifying an exit policy. The exit policy is describe by the documentation for the enumeration typeSimpleConsole.ExitMode
. This method must be called on the event dispatch thread. Its documented behavior could be altered if the caller adds additional window listeners.- Parameters:
width
- the width of the console in pointsheight
- the height of the console in pointstitle
- the title of the framevisibility
- true if the frame is initially visible; false otherwise.exit
- the exit mode- Returns:
- a console whose pane is a component of a JFrame.
- See Also:
-
newFramedInstance
public static SimpleConsole newFramedInstance(int width, int height, String title, boolean visibility, SimpleConsole.ExitAccessor accessor) Create a console with a surrounding frame and option to exit based on an exit accessor. If the exit accessor argument was created when no security manager is installed, closing the frame will cause the application to exit. If the exit accessor argument was created when a security manager is installed, closing the frame will result in the appearance of a dialog box asking if the application should exit, and canceling that operation will result in the window being reopened (i.e., becoming visible again).This method must be called on the event dispatch thread. Its documented behavior could be altered if the caller adds additional window listeners.
- Parameters:
width
- the width of the console in pointsheight
- the height of the console in pointstitle
- the title of the framevisibility
- true if the frame is initially visible; false otherwise.accessor
- an exit accessor, used to determine how and if an application exits when a console's frame is closed- Returns:
- a console whose pane is a component of a JFrame.
- See Also:
-
createMenuItem
public JMenuItem createMenuItem(String label, String title, int width, int height) throws IllegalStateException Create a new menu item that will open a frame containing this console.This method will provide a frame for this console if such a frame does not already exist. This method must not be called if the console was added to a component and does not have a JFrame as an ancestor. Otherwise it may be called multiple times (e.g., to add a menu item to open a console in multiple windows).
- Parameters:
label
- the label to use for the menu itemtitle
- the title to use if a new frame is createdwidth
- the minimum frame-width to use (if there is an existing frame width that is larger, that will be used instead)height
- the minimum frame-height to use (if there is an existing frame height that is larger, that will be used instead)- Returns:
- the menu item for this console
- Throws:
IllegalStateException
- the console was added to a component but does not have a frame
-
isBold
public boolean isBold()Determine if newly inserted text will use a bold font.This method is thread safe.
- Returns:
- true if newly inserted text will be bold; false otherwise
-
setBold
public void setBold(boolean value) Set the font weight for subsequently inserted text to either normal or bold.This method is thread safe.
- Parameters:
value
- true if the font is bold; false if not.
-
isItalic
public boolean isItalic()Determine if newly inserted text will be in italics.This method is thread safe.
- Returns:
- true if newly inserted text will be in italics; false otherwise
-
setItalic
public void setItalic(boolean value) Set the font slant for subsequently inserted text.This method is thread safe.
- Parameters:
value
- true if the font is italic; false if not.
-
getTextForeground
Get the color of subsequently inserted or appended text.This method is thread safe.
- Returns:
- The color that will be used for new text.
-
setTextForeground
Set the text color for new text.This method is thread safe.
- Parameters:
fg
- the color for subsequently inserted or appended text.
-
getTextBackground
Get the background color for subsequently inserted or appended text.This method is thread safe.
- Returns:
- the color that will be used for the background for new text.
-
setTextBackground
Set the background color for new text.This method is thread safe.
- Parameters:
bg
- the background color for subsequently inserted or appended text.
-
getBackground
Get the background color for the console.- Overrides:
getBackground
in classComponent
- Returns:
- the background color
-
setBackground
Set the background color for the console.- Overrides:
setBackground
in classJComponent
- Parameters:
bg
- the background color for subsequently inserted or appended text.
-