net.sourceforge.webcompmath.awt
Class ExpressionInput

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.JTextField
                      extended by net.sourceforge.webcompmath.awt.ExpressionInput
All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible, javax.swing.event.DocumentListener, javax.swing.Scrollable, javax.swing.SwingConstants, InputObject, Value
Direct Known Subclasses:
WCMExpressionInputBean

public class ExpressionInput
extends javax.swing.JTextField
implements InputObject, Value, java.awt.event.ActionListener, javax.swing.event.DocumentListener

An ExpressionInput is an input box that allows the user input a mathematical expression. There is an associated object that belongs to the class Expression. The value of this object can change only when checkInput() is called. The checkInput() method is usually called by a Controller.

An ExpressionInput will ordinarily be registered with a Controller in TWO ways: It's added to a Controller with the Controller's add() method. This makes the Contrller call the ExpressionInput's checkInput() method during the Controller's compute() method. Secondly, the Controller is set as the "onUserAction" property. This causes the Controller's compute() method to be called when the user presses return in the ExpressionInput box. This is optional-- you might, for example, only want the Controller to compute() when a Compute button is pressed. You can also set the ExpressionInput's onTextChange property to a Controller if you want it to compute every time the text in the box changes.

Use the function getFunction() if you want to use an ExpressionInput as a way of inputting a function.

See Also:
Serialized Form

Nested Class Summary
protected  class ExpressionInput.EI
          The expression associated with an ExpressionInput belongs to this class.
 
Nested classes/interfaces inherited from class javax.swing.JTextField
javax.swing.JTextField.AccessibleJTextField
 
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
javax.swing.text.JTextComponent.AccessibleJTextComponent, javax.swing.text.JTextComponent.DropLocation, javax.swing.text.JTextComponent.KeyBinding
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
protected  java.lang.String errorMessage
          Error message from the most recent time the input was checked by a call to checkInput().
protected  ExpressionInput.EI expr
          The Expression associate with this input box.
protected  boolean hasChanged
          True if the contents of the box have not changed since the last time the input was checked (by a call to checkInput()).
protected  Parser parser
          A parser for parsing the user's input expression.
protected  boolean throwErrors
          True if an error should be thrown when checkInput() is called, but the content of the box is not a legal expression.
 
Fields inherited from class javax.swing.JTextField
notifyAction
 
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 javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
ExpressionInput()
          changed by PKHG 050415 A default function 1 Create a new ExpressionFunction with no associated parser.
ExpressionInput(java.lang.String initialValue, Parser p)
          Create an ExpressionInputBox with initial contents given by initialValue.
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent evt)
          Overridden to call onUserAction.compute() if onUserAction is non-null.
 void changedUpdate(javax.swing.event.DocumentEvent evt)
          Dummy, required by DocumentListener interface
 void checkInput()
          Get the expression from the box, maybe throw a JBCError if a ParseError occurs.
 void forceCheckInput()
          Forces a checkInput.
 java.lang.String getErrorMessage()
          Get error message from previous call to checkInput().
 Expression getExpression()
          Get the Expression associated with this ExpressionInput.
 Function getFunction(Variable v)
          Get a function of one variable whose value at a real number x is computed by assigning x to the variable v and then returning the value of the expression associated with this ExpressionInput.
 Function getFunction(Variable[] v)
          Get a function of one or more variables whose value at arguments x1, x2, etc is computed by assigning the x's to the variables and then returning the value of the expression associated with this ExpressionInput.
 Controller getOnTextChange()
          Return the Controller, if any, that is notified whenever the text in this input box changes
 Controller getOnUserAction()
          Return the Controller, if any, that is notified when the user presses return in this text-input box.
 Parser getParser()
          test pkhg 050418
 boolean getThrowErrors()
          Return the value of the throwErrors property, which determines whether errors can be thrown when checkInput() is called.
 double getVal()
          Return the current value of the expression associated with this ExpressionInput.
 void insertUpdate(javax.swing.event.DocumentEvent evt)
          Overridden to call onTextChange.compute() if onTextChange is non-null.
 void notifyControllerOnChange(Controller c)
          Method required by InputObject interface; in this class, it simply calls setOnUserAction(c).
 void removeUpdate(javax.swing.event.DocumentEvent evt)
          Overridden to call onTextChange.compute() if onTextChange is non-null.
 void setOnTextChange(Controller c)
          If the parameter, c, is non-null, then its compute method will be called whenever the text in this input box changes.
 void setOnUserAction(Controller c)
          If the parameter c is non-null, then its compute method will be called whenever the user presses the return key while typing in this text-input box.
 void setParser(Parser p)
          Set the parser that is used to parse the user's input strings.
 void setText(java.lang.String str)
          Set the text displayed in this input box.
 void setThrowErrors(boolean throwErrors)
          Set the throwErrors property.
 java.lang.String toString()
          returns a text representation of this ExpressionInput.
 
Methods inherited from class javax.swing.JTextField
actionPropertyChanged, addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getActions, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, getUIClassID, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset
 
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setDropMode, 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, 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, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, 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, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, 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, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

expr

protected ExpressionInput.EI expr
The Expression associate with this input box. Class EI is a private nested class.


parser

protected Parser parser
A parser for parsing the user's input expression. If this is null, a default parser will be used and only constant expressions will be allowed.


hasChanged

protected boolean hasChanged
True if the contents of the box have not changed since the last time the input was checked (by a call to checkInput()).


throwErrors

protected boolean throwErrors
True if an error should be thrown when checkInput() is called, but the content of the box is not a legal expression. Otherwise, the expression will become a constant expression with value Double.NaN.


errorMessage

protected java.lang.String errorMessage
Error message from the most recent time the input was checked by a call to checkInput(). If this is null, then no error occurred.

Constructor Detail

ExpressionInput

public ExpressionInput()
changed by PKHG 050415 A default function 1 Create a new ExpressionFunction with no associated parser. This can only be used to input constant expressions, unless you set a parser later with setParser().


ExpressionInput

public ExpressionInput(java.lang.String initialValue,
                       Parser p)
Create an ExpressionInputBox with initial contents given by initialValue. (If initialValue is null, the empty string is used.) If p is not null, then p will be used to parse the contents of the box.

Parameters:
initialValue - initial contents of ExpressionInputBox.
p - if non-null, this parser will be used to parse contents of the ExpressionInputBox.
Method Detail

setParser

public void setParser(Parser p)
Set the parser that is used to parse the user's input strings. If this is null, then a default parser is used that will only allow constant expressions.

Parameters:
p - parser to register with user's input strings.

getParser

public Parser getParser()
test pkhg 050418


getExpression

public Expression getExpression()
Get the Expression associated with this ExpressionInput.

Returns:
the expression

getFunction

public Function getFunction(Variable v)
Get a function of one variable whose value at a real number x is computed by assigning x to the variable v and then returning the value of the expression associated with this ExpressionInput. Of couse, v should be one of the variables registered with the Parser for this ExpressionInput, or else in can never occur in the expression. Note that the value of the variable v changes TEMPORARILY when the function is evaluated. (So you should not use a variable where setting the value has a side effect, such as the variable associated with a SliderVariable.)

Parameters:
v - The function that is returned is a function of this variable.
Returns:
the function

getFunction

public Function getFunction(Variable[] v)
Get a function of one or more variables whose value at arguments x1, x2, etc is computed by assigning the x's to the variables and then returning the value of the expression associated with this ExpressionInput. Of couse, each v[i] should be one of the variables registered with the Parser for this ExpressionInput. Note that the value of the variables change TEMPORARILY when the function is evaluated.

Parameters:
v - The function that is returned is a function of the variables in this array.
Returns:
the new function

getVal

public double getVal()
Return the current value of the expression associated with this ExpressionInput.

Specified by:
getVal in interface Value
Returns:
the current value

setOnUserAction

public void setOnUserAction(Controller c)
If the parameter c is non-null, then its compute method will be called whenever the user presses the return key while typing in this text-input box.

Parameters:
c - the controller to use

getOnUserAction

public Controller getOnUserAction()
Return the Controller, if any, that is notified when the user presses return in this text-input box.

Returns:
the controller

notifyControllerOnChange

public void notifyControllerOnChange(Controller c)
Method required by InputObject interface; in this class, it simply calls setOnUserAction(c). This is meant to be called by JCMPanel.gatherInputs().

Specified by:
notifyControllerOnChange in interface InputObject
Parameters:
c - the controller to notify

setOnTextChange

public void setOnTextChange(Controller c)
If the parameter, c, is non-null, then its compute method will be called whenever the text in this input box changes. Furthermore, the throwErrors property will be set to false, to avoid throwing multiple errors while the user is typing. (You can change it back to true if you want by calling setThrowErrors(true).) It would only rarely make sense to use this feature.

Parameters:
c - the controller to call

getOnTextChange

public Controller getOnTextChange()
Return the Controller, if any, that is notified whenever the text in this input box changes

Returns:
the controller

setThrowErrors

public void setThrowErrors(boolean throwErrors)
Set the throwErrors property. When this is true, a JCMError can be thrown when checkInput() is called an a parse error is found in the contents of the input box. If throwErrors is false, no error is thrown. Instead, the expression is set to a constant expression with value Double.NaN.

Parameters:
throwErrors - true or false

getThrowErrors

public boolean getThrowErrors()
Return the value of the throwErrors property, which determines whether errors can be thrown when checkInput() is called.

Returns:
true or false

getErrorMessage

public java.lang.String getErrorMessage()
Get error message from previous call to checkInput(). Returns null if and only if there was no error.

Returns:
the error message

checkInput

public void checkInput()
Get the expression from the box, maybe throw a JBCError if a ParseError occurs. This is meant to be called by a Controller, in general. The expression associated with this ExpressionInput can only change when this method is called; it DOES NOT change continuously as the user types.

Specified by:
checkInput in interface InputObject

forceCheckInput

public void forceCheckInput()
Forces a checkInput. This should only be used by applications that listen for document change notices on an ExpressionInput and might get their event before the ExpressionInput gets its event. The application can call forceCheckInput() to ensure it can get a valid value from the ExpressionInput


setText

public void setText(java.lang.String str)
Set the text displayed in this input box. This overrides TextField.setText to make sure that the expression will be recomputed the next time checkInput() is called.

Overrides:
setText in class javax.swing.text.JTextComponent
Parameters:
str - the text to display

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)
Overridden to call onUserAction.compute() if onUserAction is non-null. This is not meant to be called directly

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Parameters:
evt - the event created when user hits return

insertUpdate

public void insertUpdate(javax.swing.event.DocumentEvent evt)
Overridden to call onTextChange.compute() if onTextChange is non-null. This is not meant to be called directly.

Specified by:
insertUpdate in interface javax.swing.event.DocumentListener
Parameters:
evt - event created when user inserts a character

removeUpdate

public void removeUpdate(javax.swing.event.DocumentEvent evt)
Overridden to call onTextChange.compute() if onTextChange is non-null. This is not meant to be called directly.

Specified by:
removeUpdate in interface javax.swing.event.DocumentListener
Parameters:
evt - event created when user deletes a character

changedUpdate

public void changedUpdate(javax.swing.event.DocumentEvent evt)
Dummy, required by DocumentListener interface

Specified by:
changedUpdate in interface javax.swing.event.DocumentListener
Parameters:
evt - the event

toString

public java.lang.String toString()
returns a text representation of this ExpressionInput. Just returns the contents of the text field.

Overrides:
toString in class java.awt.Component
See Also:
Component.toString()