Image of JPT in children's blocks

Annotated Java Power Tools 2.7.0 Source, Tutorial, Docs

Updated on January 27, 2008 (293 files)

The Java Power Tools Vision

The Java Power Tools vision is to create beautiful code for building graphics and graphical user interfaces in Java. The aim has been to articulate a set of general Java interfaces and then to implement these interfaces with a robust and complete collection of classes. Fundamental issues such as input/output are handled in a general way so that the user may provide input in a console or in a GUI in the same fashion. Attention is paid to experimentation and testing through the Java Power Framework classes and as well as to the rapid construction of complete programs. Finally, enormous effort has been given to the source code itself so that as a 100% open-source repository of interlocking classes the toolkit may serve as an excellent example of object-oriented design.

The Java Power Tools Packages

The JPT package edu.neu.ccs (43 files)
Stringable and Foundation Classes

The JPT package edu.neu.ccs.codec (4 files)
Encoding and Decoding String Arrays

The JPT package edu.neu.ccs.console (5 files)
Console IO

The JPT package edu.neu.ccs.filter (9 files)
IO Filters

The JPT package edu.neu.ccs.gui (177 files)
GUI Tools, Paintable, Shapes, Plots, Actions, Threads

The JPT package edu.neu.ccs.jpf (7 files)
The Java Power Framework for Experiments and Tests

The JPT package edu.neu.ccs.parser (11 files)
IO Parse Routines and Simple Functions

The JPT package edu.neu.ccs.pedagogy (1 file)
Turtle Graphics

The JPT package edu.neu.ccs.quick (15 files)
Assorted Data Structures

The JPT package edu.neu.ccs.util (21 files)
Assorted Utilities

Java Source Files in edu.neu.ccs (43 files)
Stringable and Foundation Classes

The Stringable interface

The Java file Stringable.java (javadocs)

The Stringable interface is one of the most fundamental concepts in the Java Power Tools library. The required methods are deceptively simple:

public void fromStringData(String data) throws ParseException;

public String toStringData();

A Stringable object is an object whose state can be set from a suitable String via fromStringData and which, conversely, can supply a String via toStringData that is sufficient to set its state accurately at a future time.

The fact that fromStringData is permitted in its specification to throw a ParseException means that a Stringable object is encouraged to use parsing techniques to read sophisticated data in setting its state and that it has a built-in mechanism to report errors to its callers. This permits Stringable data to be read in a uniform manner from graphical user interfaces, from console input, and from text files. This also permits error handling for GUIs and console input to be entirely automated by other classes in the JPT such as TextFieldView, DropdownView, ColorView, SliderView, and ConsoleGateway.

This package contains many examples of Stringable classes. Most of these classes use parsing in the fromStringData method to permit sophisticated data input. For instance:

Each Stringable class builds in a mechanism for providing significant and user friendly error messages in case a user does enter data incorrectly. For the numeric and boolean types, the parser will attempt to pinpoint the exact location of the error and give a message that explains the problem. For more complicated data types, the user may enter the ? character when providing data and the resulting error message will list all data formats accepted for that data type.

Support for the parsing requirements of Stringable is provided by many parts of the Java Power Tools infrastructure.

Final note: A Stringable object is always mutable. This is much more convenient for dealing with user interaction and IO than using immutable data types.

For interesting examples of how the Stringable interface plays out in graphical user interfaces, see the following 4 applets:

See also SimpleFunction.

Back to top of edu.neu.ccs or back to top of page

Abstract Stringable classes

The Java file XObject.java (javadocs)

The abstract class XObject is the standard base class for building many Stringable objects.

The Java file XNumber.java (javadocs)

The abstract class XNumber is the standard base class for building most numeric Stringable objects.

Back to top of edu.neu.ccs or back to top of page

Stringable encapsulations of the boolean and char types

The Java file XBoolean.java (javadocs)

The Java file XChar.java (javadocs)

Back to top of edu.neu.ccs or back to top of page

Stringable encapsulations of the basic numeric types using decimal IO with expression parsing

The Java file XByte.java (javadocs)

The Java file XShort.java (javadocs)

The Java file XInt.java (javadocs)

The Java file XLong.java (javadocs)

The Java file XFloat.java (javadocs)

The Java file XDouble.java (javadocs)

See also XComplex

Back to top of edu.neu.ccs or back to top of page

Stringable encapsulations of the basic numeric types using hexadecimal IO

The Java file HexXByte.java (javadocs)

The Java file HexXShort.java (javadocs)

The Java file HexXInt.java (javadocs)

The Java file HexXLong.java (javadocs)

The Java file HexXFloat.java (javadocs)

The Java file HexXDouble.java (javadocs)

Back to top of edu.neu.ccs or back to top of page

Stringable encapsulations of the basic geometric shapes

The Java file XPoint2D.java (javadocs)

The Java file XLine2D.java (javadocs)

The Java file XRect.java (javadocs)

The Java file XSquare.java (javadocs)

The Java file XOval.java (javadocs)

The Java file XCircle.java (javadocs)

The Java file XRoundRect.java (javadocs)

The Java file XRoundSquare.java (javadocs)

The Java file XInterval.java (javadocs)

For additional Stringable geometric types, see also PathNode and PathList in the package edu.neu.ccs.gui.

Back to top of edu.neu.ccs or back to top of page

Stringable encapsulations of some common object types

The Java file XString.java (javadocs)

The Java file XBigInteger.java (javadocs)

The Java file XBigDecimal.java (javadocs)

The Java file XComplex.java (javadocs)

The XComplex class implements a complex number data type.

The Java file XColor.java (javadocs)

The XColor class supports a variety of text formats for the specification of a color: RGB or RGBA in decimal; assorted hexadecimal formats that are common on the web; and named colors. The named colors are based on class Colors.

The Java file SmallSet.java (javadocs)

The SmallSet class encapsulates a set of numbers between 0 and 31. Internally, a set is represented as bits in an integer. The class provides an efficient utility for enumerating the subsets of a given set.

Back to top of edu.neu.ccs or back to top of page

Polynomials and Fourier series as Stringable

The Java file XPolynomial.java (javadocs)

The Java file XFourier.java (javadocs)

The Java file XPolynomialComplex.java (javadocs)

Back to top of edu.neu.ccs or back to top of page

Tools for Stringable

The Java file Strings.java (javadocs)

This class contains general purpose string and parsing utilities. One application of these tools is in the implementation of the Stringable interface for several classes.

This class provides support for the exact encoding of a String[] into a String using a desired delimiter and the corresponding exact decoding of a String into a String[]. Of course, these tools must assume that the delimiter itself does not appear in the String data. These decoding tools go beyond the tools of the Java class StringTokenizer.

This class also supports the notion of a string group. There are three kinds of string group that may be embedded into a larger String:

The advantage of a string group is that the boundary delimiter pairs [] () {} are matched with corresponding internal delimiters ; , | so that a decoder knows how to decode simply by reading an initial boundary delimiter and then locating the extent of the string group.

The decode method in this class not only uses its own methods, it also attempts to decode using the more sophisticated tools of the edu.neu.ccs.codec package. Thus, one decode method call combines all decoding strategies.

Finally, this class contains methods to build name-value string pairs of the form id=value and to decompose such pairs. This class also has conversion utilities to go back and forth between strings and numeric types and text-to-html utilities.

The Java file Colors.java (javadocs)

The Colors class is a support class that supplies a large list of named RGB colors. These colors may be entered directly by the user, may be used in the XColor method fromStringData, and may be accessed interactively in the dropdown view that is incorporated as an option into ColorView.

Back to top of edu.neu.ccs or back to top of page

Tools for functions and parameters

The Java file Function.java (javadocs)

The class Function is a collection of interfaces that classify functions that accept and return values of type double according to the number and kind of direct function arguments.

For example, a class that implements the interface Function.OneArg is required to have a method with the following signature.

public double evaluate(double x).

The Java file Parameter.java (javadocs)

The class Parameter is a collection of interfaces that classify functions that accept and return values of type double according to the number and kind of auxiliary function parameters.

For example, a class that implements the interface Parameter.ArrayParam is required to have a method with the following signature.

public void setParam(double[] params)

The Java file F.java (javadocs)

This class consists of higher order functions that will take real functions as arguments and produce a real function as the return value.

The Java file FunctionComplex.java (javadocs)

The class FunctionComplex is a collection of interfaces that classify functions that accept and return values of type XComplex according to the number and kind of direct function arguments.

The Java file ParameterComplex.java (javadocs)

The class ParameterComplex is a collection of interfaces that classify functions that accept and return values of type XComplex according to the number and kind of auxiliary function parameters.

The Java file FC.java (javadocs)

This class consists of higher order functions that take complex functions as arguments and produce a complex function as the return value.

See also SimpleFunction.

Back to top of edu.neu.ccs or back to top of page

Java Source Files in edu.neu.ccs.codec (4 files)
Encoding and Decoding String Arrays

The edu.neu.ccs.codec package contains tools for encoding and decoding string arrays with 100% robustness. Unlike the simpler tools in the Strings class, these tools will guarantee that a string array encoded into a string can be faithfully decoded into its original constituents. The one drawback to the tools in this package is that the encoded strings are machine-readable but are not particularly easy to read or enter interactively by humans. Hence, these tools are more appropriate for

The Codec interface

The Java file Codec.java (javadocs)

The Codec interface describes the requirements for a tool that can encapsulate a String[] into a String and then faithfully unencapsulate the String back into the original String[].

Back to top of edu.neu.ccs.codec or back to top of page

Two Codec implementations

The Java file CountPrefixCodec.java (javadocs)

The Java file EscapedCodec.java (javadocs)

Encoding and decoding operations should be performed through the methods of the class CodecUtilities rather than by directly calling a particular Codec.

Back to top of edu.neu.ccs.codec or back to top of page

The Codec utilities used to convert between a String[] and a String

The Java file CodecUtilities.java (javadocs)

Provides methods to encode either a String[] or a Stringable[] into a String using either the default Codec for this package or a specified Codec implementation. Also provides the inverse method decode that will faithfully unencapsulate an encoded String back into a String[].

Encoding and decoding operations should be performed through the methods of this class rather than by directly calling a particular Codec.

Note: The current default Codec for this package is the CountPrefixCodec.

Back to top of edu.neu.ccs.codec or back to top of page

Java Source Files in edu.neu.ccs.console (5 files)
Console IO

The ConsoleAware interface

The Java file ConsoleAware.java (javadocs)

The ConsoleAware interface provides access to the console object that is shared by all threads in the program. The console object is an instance of the class ConsoleGateway. Methods that operate on the console object itself include activation of the console so that it uses its own window, selection of the default console settings, and provision of input-output utilities such as prompting that are used by the inner classes.

If you plan to manually initialize the console then the following call is recommended:

console.setActivated(true)

If you use the Java Power Framework (JPF) environment, then this call is done automatically by the button Toggle Console if the console has not yet been activated or if the console has been activated and then closed by the user.

The console object provides three data streams:

Input-output methods in console and console.in should normally not be called in the event handling thread because waiting for console input may block the handling of other user interaction events. Use one of the classes SimpleThreadedAction or ThreadedAction to create an action to manage the console interaction so that user input and output may run in its own thread.

If you use the Java Power Framework (JPF) environment, then separate threads are created automatically for all method buttons in the JPF GUI. Therefore, if a method button directly manages the console interacation the separate threading will be automatic. Moreover, if the method associated with a method button is active, the method buttons are temporarily disabled so it is impossibe to start another console interaction that will conflict with the console interaction in progress.

Since the introduction of the console in JPT, it has been possible to color-code the streams in, out, and err by making the call:

console.selectColorTextScheme();

If the color text scheme is enabled, then the streams in, out, and err will use the colors blue, black, and red respectively.

However, without changing the code in JPT, there is now a problem with the above call in the Macintosh implementation of Java. The effect is that the console will not behave properly if the color text scheme is enabled on the Macintosh. In contrast, things work perfectly for the Windows implementation of Java 6 so the problem is not due to a change made by Sun Microsystems in Java itself.

Back to top of edu.neu.ccs.console or back to top of page

The ConsoleGateway class

The Java file ConsoleGateway.java (javadocs)

The methods provided by ConsoleGateway itself fall into three categories:

Back to top of edu.neu.ccs.console or back to top of page

The ConsoleGateway.ConsoleInputStream inner class

The ConsoleGateway.ConsoleInputStream inner class provides the extended functionality for the input stream console.in. Input of primitive types and simple objects types is fully supported by robust methods that handle input error checking automatically and also parse and evaluate arithmetic and boolean expressions entered by the user. Below is a list of the main method names. Each method usually has several versions to allow the caller to customize the input behavior as desired.

Back to top of edu.neu.ccs.console or back to top of page

The ConsoleGateway.ConsoleOutputStream inner class

The ConsoleGateway.ConsoleOutputStream inner class provides the functionality for the output streams console.out and console.err. This class extends the Java class java.io.OutputStream so much of its functionality is inherited from Java. Only a few utility methods are added to this base functionality.

Back to top of edu.neu.ccs.console or back to top of page

The console implementation classes

The following classes are used in the implementation of the console functionality and should normally not be called directly by the console user.

The Java file ConsoleInputListener.java (javadocs)

The Java file ConsoleTextPane.java (javadocs)

The Java file ConsoleWindow.java (javadocs)

Back to top of edu.neu.ccs.console or back to top of page

Java Source Files in edu.neu.ccs.filter (9 files)
IO Filters

The StringableFilter interface and the FilterException class

The Java file StringableFilter.java (javadocs)

The Java file FilterException.java (javadocs)

The StringableFilter interface describes a filter object that encapsulates one method:

Stringable filterStringable(Stringable obj) throws FilterException

This filter method is used to determine if the given Stringable object is suitable for further processing, that is, if the object satisfies whatever constraints are represented by the filter. If the object does satisfy the constraints, the filter method will normally return the same Stringable object. However, if state changes must be made, then the filter method should create and return a new Stringable object so that the original Stringable object is unchanged. If the given Stringable object does not satisfy the constraints of the filter method, then the method should throw a FilterException.

This package contains 2 abstract classes for creating filters and 4 concrete classes for specific filters. In addition, the class StringableFilterSequence provides the mechanism to create a composite filter that invokes a sequence of filters in turn.

The input operations defined in the GeneralView interface and in the 3 classes that implement this interface TextFieldView, DropdownView, and StringViewer permit the caller to supply a StringableFilter to impose constraints on the user input. If the filter throws a FilterException then this will be converted to a ParseException which will then be handled by the automatic error handlers. Similar options are provided by the input operations in ConsoleGateway.

Back to top of edu.neu.ccs.filter or back to top of page

Abstract StringableFilter classes

The Java file NumericFilter.java (javadocs)

The Java file BoundFilter.java (javadocs)

Back to top of edu.neu.ccs.filter or back to top of page

Concrete StringableFilter classes

The Java file CaseActionFilter.java (javadocs)

The Java file MinimumBoundFilter.java (javadocs)

The Java file MaximumBoundFilter.java (javadocs)

The Java file RangeFilter.java (javadocs)

Back to top of edu.neu.ccs.filter or back to top of page

A class to compose StringableFilter objects

The Java file StringableFilterSequence.java (javadocs)

Back to top of edu.neu.ccs.filter or back to top of page

Java Source Files in edu.neu.ccs.gui (177 files)
GUI Tools, Paintable, Shapes, Plots, Actions, Threads

Back to top of edu.neu.ccs.gui or back to top of page

GUI interfaces for model-view interaction

The three Java interfaces Displayable, TypedView, and GeneralView are intended to support graphical user interfaces in which the data for an object may be given by text input. Such GUIs will often provide additional graphical means for supplying the object data. We arrange these three interfaces in a hierarchy, that is, Displayable is the base, TypedView adds behavior to Displayable, and GeneralView adds behavior to TypedView. The data model for a TypedView or GeneralView must be a type that implements Stringable.

The Java interface StringObjectView is intended to support a direct mapping between strings that appear in the graphical user interface and specific objects in the internal data structure of the program. Thus, the selection of a string by the user can map directly to the selection of an object.

The Java file Displayable.java (javadocs)

The Displayable interface requires methods to deal with the view state of a view, that is, the portion of the state that is in correspondance with a data model. A Displayable can set or get the current view state as a String, set or get a similar default view state, reset the view to its default state, and handle setEnabled calls by recursive propagation to internal component objects. In a Displayable, incidental aspects of a view such as its widget geometry and color are normally not part of the view state.

Unlike TypedView and GeneralView, Displayable does not impose any requirements on the data model.

In Displayable, the two most important methods are:

public void setViewState(String data)
public String getViewState()

The Java file TypedView.java (javadocs)

The TypedView interface extends Displayable and requires methods that deal with the data model. A TypedView must return the class of its current data model via the method getDataType. This class must implement Stringable. A TypedView should also manage the extraction of its view state and the creation of a corresponding data model object via the methods demandObject and requestObject. Both methods should totally encapsulate the error checking process so that if the view state is invalid for the desired type of return object then the user will be prompted to make corrections. The method demandObject should normally insist that the user provide valid input while the method requestObject should normallly offer the user the option of cancelling the input process if the data is invalid. In the latter situation, a CancelledException should be thrown to alert the program of this user decision.

In TypedView, the three most important methods are:

public Class getDataType()
public Stringable demandObject()
public Stringable requestObject() throws CancelledException

In addition to these straightforward methods, a TypedView should also maintain an internal property list object using the class InputProperties. In this object, the view may store additional settings such as error handling parameters.

The Java file GeneralView.java (javadocs)

The GeneralView interface extends TypedView and adds the method setDataType.

public void setDataType(Class dataType)

Thus, a GeneralView is a TypedView that is able to handle multiple Stringable data types. This feature is very powerful.

The GeneralView interface requires additional methods beyond the method setDataType to allow such views to be used with great flexibility. These include:

The helper class GeneralViewSupport may be used internally in a GeneralView to assist in implementation of the various required methods.

The prime examples of GeneralView’s are TextFieldView and DropdownView.

The Java file StringObjectView.java (javadocs)

The StringObjectView interface requires methods that reflect the implicit mapping of strings to objects and objects to strings. The methods getSelectedString and getSelectedObject allow a caller to query the state of the view either by its selected string (which is visible in the view) or by its associated object (which is in the model). In most cases, the user will make selections interactively but it is also possible to set selections directly using the methods setSelectedString and setSelectedObject. The methods getSelectedObject and setSelectedObject permit a caller to work with a StringObjectView entirely in terms of objects in the model which is quite convenient.

The prime examples of StringObjectView’s are StringObjectRadioPanel and StringObjectDropdown.

Note that both GeneralView and StringObjectView require methods to add or remove action listeners that will be triggered when the view state changes.

Back to top of edu.neu.ccs.gui or back to top of page

Support classes for the GUI interfaces

The Java file GeneralViewSupport.java (javadocs)

The GeneralViewSupport class provides the core functionality of a GeneralView in such a way that actual GeneralView objects can delegate much of their work to this class. Normally, this class is used internally in a GeneralView object.

The Java file InputProperties.java (javadocs)

InputProperties is a class utilized in the specification of the TypedView interface through get and set methods.

An InputProperties object is a property list used to store properties pertaining to input components.

There are four bound properties for an input properties that represent the standard properties for an input component and the parameters it contributes to a standard error strategy:

The use of an InputProperties object by a TypedView object permits the TypedView object to control what will happen if an error dialog is needed during input. In particular, if the INPUT_MODEL is OPTIONAL then the error dialog will have a CANCEL button whereas if it is MANDATORY then there will be no CANCEL button and the user will be required to submit valid input.

The InputProperties class implements a data structure that can be used to store any number of input properties of any type, keyed using String property names. An input properties object can be created so that it shadows the properties stored in a preexisting InputProperties object or the base InputProperties object that contains default property values.

The Java file CancelledException.java (javadocs)

CancelledException is an exception designating that an input operation was cancelled by the user.

Back to top of Support classes for the GUI interfaces or back to top of edu.neu.ccs.gui or back to top of page

Views: text fields, text areas, strings

The Java file TextFieldView.java (one line text input) (javadocs)

The TextFieldView class is a GeneralView designed to input a single line of text using a Java JTextField. A TextFieldView may be used to input any Stringable object that may be set using a single line of text that could reasonably be expected to be entered directly by a user. This functionality is provided by the methods demandObject and requestObject specified in the TypedView interface.

Important convenience methods are also provided that permit the caller to either demand or request one of the following types: boolean, char, byte, short, int, long, float, double, BigInteger, BigDecimal, and String. These methods parallel similar methods for console IO that are available through the ConsoleGateway class and the associated ConsoleAware interface. Both sets of methods implement automatic arithmetic and boolean expression parsing using tools in the package edu.neu.ccs.parser.

The TextFieldView class provides numerous constructors so that many properties of the view may be set at the time of construction. In particular, the width of the view may be set. The height of the view is determined by the current font for the text field view. The default font is the text field font in the current look and feel but the font may be changed either in a constructor or after construction.

As a further convenience, TextFieldView provides static methods to compute the text field width required to hold a particular string or a particular run of repeated characters using a given font. With these static methods, the caller can compute the optimal width for a text field based on the font that will be used in the text field.

TextFieldView inherits from JTextField the ability to add an ActionListener that will be triggered when the return key is pressed in the view.

The Java file TextAreaView.java (multi line text input) (javadocs)

The TextAreaView class is a TypedView designed to input multi-line text using a Java JTextArea. Using the method getViewState, the text in the view is returned as a String object. Using the methods demandObject and requestObject which are identical for a TextAreaView, the text in the view is returned as an XString object. Further processing of the string data is the responsibility of the caller.

The Java file StringViewer.java (display of a string in a GUI) (javadocs)

Class StringViewer provides static tools for viewing a String in a GUI. The core methods wrap a String in an Annotation which is in turn wrapped in a JPTScrollPane whose viewport size may be set by the caller or may be defaulted to 800 by 600. The caller can then manually place this scroll pane in a GUI or can automatically display it in either a frame or an OK dialog box.

The class StringViewer was built specifically to support the display of a stack trace generated by the class StackTrace but it has many other potential applications in which significant amounts of text must be shown to a user.

The Java file XObjectView.java (javadocs)

The XObjectView class is a Displayable designed as a view for the output of the String representation of the state of an XObject. This view is intended to be used as a default view in case no more specific view is available. This view is in fact rarely used. Note also that this view may not be used for data input.

Back to top of Views: text fields, text areas, strings or back to top of edu.neu.ccs.gui or back to top of page

Views: check boxes

The Java file BooleanView.java (check box selection) (javadocs)

The BooleanView class is a TypedView designed to input a boolean value using a Java JCheckBox. If the check box is checked, then the state is true, and if it is unchecked, then the state is false.

BooleanView inherits from JCheckBox the ability to add an ActionListener that will be triggered when the state of the view (checked or unchecked) changes.

Back to top of Views: check boxes or back to top of edu.neu.ccs.gui or back to top of page

Views: radio buttons

The Java file RadioPanel.java (radio button selection) (javadocs)

The RadioPanel class may be used directly to construct a panel of radio buttons. The class is also the base class for OptionsView and StringObjectRadioPanel.

RadioPanel is designed to input a selection using a set of Java JRadioButton objects. What makes RadioPanel quite convenient are its constructors that make it possible to set many choices immediately. Here are some of the options:

To illustrate the interaction of the String array of labels and a TableLayout layout manager, let us consider two examples. Both examples will use the same array of 8 labels:

String[] labels =
    { "1", "22", "333", "4444", "55555", "666666", "7777777", "88888888" };

To better illustrate what is happening, we will use a TableLayout that is set for only 2 rows and 2 columns which is insufficient for 8 labels. This will permit us to see how the table grows. We will set the cell gaps to be 10 and will align the radio buttons in each cell to the WEST which is what is commonly done with radio buttons.

In example 1, we will use an orientation parameter of HORIZONTAL. Here is the code:

TableLayout layout = new TableLayout(2, 2, 10, 10, WEST, HORIZONTAL);
        
RadioPanel radio = new RadioPanel(labels, layout);

Here is the screen snapshot for a HORIZONTAL orientation parameter:

RadioPanel with HORIZONTAL TableLayout

In example 2, we will use an orientation parameter of VERTICAL. Here is the code:

TableLayout layout = new TableLayout(2, 2, 10, 10, WEST, VERTICAL);
        
RadioPanel radio = new RadioPanel(labels, layout);

Here is the screen snapshot for a VERTICAL orientation parameter:

RadioPanel with VERTICAL TableLayout

As you can see, the orientation parameter (HORIZONTAL or VERTICAL) controls the direction in which the table grows if its initial number of rows and columns is insufficient for the data. A HORIZONTAL TableLayout grows horizontally and a VERTICAL TableLayout grows vertically. Another way to see this is:

Although this convention may seem strange, it makes perfect sense if you imagine starting with a layout with 1 row and 1 column. In that case, an orientation parameter of HORIZONTAL leads to a horizontal table and an orientation parameter of VERTICAL leads to a vertical table.

Final note: When using a RadioPanel, the caller may obtain the label of the selected radio button, the index of the selected radio button, or the selected radio button itself.

The Java file OptionsView.java (radio button selection) (javadocs)

An OptionsView is a RadioPanel that implements TypedView by setting the data type to XInt and by using the selected index to set and get its view state as a TypedView.

The Java file StringObjectRadioPanel.java (radio button selection) (javadocs)

A StringObjectRadioPanel is a RadioPanel that implements StringObjectView. Hence the user selection of a radio button implicitly selects its string which in turn implicitly selects the associated object in the model.

Back to top of Views: radio buttons or back to top of edu.neu.ccs.gui or back to top of page

Views: dropdown lists

The Java file Dropdown.java (editable dropdown list selection) (javadocs)

The Dropdown class is a class that provides basic dropdown list capabilities in its own right and is also the base class for more sophisticated dropdown objects.

The Java file DropdownView.java (editable dropdown list selection) (javadocs)

The DropdownView class is a GeneralView based on the dropdown list functionality of the Java class JComboBox. DropdownView is designed to input a selection from one of many text strings that are predefined in the program. If the dropdown list is made editable, then the user may also enter string data that will be parsed according the rules of the data type associated with the GeneralView.

The Java file StringObjectDropdown.java (dropdown list selection) (javadocs)

The StringObjectDropdown class is a StringObjectView based on the dropdown list functionality of the Java class JComboBox. StringObjectDropdown is designed to input a selection from one of many text strings that are predefined in the program. The caller may also obtain the object associated with one of the text strings directly. The dropdown list in this view should not be made editable.

Back to top of Views: dropdown lists or back to top of edu.neu.ccs.gui or back to top of page

Views: sliders

The Java file SliderView.java (slider selection) (javadocs)

Class SliderView permits the construction of a slider with pixel-level control of the size of the slider track. The caller can therefore control the relationship between the minimum and maximum values represented by the slider and the physical implementation in pixels. This can permit users to make slider selections with more accuracy.

The SliderView code was completely rewritten for version 2.6.0. A few older methods that are now obsolete have been retained for backward compatibility. This class no longer depends on the Java class JSlider.

In addition to pixel-level control of the size of the slider, SliderView offers several advantages over the Java class JSlider.

The SliderView class implements TypedView with a type of XInt corresponding to the int value returned by a slider.

For examples of a SliderView, see the Spinning Animation applet and the Star Color applet. In the latter, click on the color box to bring up a ColorPaneDialog which uses 4 color sliders each with a gradient paint on its slider track.

Back to top of Views: sliders or back to top of edu.neu.ccs.gui or back to top of page

Views: color selection

The Java file ColorView.java (color selection) (javadocs)

The ColorView class is a TypedView for the user input of a Color. By default, the view will display a color box using a PaintSwatch together with an dropdown list for selection of the color. If desired, either the color box or the dropdown may be made invisible.

The color box is active. If the color box is clicked, a ColorPaneDialog dialog is displayed to permit the user to select the color interactively using sliders for the red, green, blue, and alpha components of the color. This dialog permits the user to contrast the selected color with a color previously entered called the original color.

The dropdown list permits the user to select a color from 142 named colors that are presented in the dropdown as a color swatch together with a color name. These color names follow conventions that have become more or less standard on the web. The dropdown list is also editable so that the user may enter a color using red, green, blue, and optional alpha components using either decimal or hexadecimal formats.

The following sequence of screen snapshots illustrates the features of a ColorView. First, we show a default ColorView with color black.

ColorView snapshot 1

Next, we show the color dropdown list with “DarkOrange” about to be selected.

ColorView dropdown

Next, we show the ColorView with “DarkOrange”.

ColorView snapshot 2

Next, we show the ColorPaneDialog that is brought up with a click on the color swatch in the ColorView.

ColorPaneDialog snapshot

Finally, we show the ColorView after the user has clicked OK in the ColorPaneDialog.

ColorView snapshot 3

The Java file ColorPane.java (color selection) (javadocs)

A pane in which the user may select a color using sliders for each of the 4 color components: red, green, blue, alpha. For convenience, the pane also contains a color dropdown so the user can start with a named color and then modify that color interactively.

See ColorView and ColorPaneDialog.

The Java file ColorPaneDialog.java (color selection) (javadocs)

An OK-Cancel dialog that contains a ColorPane. This type of dialog is opened by clicking on the color swatch in a ColorView.

For a snapshot, click here.

The Java file MultiColorView.java (multi-color selection) (javadocs)

Class MultiColorView provides a view for the interactive selection of multiple colors. In this view, there is a table with labels in column 0 and corresponding ColorView objects in column 1. The user may set multiples colors by setting each of the individual ColorView objects. In interfacing with other objects, a MultiColorView can return either an individual color based on its index or an array of all colors represented in the view.

One application of MultiColorView is the selection of the function plot colors in FunctionsPlotter. Below is a snapshot of the multi-color view as extracted from the larger GUI.

MultiColorView snapshot

Back to top of Views: color selection or back to top of edu.neu.ccs.gui or back to top of page

Factory methods for components, icons, paintables

The Java file ComponentFactory.java (javadocs)

ComponentFactory has 3 static methods:

Throughout Java Power Tools, whenever a caller is required to supply a Component, Icon, or Paintable, an effort is made to permit the caller to supply a more general Object and to have the construction of the desired entity be entirely automated. For example, if the user wants to install a String into a GUI in the “standard fashion” then this may be handled automatically. Of course, the caller retains the ability to build whatever explicit GUI objects are desired. If automation is desired by the caller then the 3 static methods in this class are usually called behind the scenes so that no extra effort will be required.

In 3 tables below, we will show how the 3 static methods work. Before that, let us make some general remarks. The first two methods both make certain specific attempts to convert a general Object into the desired type. If these attempts fail then the methods will call the makePaintable method to try to convert the Object into a Paintable. If that attempt succeeds then the Paintable will be placed into a PaintableComponent which is both a Component and an Icon. On the other hand, if this final attempt fails then null will be returned.

The table below shows more about how makeComponent works.

Argument Return
Component The same Component
String Annotation
Icon Annotation
Action JButton
Paint PaintSwatch
converts to
Paintable
PaintableComponent
otherwise null

The table below shows more about how makeIcon works.

Argument Return
Icon The same Icon
Paint PaintSwatch
converts to
Paintable
PaintableComponent
otherwise null

The table below shows more about how makePaintable works.

Argument Return
Paintable The same Paintable
Shape ShapePaintable
PathList ShapePaintable
Image ImagePaintable
ImageIcon ImagePaintable
String MultiLineTextPaintable
Point2D PointPaintable
Object[] PaintableSequence
otherwise null

Notice that if the argument to makePaintable is an array of Object then the method is called recursively on the items in the array to make a PaintableSequence.

To permit overriding, the method makeComponent in DisplayPanel is a member method that calls the static method in this class.

Back to top of Factory methods or back to top of edu.neu.ccs.gui or back to top of page

Layout managers: TableLayout, etc.

The Java file TableLayout.java (javadocs)

TableLayout is the most important layout manager in the Java Power Tools. This layout manager will arrange components in a one or two dimensional table as desired. This manager will compute the row heights and column widths from the preferred size of the components and can impose minimum values for these measurements if needed. The gaps between the rows or columns can be set in absolute pixels. If a component is smaller than its cell, then its alignment within the cell can be set to the center or to one of the eight compass directions. Cell alignment can be set for the entire table, for individual rows or columns, or for individual cells. Finally, null components are handled cleanly by leaving cells empty as appropriate.

TableLayout is the technical foundation for the panel TablePanel. TableLayout may also be used for other Java panels such as RadioPanel to provide fine control of component layout.

Since the invention of TableLayout, we have found in practice that we rarely need to use any other layout manager.

The Java file CenterLayout.java (javadocs)

CenterLayout maintains a single component in the absolute center of the parent container. This manager is a precursor to TableLayout and was inspired by code posted on the internet by an author named "Sapex".

Since the invention of TableLayout, this layout manager is rarely used but it still has a role in classes that wrap a single object and center that object. Examples are: JPTFrame, DirectApplet, Halo

The Java file AlignedLayout.java (javadocs)

AlignedLayout maintains a single component either in the absolute center of the parent container or in one of the eight compass directions. This manager is a precursor to TableLayout.

Since the invention of TableLayout, this layout manager is rarely used.

The Java file AbsoluteLayout.java (javadocs)

AbsoluteLayout is to the extent possible a hands off layout manager. However, in 2.3.5, a serious bug was fixed and this fix required a policy concerning how to compute the size of each of the installed components. Here is the policy.

If a Component is actually a Container then its size is computed by calling getPreferredSize and any existing size set by setSize is ignored. This permits objects that extend Container to effectively change their size by changing the return value of getPreferredSize and this change is not affected by an obsolete value set earlier by setSize.

For a general Component, the size is set to be the maximum of getSize and getMinimumSize. This approach was a design choice based on the fact that for many older Java Component objects people often directly set the size and do not bother with the minimum size. This means that the resulting size set in this layout manager is at least a big as both the actual size set earlier and the minimum size.

The size policy is consistent with the effort in JPT to use getPreferredSize (which is algorithmic) rather than rely on size settings that may become obsolete for dynamically changing components.

The use of this layout manager is not recommended unless the application is fully capable of handling the layout responsibities for a panel.

AbsoluteLayout is used for the Zoo panel.

Back to top of Layout managers or back to top of edu.neu.ccs.gui or back to top of page

Panels: DisplayPanel and BasePane

The Java file DisplayPanel.java (javadocs)

Class DisplayPanel is the base panel for all other JPT panels. DisplayPanel implements the Displayable interface and is designed to recursively propagate Displayable method calls to contained components that are also Displayable. In particular, the method setEnabled is propagated to all of its immediate components (which oddly is not the Java default) and will therefore recursively propagate in its Displayable components.

DisplayPanel also provides the following special features:

The Java file BasePane.java (javadocs)

Class BasePane extends DisplayPanel and contains common font and size definitions for use in other components. The common fonts are built using the class Fonts in conjunction with any font size adjustment made using the methods in LookAndFeelTools. The caller who wishes to use these common definitions can either extend BasePane or install components into an instance of BasePane. In either case, it is the responsibility of the caller to set the fonts for any components that will use these common definitions. This cannot be done automatically.

Back to top of Panels: DisplayPanel and BasePane or back to top of edu.neu.ccs.gui or back to top of page

TablePanel and associated classes

The Java file TablePanel.java (javadocs)

TablePanel is the most important panel in the Java Power Tools. TablePanel is designed to quickly build one or two dimensional tables of components. These components may provided as objects that extend Java's class Component or they may be more general objects that are automatically converted into components using the makeComponent method. Since TablePanel's nest within TablePanel's, component layouts of arbitrary complexity may easily be achieved.

TablePanel is based on the layout manager TableLayout. Due to the TableLayout algorithms, TablePanel is able to handle the arrangement of objects in rows and columns, the alignment of objects within cells, and the pixel gaps between cells.

The TablePanel constructors are designed to allow a table to be built in a ready to use state by permitting the caller to provide all objects to be installed and all other relevant parameters. The objects may be supplied as an array of Object that is either one or two dimensional. These objects will be converted to Component's as needed using the method makeComponent.

It is also possible to build a table algorithmically by supplying the dimensions of the table together with a strategy for building objects that is encapsulated in a TableGenerator object.

The TablePanel class has numerous constructors but the three most important constructors are:

        TablePanel(Object[][] contents, int hgap, int vgap, int align)

        TablePanel(Object[] contents, int orientation, int hgap, int vgap, int align)

        TablePanel(TableGenerator tg, int rows, int cols, int hgap, int vgap, int align)

In the first two constructors, the contents array parameter supplies the objects that will be converted into Component's via the makeComponent method and then inserted into the table. In the third constructor, the TableGenerator tg supplies the objects for the table algorithmically and the size of the table is determined by the given rows and cols.

In the second constructor, the caller must supply the display orientation which is one of the following constants from SwingConstants or JPTConstants:

The parameters hgap and vgap represent the standard horizontal and vertical pixel gaps between table cells. Finally, the align parameter determines the alignment of components within table cells when the components are smaller than the cells. The align parameter is one of the following constants from SwingConstants or JPTConstants:

The Java file TableGenerator.java (javadocs)

The TableGenerator interface specifies an algorithm for building the contents of a table via the method makeContents that returns an Object for each row and column of the table.

The Java file CellPosition.java (javadocs)

CellPosition is a simple helper class to encapsulate a row and column position in a table.

The Java file HTable.java (javadocs)

HTable is a derived class of TablePanel that is constrained to be 1-dimensional and horizontal. Thus, the orientation parameter HORIZONTAL does not need to be supplied to an HTable constructor.

The Java file VTable.java (javadocs)

VTable is a derived class of TablePanel that is constrained to be 1-dimensional and vertical. Thus, the orientation parameter VERTICAL does not need to be supplied to a VTable constructor.

Back to top of Panels: TablePanel and associated classes or back to top of edu.neu.ccs.gui or back to top of page

Panels: BufferedPanel

The Java file BufferedPanel.java (javadocs)

BufferedPanel is a panel that automates the refresh process by repainting itself from a persistent graphics state that is stored in 2 data structures for the background layer and sprite layer.

To use the BufferedPanel background layer properly, the caller should paint to the stored buffer whose graphics context is available through the method call getBufferGraphics. All calls in Java 2D graphics are available for this purpose. For more sophisticated manipulation of the background layer, the caller may access the buffer itself through the method call getBuffer.

To use the sprite layer of a BufferedPanel, there are various methods to add, append, or remove one or more objects to or from the layer. These objects are passed through the makePaintable method of ComponentFactory to create a Paintable if needed.

When the caller is ready to display the changes made to the 2 panel data structures, the repaint method on the panel should be invoked.

A BufferedPanel may be made responsive to the mouse by installing appropriate mouse actions using the built-in mouse action adapter object. Such actions may be defined by the caller. There is also a default set of mouse actions that may be used to drag the paintables in the sprite layer. To obtain these actions, use the method installSimpleMouseActions.

Back to top of Panels: BufferedPanel or back to top of edu.neu.ccs.gui or back to top of page

Panels: Annotation

The Java file Annotation.java (javadocs)

Annotation extends DisplayPanel to provide a Displayable component representing an annotation in a GUI, such as the prompt for an input object or the caption for an image.

The functionality of this class is based on the functionality of the JLabel class provided in the javax.swing package, with the following additional functionality:

Back to top of Panels: Annotation or back to top of edu.neu.ccs.gui or back to top of page

Panels: Wrapper panels

The Java file Halo.java (javadocs)

Halo is a wrapper class for one Object viewed as a Component. This class uses a CenterLayout and provides positive minimal insets.

The purpose of Halo is to provide a panel that just barely surrounds its wrapped component. This is useful because, when the JPT detects an input error, it highlights the panel surrounding the component in which the error occured. By wrapping a component in which an error may occur, the error highlighting is focused precisely on that component.

In particular, it is recommended that if a TextFieldView, say, view, is to be inserted into a TablePanel and if there is a possibility of an input error within view, then the following idiom should be used for the inserted object:

The Java file JPTScrollPane.java (javadocs)

JPTScrollPane extends JScrollPane by adding methods that help control the preferred size of the JViewport window. Since the size of the JViewport window is what concerns the caller of a scroll pane class, this size control is very convenient.

JPTScrollPane does not implement Displayable but leaves that to its derived class ScrollableDisplay.

The Java file ScrollableDisplay.java (javadocs)

ScrollableDisplay is a JPTScrollPane that also implements Displayable. A ScrollableDisplay contains a single Displayable object as its viewport view and delegates its Displayable method calls to this view.

The functionality of this class assumes that the viewport view for this scroll pane is a Displayable object that is set through the setDisplay method, and effects are undefined if the viewport view is set through other means.

The Java file Display.java (javadocs)

The class Display is a wrapper class designed to add either annotation text as a label or title text as a titled border or both to its wrapped component.

Since the invention of TablePanel, one may add a label to an object while building the table. Hence Display is no longer needed to add a label annotation.

Titles may now be created in two ways. The class DisplayPanel provides numerous methods to create borders including a titled border via its titleBorder methods. This provides an alternative to the use of Display. However, as the screen snapshot below illustrates, the default conventions for the two approaches are different.

Snapshot comparing Display versus titleBorder

The Display class builds its border using an etch border for its frame whereas the method titleBorder uses a line border of thickness 2 as its default. Which is preferable is a matter of aesthetic choice. The titleBorder family of methods is more general, however, since there are several variations that permit the caller to choose the base border for the frame. The titleBorder family of methods also includes options to set the title font and color and to set the title position in the frame.

To integrate additional components into a GUI that already uses Display, it is best to continue to use Display for visual continuity. For new code, the use of titleBorder will provide the most flexibility.

Back to top of Panels: Wrapper panels or back to top of edu.neu.ccs.gui or back to top of page

Other collection panels

The Java file ActionsPanel.java (javadocs)

ActionsPanel is a precursor to TablePanel. Its use of an array of Action objects to define a panel of JButton objects was one of the inspirations for TablePanel. Despite the fact that one can now install a button into a TablePanel using an Action object, there are still reasons to use ActionsPanel. Since an ActionsPanel consists solely of buttons, one can define the default button that is executed by a press of the return key. In addition, ActionsPanel makes it easy to provide each button with a tool tip. To make all buttons in an ActionsPanel have the same size, use the inherited method uniformizeSize.

The Java file DisplayCollection.java (javadocs)

DisplayCollection creates a one dimensional table of Displayable components.

Since the invention of TablePanel, this panel is rarely used.

The Java file SimpleArrayPanel.java (javadocs)

SimpleArrayPanel (which was introduced in 2.4.0) is a much simpler way to create user controlled array views than the older class ArrayPanel. It is recommended that this class be used for future development.

The javadoc introduction for SimpleArrayPanel contains detailed instructions for the use of this panel. We excerpt the opening remarks from these instructions.

Class SimpleArrayPanel provides a panel that can hold one or more views of a given type with the number of such views under interactive user control.

The views are arranged in a 4-column vertical list with the following structure in each row:

This 4-column vertical list is placed in a scroll pane. The designer can determine how many rows will be visible at once.

The interactive controls that permit the user to change the total number of views are placed in a panel underneath the scroll pane.

To construct a SimpleArrayPanel, the user must supply its viewType which is an object of type Class that defines the view that will be repeated in the panel.

The following restrictions on the viewType must hold:

For a snapshot of a SimpleArrayPanel in use, see PathListView

The Java file ArrayPanel.java (javadocs)

ArrayPanel is an abstract class implementing the interface TypedView whose purpose is to provide for the input of a possibly dynamic array of Stringable objects.

An ArrayPanel is an integrated component containing a collection of TypedView's for input of Stringable objects of a specific type, with the option of controls for the dynamic modification of the length of the array by the user.

To implement ArrayPanel, it is necessary to build a derived class that implements the abstract methods. It is also recommended that the designer consider overriding the protected method createViewFor. It is this method that constructs the views for the items in the array. By default, this method returns a vanilla TextFieldView. It is likely that the designer will either want to return a customized TextFieldView or a more sophisticated TypedView.

Since an ArrayPanel may have few components when it is initialized, it is important to allow for dynamic growth by the user. It is recommend that the ArrayPanel be inserted into a wrapper of type JPTScrollPane or of type ScrollableDisplay. Then, using the sizing methods of the wrapper, one can provide enough space for the ArrayPanel.

Back to top of Panels: Other collection panels or back to top of edu.neu.ccs.gui or back to top of page

Zoo and associated classes

The Java file Zoo.java (javadocs)

A Zoo is a ZooContainer that allows selection and direct mouse manipulation of its components.

A Zoo is a container used to contain components that can be moved and resized through direct mouse manipulation. In this way, a Zoo is like a desktop for components. In a Zoo, it is permissible to overlap components if that is desired.

An individual component, or a collection of components, may be selected through direct mouse manipulation or through method calls. A selected component is painted with a box surrounding its bounds. The components that are currently selected may be retrieved using various methods. A component is selected if it is clicked with the mouse. To select multiple components, hold the Shift key when selecting the components.

Components in a Zoo are called child items. All child items are contained at the top level of the Zoo. Components may be grouped into a ZooGroup which is treated as a single entity in the Zoo.

To permit a child item to be treated alternately as an object for mouse manipulation or as Java component with its own functionality, each child item is encapsulated in a transparent Laminate object that will either handle the mouse when the child item is being manipulated or, if the Zoo is not in edit mode, will pass this mouse information through to the component that is encapsulated.

The Java file ZooGroup.java (javadocs)

The Java file ZooContainer.java (javadocs)

The Java file Laminate.java (javadocs)

The three classes above are helper classes for Zoo.

Back to top of Panels: Zoo and associated classes or back to top of edu.neu.ccs.gui or back to top of page

Frames

The Java file JPTFrame.java (javadocs)

JPTFrame extends the Java JFrame class for the following purposes.

The same static frame factory methods have also been introduced into the class JPF as convenience methods for testing and experimentation.

The class DisplayPanel has a parallel set of member frame methods that permit a DisplayPanel to frame itself. We call this ability self actualization.

Back to top of Frames or back to top of edu.neu.ccs.gui or back to top of page

Dialogs

The Java file GeneralDialog.java (javadocs)

GeneralDialog creates a dialog box with an arbitrary Component in the upper half of its window and a suitable ActionsPanel in the lower half of its window that contains actions to respond to the data in the Component and to dismiss the dialog. For convenience, the user may supply a general object to be placed in the upper half of the dialog window and this object will be converted to a component using the makeComponent method.

GeneralDialog provides controls to set what happens when the dialog box opens and closes and to choose the default button that will be executed if the user presses the return key. When the dialog is closed, the caller may query if the dialog was cancelled.

GeneralDialog provides static make methods to return simple objects of its own type. This makes it easier to specify common dialogs. GeneralDialog also provides static show methods to both create and show a dialog in one step. If a dialog created via a show method is cancelled, then a CancelledException will be thrown to signal the caller.

The most commonly used constructor for GeneralDialog is:

        GeneralDialog(Object displayObject, String title, Object[][] actionData, boolean modal)

The displayObject is converted into a component using the makeComponent method and placed into the upper half of the dialog window. The 2-dimensional array actionData is used to create the dialog buttons in the lower half of the dialog window. Each sub-array of actionData consists of an Action together with one of the constants from DialogAction that determine what will happen to the dialog after that action is performed.

The Java file DialogAction.java (javadocs)

DialogAction is an ActionWrapper that encapsulates an Action together with information about what should happen to the dialog box when the Action is completed. The options for the completion are:

GeneralDialog uses DialogAction internally. The constructors for GeneralDialog provide an elegant way to specify pairs consisting of an action and a completion operation that will be used to construct the ActionsPanel of the dialog.

The Java file SimpleDialog.java (javadocs)

SimpleDialog consists of static methods to either demand or request via a dialog box an item whose type is one of the following: boolean, char, byte, short, int, long, float, double, or String. There are also static methods to either demand or request via a dialog box any Stringable object that may be returned by the demand or request methods of a TypedView object. The static methods in this class all utilize InputDialog.

The Java file JPTDialog.java (javadocs)

JPTDialog is the base class for dialogs constructed from a TypedView and a set of Action's that are formed into an ActionsPanel.

JPTDialog is a precursor to GeneralDialog. The main difference is that GeneralDialog uses an arbitrary Component while JPTDialog requires a TypedView.

The Java file InputDialog.java (javadocs)

InputDialog extends JPTDialog and provides a modal dialog box for input of a Stringable object using the supplied TypedView object.

The InputProperties for the TypedView determine the input model for the dialog box. In the mandatory model, OK and Reset buttons are provided. In the optional model, a Cancel button is provided in addition to the buttons provided for the mandatory model. If the suggestion property is not-null, then a Suggest button is also provided. The advantage that InputDialog has over GeneralDialog is in the automatic creation of these buttons based on the InputProperties for the TypedView.

InputDialog also provides static convenience methods for input using a supplied TypedView.

The Java file ErrorDialog.java (javadocs)

ErrorDialog extends InputDialog and provides a modal dialog box for input of Stringable objects that is used by the standard error handling strategy for Fragile components in the JPT.

Back to top of Dialogs or back to top of edu.neu.ccs.gui or back to top of page

Applets

The Java file DirectApplet.java (javadocs)

The DirectApplet class provides an abstract base class for building an applet easily by proving a method to create the applet GUI. The designer must build a derived class with one method:

    public Object createGUI()

The object returned by this method should either be a Component or be capable of being converted to such using ComponentFactory.makeComponent. If so, the component will become the GUI content of this applet.

If not, an exception will be thrown and displayed in a dialog. This allows the designer of the applet to get appropriate error feedback which is often difficult to obtain with applets constructed in the traditional fashion.

The derived class of DirectApplet may, of course, have additional helper data and/or methods besides createGUI().

Back to top of Applets or back to top of edu.neu.ccs.gui or back to top of page

Paintable and its implementations

Back to top of edu.neu.ccs.gui or back to top of page

Paintable

The Java file Paintable.java (javadocs)

Paintable is an interface that describes an object that can paint itself onto a graphics context. Paintable was introduced in JPT 2.3.0 and since that time has grown to become a fundamental component in JPT both for the production of output graphics with shapes, images, and text and for the use of graphics in interactive situations. Before discussing the Paintable interface itself, let us summarize the implementation classes.

JPT provides the following classes for the creation of atomic Paintable objects.

JPT provides the following classes that implement the composite pattern of object-oriented design, specifically, that permit a sequence of Paintable objects to be treated as a Paintable.

The Paintable interface currently contains 67 methods that summarize the many behaviors one would like for an entity that paints itself. In addition, Paintable extends the interface SupportsPropertyChange which has 22 additional methods.

Lest you feel that the implementation burden is onerous, let us immediately state that the abstract implementation class AbstractPaintable implements 86 of the required 89 methods and leaves only the following 3 methods to be defined:

The method originalPaint contains the code that paints the object in its pristine state. Any subsequent changes to the object rendering can be handled by other methods. This includes affine transformations (mutations) and changes to opacity and visibility.

The method getActualBounds2D returns the bounding box for the region that will be painted by the method originalPaint. This box may be computed based on what will be painted or it may be computed algorithmically. If the “default original bounds” box is set then this method will be bypassed to eliminate the need for any computation.

The method originalContains returns true if the point (x,y) hits the pixels painted by the method originalPaint or if the point is viewed as “belonging to the object region”. This method is the basis for all subsequent mouse interation with the object.

To understand how a Paintable paints, we need to describle some common aspects of all Paintable objects.

Note: The class PaintableSequence is treated in a special manner in that mutations are passed directly to the consituent paintables in the sequence. This design allows such a sequence to be mutated by a Mutator.Strategy that performs the same conceptual action on the paintables in the sequence but actually applies mathematically distinct transforms. To override this special treatment, wrap a paintable sequence in a Tile or TileBox.

We are now ready to explain how a Paintable paints. Normally, painting is done by a call to the following method:

public void paint(Graphics g)

The method paint operates as follows:

This package implements Paintable classes for shapes, images, and text. The tile classes provide wrappers that allow a paintable to be replicated with independent mutator, opacity, and visibility settings. The clipping wrapper class allows the paintable region to be clipped to an arbitrary shape. Finally, the paintable sequence class allows sequences of paintables to be viewed as a single paintable entity.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

AbstractPaintable

The Java file AbstractPaintable.java (javadocs)

The abstract class AbstractPaintable defines objects that implement Paintable.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintables for shapes

The Java file ShapePaintable.java (javadocs)

ShapePaintable creates an AbstractPaintable using a Shape object and other related data, specifically, a PaintMode strategy, 2 Paint objects for filling the Shape and for drawing its boundary, and a Stroke object for determining how the boundary will be drawn.

The Java file PaintMode.java (javadocs)

The abstract class PaintMode defines the requirements for an object that can control the painting of a ShapePaintable. In fact, a ShapePaintable implements the abstract methods in its base class AbstractPaintable by using the algorithmics of its PaintMode member data object. These algorithmics include the paint operation itself and the computation of the original bounding box (before mutation) and the test for whether a point is among the pixels painted (again before mutation).

PaintMode provides some examples of its own objects as static member data:

PaintMode also provides some static convenience methods to directly fill, draw, or fill_draw a Shape onto a graphics context. These methods create a temporary ShapePaintable to do the work of painting so the effects are identical to those that the user would achieve by explicitly constructing the associated ShapePaintable.

The Java file PointPaintable.java (javadocs)

A PointPaintable creates a Paintable using a point, a PlotMark, and a Paint. When a mutation is applied to a point paintable, it is applied to the position at which the point paintable does its painting but does not affect the shape rendered.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintables for images

The Java file ImagePaintable.java (javadocs)

ImagePaintable creates an AbstractPaintable using one of the following:

The Java file ImagePaintableLite.java (javadocs)

ImagePaintableLite creates an AbstractPaintable using one of the following:

To save memory, an ImagePaintableLite does not cache its image but rather retrieves its image as needed for paint operations. Thus the class trades time for space. This design enables a program to access a much larger collection of images at one time than would be possible by directly using the Java classes Image or ImageIcon or the JPT class ImagePaintable. These other classes all retain the bit data for an image and thus entail a high memory cost.

In practice, Java appears to use some form of caching for images obtained using ImagePaintableLite. Thus, although the impact on main memory is much reduced for an ImagePaintableLite, the speed of refresh for such an image is excellent.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintables for text

The Java file TextPaintable.java (javadocs)

TextPaintable creates an AbstractPaintable using a String to paint, a Font, a Paint object to determine how the String will be painted, a TextBounds strategy to determine whether the bounds will be tight or loose, a TextAnchor strategy to determine what position in the String will be considered the anchor, and finally the (x,y) coordinates of the anchor.

The Java file MultiLineTextPaintable.java (javadocs)

The Java file TextBounds.java (javadocs)

The TextBounds class defines an interface that specifies how to compute accurate bounds for a TextPaintable.

The TextBounds class also defines static objects that implement the interface it defines:

The Java file TextAnchor.java (javadocs)

The TextAnchor class defines interfaces that specify how to compute the location and bounds of a String that will be displayed using a given Font in conjunction with a given anchor position.

The TextAnchor class also defines static objects that implement the interfaces it defines. The static objects used directly by the class TextPaintable are the following:

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintable sequence classes

The Java file PaintableSequence.java (javadocs)

PaintableSequence encapsulates a sequence of Paintable objects. As of 2.4.0, one can supply general Object's rather than Paintable's and the makePaintable method will be invoked to convert the Object's into Paintable's. In particular, if a parameter is of type Object[], then this parameter will be recursively converted into a PaintableSequence that is installed as a single item into this sequence.

Whenever there is a change in the overall mutator for the sequence, this change is immediately applied to the individual items in the sequence. As a consequence, the individual sequence items maintain their own knowledge of the net mutation that must be applied in paint operations. In particular, as far as geometry is concerned, an individual sequence item may be viewed either as part of the sequence or as a stand-alone Paintable. This design decision enables interactive manipulation of sequence items to be handled in a natural fashion.

A PaintableSequence object has a Mutator.StrategyUsage state object that determines whether a Mutator.Strategy should apply to the sequence as a whole or to individual items.

The Java file PaintableSequenceComposite.java (javadocs)

The class PaintableSequenceComposite is a base class for the construction of Paintable classes. Although the class is not abstract, nothing useful can be done with it directly.

A derived class can control exactly what is inserted into the internal PaintableSequence via the protected access method getPaintableSequence() but this sequence is not visible to a public caller. Thus, all features of a PaintableSequence are available to a derived class without public exposure of this implementation.

The class PaintBar is an example of a derived class of PaintableSequenceComposite.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintable wrappers

The Java file Tile.java (javadocs)

Tile will wrap a Paintable in order to allow mutation to occur without changing the internal paintable. This is useful, for example, for games that may use the same paintable to define multiple pieces that must be movable independently.

The Java file TileBox.java (javadocs)

A TileBox is a Tile with a border that may be selected more easily since any point in the box is viewed as within the paintable.

The Java file ClippingWrapper.java (javadocs)

ClippingWrapper will wrap a Paintable and a clipping Shape to obtain a Paintable that clips the original Paintable to the Shape.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintable support classes

The Java file TransformFactory.java (javadocs)

TransformFactory provides a collection of static methods that construct AffineTransform objects for common 2-dimensional transforms. Such transforms need not be centered at the origin. The methods support the computation of both specific transforms and random transforms. In addition, methods are provided to find the composite of a pair of transforms or an array of transforms.

In this class, angle measurement is in degrees not radians. A positive angle is in the direction from the positive x-axis towards the positive y-axis.

The Java file Mutator.java (javadocs)

Class Mutator encapsulates:

The two Mutator.StrategyUsage constants for a PaintableSequence are:

The Java file SupportsPropertyChange.java (javadocs)

SupportsPropertyChange is an interface for objects that can add PropertyChangeListener objects, can fire PropertyChangeEvent events directly to those listeners, and can forward internal PropertyChangeEvent events to those listeners as well.

Many of the methods in this interface are identical to methods found in one or more of the following Java classes:

The Java file PropertyChangeForwardingListener.java (javadocs)

PropertyChangeForwardingListener is a PropertyChangeListener that forwards a PropertyChangeEvent event that it receives to an object that implements the interface SupportsPropertyChange by causing that object to fire the same event to its own listeners.

PropertyChangeForwardingListener is intended to permit PropertyChangeEvent events that are fired within a composite object to be handled by the listeners for the entire object.

More generally, PropertyChangeForwardingListener may be used to forward events to any appropriate object that implements the interface SupportsPropertyChange.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Paintable tools

The Java file PaintableTools.java (javadocs)

PaintableTools collects static methods that construct objects of other types from Paintable objects. The types of objects that may be constructed are as follows:

This functionality means that Paintable objects can integrate smoothly into standard Java graphics classes and components.

The Java file JPTComponent.java (javadocs)

The abstract class JPTComponent extends JComponent in order to:

The Java file PaintableComponent.java (javadocs)

The class PaintableComponent both extends JPTComponent and implements the Java interface Icon. This class uses a Paintable to provide the paint method for the object viewed as a component or as an icon.

The Java file PaintableButton.java (javadocs)

The class PaintableButton extends JButton and uses a Paintable to provide its Icon.

The Java file LayeredComponent.java (javadocs)

LayeredComponent encapsulates a JComponent which is in the foreground of the panel and a background which consists of multiple layers.

The multiple layers of the background are provided as follows:

Both the repeated tile and the topmost Paintable may be provided as general objects. In that case, they are converted to Paintable via ComponentFactory.

Any of the background layers may be null. If all layers are null, however, this panel is not very useful. On the other hand, if all layers are non-null, the background may be too busy and may overwhelm the foreground. Hence, this facility must be used with good taste.

The Java file Refresh.java (javadocs)

Refresh encapsulates a method for graphics refresh. This method is used to refresh the components created by the methods in PaintableTools and may also be used in other contexts.

Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page

Graphics tools

Paint tools

The Java file PaintAlgorithm.java (javadocs)

The interface PaintAlgorithm describes the essentials that a class must provide in order to create a Java BufferedImage and a Java TexturePaint.

The Java file PaintTools.java (javadocs)

The class PaintTools contains static methods that create a Java BufferedImage or a Java TexturePaint from a PaintAlgorithm as well as numerous static methods to manipulate such algorithms or use such algorithms to create new algorithms. Examples include methods to create hatch patterns.

The Java file PaintBar.java (javadocs)

The class PaintBar implements a Paintable that paints a one or two dimensional array of painted disks. The constructor supplies an array of Paint objects, one for each disk. The user can choose the diameter of the disks and the gap between the disks.

As an application, an object of this class may be embedded in a PaintableComponent and used to implement a custom paint selector control.

Back to top of Graphics tools or back to top of edu.neu.ccs.gui or back to top of page

Color tools

The Java file PaintSwatch.java (javadocs)

The class PaintSwatch is a light weight component to draw a rectangular paint swatch with a given Paint, size, and optional Border. This class also implements the Icon interface.

The Java file SwatchNamePair.java (javadocs)

The class SwatchNamePair provides a component with a PaintSwatch and its name. The swatch has the default size and border.

The Java file SwatchNameRenderer.java (javadocs)

The class SwatchNameRenderer is designed to implement ListCellRenderer by providing pairs using a PaintSwatch and its name. The class constructor provides a renderer for the swatch-name pairs generated from the color names in Colors. This class is used to implement the dropdown list in ColorView.

The Java file CheckerBoard.java (javadocs)

CheckerBoard implements a checkerboard in which one can interactively contrast two colors. This is useful for a developer in planning color combinations because it is often difficult to tell how two colors will look when placed side by side. The board is rendered in a BufferedPanel. Normally, a CheckerBoard object also comes with two ColorView dropdown panels that may be used to interactively select the contrasting colors and a button that will reset the colors to their original state. However, it is also possible to omit these interactive controls and then the panel may be used for board games such as checkers and chess. To do this, one may add Paintable game pieces to the internal BufferedPanel and then may manipulate these pieces either programmatically or by using the mouse.

To execute CheckerBoard in an applet, click on the screen snapshot below.

CheckerBoard snapshot

The Java file VisualColorList.java (javadocs)

VisualColorList displays the named colors as defined in the class Colors in a scroll pane using a square color swatch and 3 labels for each color: the color name, the RGB or RGBA in decimal, and the hexadecimal value. The programmer has some control of the swatch size and pane height of the scroll pane. This class is primarily intended to provide color information not to be used as a GUI control. However, for convenience, the panel also includes an instance of ColorView so the user may do some simple experiments with single colors.

To execute VisualColorList in an applet, click on the screen snapshot below.

VisualColorList snapshot

The Java file VisualColorSampler.java (javadocs)

VisualColorSampler combines a VisualColorList and a CheckerBoard side by side. This permits more flexible experiments with color.

To execute VisualColorSampler in an applet, click on the screen snapshot below.

VisualColorSampler snapshot

Back to top of Graphics tools or back to top of edu.neu.ccs.gui or back to top of page

Image tools

For convenience, we first list here three classes related to images that are also listed elsewhere.

The Java file ImagePaintable.java (javadocs)

ImagePaintable creates an AbstractPaintable using one of the following:

The Java file ImagePaintableLite.java (javadocs)

ImagePaintableLite creates an AbstractPaintable using one of the following:

To save memory, an ImagePaintableLite does not cache its image but rather retrieves its image as needed for paint operations. Thus the class trades time for space. This design enables a program to access a much larger collection of images at one time than would be possible by directly using the Java classes Image or ImageIcon or the JPT class ImagePaintable. These other classes all retain the bit data for an image and thus entail a high memory cost.

In practice, Java appears to use some form of caching for images obtained using ImagePaintableLite. Thus, although the impact on main memory is much reduced for an ImagePaintableLite, the speed of refresh for such an image is excellent.

The Java file ImageCapsule.java (javadocs)

ImageCapsule is a JComponent encapsulating an Image.

The construction of a component using ImageCapsule may be achieved via:

        new ImageCapsule(image);

A similar effect may now be achieved via:

        PaintableTools.makeComponent(new ImagePaintable(image));

The advantage of ImageCapsule is that the component can be constructed without the nested calls. The disadvantage is that the full range of choices built into ImagePaintable are not available.

We now list the additional classes that support images.

The Java file ImageTools.java (javadocs)

The class ImageTools contains tools to read image files from a local directory on disk and return these files as arrays of any of the following types:

The tools can read all images in a given directory; read the images listed in a text file that contains a list of image file names; or read a list of images whose file names are contained in a String array.

The Java file WebImageTools.java (javadocs)

The class WebImageTools contains tools to read image files from the web and return these files as arrays of any of the following types:

The tools can read read the images listed in a text file that contains a list of image file names or read a list of images whose file names are contained in a String array. If the image list is obtained from a file, that file may reside in the same web location as the images or may be located at a different URL if that is more convenient.

The Java file ImageViewer.java (javadocs)

The class ImageViewer creates an image viewer for a list of local image files. The images will be displayed in a vertical list and each image will be annotated with its file name, its image dimensions, and the index of the file in the file list. The caller may select whether to show images at full size or to autoscale so that each image fits within the available scrollpane viewport.

In tests, this class was able to display more than 100 large images at once. This is due to the use of the class ImagePaintableLite which requires only a small memory footprint. Using standard Java tools, the attempt to display the same images led to memory overflow.

The Java file WebImageViewer.java (javadocs)

The class WebImageViewer creates an image viewer for a list of web image files. The images will be displayed in a vertical list and each image will be annotated with its file name, its image dimensions, and the index of the file in the file list. The caller may select whether to show images at full size or to autoscale so that each image fits within the available scrollpane viewport.

In tests, this class was able to display more than 100 large images at once. This is due to the use of the class ImagePaintableLite which requires only a small memory footprint. Using standard Java tools, the attempt to display the same images led to memory overflow.

The Java file ImageViewerBase.java (javadocs)

The class ImageViewerBase is the base class that contains the common GUI code for ImageViewer and WebImageViewer. Its constructor is protected so it may not be directly instantiated.

The Java file RequestImageViewer.java (javadocs)

The class RequestImageViewer creates a simple GUI so that the end user may provide the directory and image file list name to construct an ImageViewer for images on the local file system.

The image file list text file is optional. If omitted, all images in the directory will be displayed in lexicographic order.

The Java file RequestWebImageViewer.java (javadocs)

The class RequestWebImageViewer creates a simple GUI so that the end user may provide the web URLs and image file list name to construct a WebImageViewer for images on the web.

The image file list text file is mandatory since there is no way to obtain the list of all images in a web directory by direct means.

Back to top of Graphics tools or back to top of edu.neu.ccs.gui or back to top of page

Capsule classes

The Java file ShapeCapsule.java (javadocs)

ShapeCapsule is JComponent encapsulating a Shape and a fill Paint and acting as a view for this filled shape.

The construction of a component using ShapeCapsule may be achieved via:

        new ShapeCapsule(shape, paint);

A similar effect may now be achieved via:

        PaintableTools.makeComponent(new ShapePaintable(shape, null, paint));

The advantage of ShapeCapsule is that the component can be constructed without the nested calls. The disadvantage is that the full range of choices built into ShapePaintable are not available.

The Java file ImageCapsule.java (javadocs)

ImageCapsule is a JComponent encapsulating an Image.

The construction of a component using ImageCapsule may be achieved via:

        new ImageCapsule(image);

A similar effect may now be achieved via:

        PaintableTools.makeComponent(new ImagePaintable(image));

The advantage of ImageCapsule is that the component can be constructed without the nested calls. The disadvantage is that the full range of choices built into ImagePaintable are not available.

Back to top of Graphics rools or back to top of edu.neu.ccs.gui or back to top of page

Shape classes

General definitions

The Java file ClosureMode.java (javadocs)

ClosureMode encapsulates as objects the choices for the closure mode of a polygon or bezier cubic curve. The closure modes are:

The Java file WindingRule.java (javadocs)

WindingRule encapsulates as objects the two constants from GeneralPath: WIND_NON_ZERO and WIND_EVEN_ODD. The winding rules are:

Back to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page

Classes based on a vertex-tangent concept

The Java file BaseShape.java (javadocs)

BaseShape encapsulates a Shape defined using vertex and tangent data.

Specifically, BaseShape encapsulates:

A BaseShape is parametrized by three additional settings:

BaseShape contains the common code and data for several derived classes.

Although not abstract, BaseShape may not be instantiated directly since it does not have a public constructor.

The Java file BaseVertexShape.java (javadocs)

BaseVertexShape extends BaseShape to provide the common functionality for those classes that either do not use the tangent data of BaseShape or compute the tangent data automatically using the vertex data and other internal settings.

Although not abstract, BaseVertexShape may not be instantiated directly since it does not have a public constructor.

The Java file PolygonShape.java (javadocs)

PolygonShape extends BaseVertexShape and fixes its Path.Strategy to be Path.POLYGON. This class does not use the tangent array inherited from BaseShape.

The Java file PolygonDotsShape.java (javadocs)

PolygonDotsShape extends BaseVertexShape and fixes its Path.Strategy to be Path.POLYGON_DOTS. This class does not use the tangent array inherited from BaseShape.

The Java file RegularShape.java (javadocs)

Class RegularShape provides factory methods to create regular polygons and regular star shapes.

This class also provides the mathematical methods that return the vertex arrays in case the caller wishes to deal directly with this data.

The Java file AutomaticShape.java (javadocs)

AutomaticShape implements a BaseShape in which the tangent array is always computed from the vertex array automatically using a Tangent.Strategy object.

The default tangent strategy produces Bézier curves in which the first and second derivatives of the curve are continuous at each vertex. This strategy is described in the article:

Richard Rasala, Explicit Cubic Spline Interpolation Formulas, in Andrew S. Glassner, Graphics Gems, Academic Press, 1990, 579-584.

To define a shape in which the tangent array varies independently of the vertex array, use the class TweakableShape.

The Java file AutomaticCurve.java (javadocs)

AutomaticCurve extends AutomaticShape and fixes its Path.Strategy to be Path.BEZIER_CUBIC.

The Java file TweakableShape.java (javadocs)

TweakableShape implements a BaseShape in which the vertex array and the tangent array may be changed independently of one another.

To define a shape in which the tangent array is computed from the vertex array automatically, use the class AutomaticShape.

The Java file TweakableCurve.java (javadocs)

TweakableCurve extends TweakableShape and fixes its Path.Strategy to be Path.BEZIER_CUBIC.

The Java file Tangent.java (javadocs)

Tangent encapsulates an interface Strategy that defines the requirement for a strategy that can automatically use the vertex array and boundary information to generate the tangent array for Bézier curves.

Tangent provides some examples of Strategy objects via factory methods and also makes their methods directly available as public static methods in the class to permit others to create Strategy objects.

The factory method bezierStrategy encapsulates the strategy discussed in the article:

Richard Rasala, Explicit Cubic Spline Interpolation Formulas, in Andrew S. Glassner, Graphics Gems, Academic Press, 1990, 579-584.

The factory method chordStrategy encapsulates a strategy in which the tangent at a given vertex is some fixed fraction of the chord joining the two adjacent vertices.

The Java file Path.java (javadocs)

Path encapsulates an interface Strategy that defines the requirement for a strategy that can automatically build a GeneralPath given:

Path also provides some examples of Strategy objects and some useful static methods. The Strategy objects are:

The most useful static methods in Path are:

Back to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page

Classes based on a path list with move, line, quad, cubic, and close operations

The Java file PathNode.java (javadocs)

PathNode defines a data structure for one segment of a path. It uses simplified path constants MOVE, LINE, QUAD, CUBIC, and CLOSE that are equal to the corresponding complicated constants in GeneralPath. The class methods allow one to set individual segment coordinates or x,y coordinate pairs in a easy manner.

The Java file PathList.java (javadocs)

PathList defines a data structure for a general path that consist of a WindingRule and a list data structure of PathNode objects that may be flexibly created, edited, and searched. Although this class ultimately uses the Java class GeneralPath to construct Shape objects, this class provides far more flexibility than GeneralPath. It is therefore possible to easily use this class for interactive graphics.

Below is a screen snapshot of the Shape Editor demo applet that uses a PathList to specify the MOVE, LINE, QUAD, CUBIC, and CLOSE path segments that constitute the path for the shape. The path segment data on the left hand side is reflected in the shape structure painted on the right hand side. Once a shape is designed and painted, the user may change the shape by dragging the vertex points or the control points.

Shape Editor Image

For more details about this demo applet, click on the link above or on the screen snapshot.

The Java file PathListFunction.java (javadocs)

Class PathListFunction contains methods to compute one or more points on a path that is defined by a PathList given a parameter t.

The Java file PathListIterator.java (javadocs)

PathListIterator provides a Java PathIterator based on a PathList This class is not really essential since Shape creation may be very efficiently done directly in class PathList.

Furthermore, Java has serious performance problems when it attempts to append to an existing path using a PathIterator. Therefore we recommend working directly with PathList whenever possible.

The Java file PathNodeView.java (javadocs)

PathNodeView provides a view for setting PathNode data through a GUI.

The Java file PathListView.java (javadocs)

PathListView provides a view for setting PathList data through a GUI. This view uses a SimpleArrayPanel to allow the user to control the number and contents of the PathNode objects in the list.

Back to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page

Area Computation

The Java file AlgebraicArea.java (javadocs)

The AlgebraicArea class provides static methods to compute the signed area of a Java Shape and of a JPT PathList object. The area computation is based on calculus. Since any Shape or PathList is built by a combination of 5 commands (move, line, quad, cubic, and close), the calculus may be done in advance and the area reduced to algebraic formulas in the x,y coordinates of the path data.

Back to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page

Actions and threads

The Java file SimpleAction.java (javadocs)

SimpleAction is an abstract class that is a simple extension of the Java AbstractAction class. It is used to simplify the programming interface for an object representing a GUI action that requires no parameters.

To implement a SimpleAction, one must extend the abstract class and define the following method with no parameters:

    public void perform()

Since a SimpleAction is a data member and a data member may have the same name as a method, there is a convenient convention in which the perform method is implemented by calling a class method whose name is identical to that of the SimpleAction. Here is the template:

    private SimpleAction name_of_action =
        new SimpleAction("name as text string") {
            public void perform() { name_of_action(); }
        };

Notice that name_of_action in line 1 is the member data being defined and name_of_action in line 3 is the method call. The method must of course be defined elsewhere in the class. Notice also that this definition template uses an anonymous inner class to, in effect, convert a class method into an object. It is therefore analogous to a simple lambda expression.

Java can construct a JButton from an Action and hence from a SimpleAction. ComponentFactory converts an Action automatically into a JButton and ditto for a SimpleAction. Therefore, to define a GUI button in the JPT panel constructors and methods that use ComponentFactory behind the scenes, it is enough to provide a SimpleAction. This is very convenient because it allows the caller to think about the behavior represented by the action and not about the actual button.

Note that, for convenience, SimpleAction also implements ChangeListener and PropertyChangeListener.

The Java file SimpleThreadedAction.java (javadocs)

SimpleThreadedAction is an abstract class that is a simple extension of the Java AbstractAction class. It is used to simplify the programming interface for an object representing a GUI action that requires no parameters and that must be performed in a new separate thread each time the action is executed.

In a manner parallel to SimpleAction, to implement a SimpleThreadedAction, one must extend the abstract class and define the following method with no parameters:

    public void perform()

The SimpleThreadedAction class has a predefined method

    public void performThreaded()

that will execute the perform() in a separate thread each time that it is invoked. The action of the class is performed by calling the method performThreaded() rather than the method perform(). In particular, if a button is constructed from a SimpleThreadedAction, its behavior will automatically run in a separate threaded.

See also ThreadedAction.

The Java file ActionSequence.java (javadocs)

ActionSequence implements the composite pattern for Action objects by maintaining a list of such objects and then executing them in sequence when its own actionPerformed method is called.

The Java file ActionWrapper.java (javadocs)

ActionWrapper is the base class for encapsulating an Action object and producing a new Action object that adds extra functionality on top of the original functionality.

The Java file ThreadedAction.java (javadocs)

ThreadedAction is an ActionWrapper that performs its encapsulated Action in a newly created separate thread.

Using ThreadedAction makes it extremely easy to ensure that actions launched from a GUI run in separate threads from the GUI thread. This technique is used, in particular, for all buttons in the Java Power Framework user interface.

See also Action adapters

Back to top of Actions and threads or back to top of edu.neu.ccs.gui or back to top of page

Action adapters

The purposes of the classes in this category is to adapt event handlers to fit into the ActionListener paradigm and, in particular, to be able to use ActionSequence for storage of one or more of the handlers (see also Actions and threads).

Normally, these handlers form groups of three classes:

The name signifies what is being adapted. Since there are nine groups of three adapters that are all quite similar, we will describe only one group, namely, Mouse adapters. The other groups that we have found particularly useful are Key adapters and Window adapters. The remaining adapters are used only in special situations.

The Java file MouseAction.java (javadocs)

The abstract class MouseAction extends AbstractAction and encapsulates an action that is performed as a result of a MouseEvent.

To instantiate a MouseAction object, one must define the method:

        public void mouseActionPerformed(MouseEvent mevt)

This object instantiation is frequently done inline using an anonymous inner class that calls a corresponding method in the enclosing class.

The Java file MouseActionAdapter.java (javadocs)

A MouseActionAdapter can be constructed to listen to a specific Component or this Component may be set later. The MouseActionAdapter can add, remove, set, or get actions to take place if any of the seven standard MouseEvent's takes place within the Component. To illustrate what is possible, we list the seven add methods that add a single ActionListener:

The Java file MouseActionEvent.java (javadocs)

MouseActionEvent is an adapter event class that extends ActionEvent and that represents an action triggered by a MouseEvent.

Normally, the use of MouseActionEvent is internal to JPT and thus this class does not need to be a concern for the designer.

The Java file KeyAction.java (javadocs)

The Java file KeyActionAdapter.java (javadocs)

The Java file KeyActionEvent.java (javadocs)

The Java file WindowAction.java (javadocs)

The Java file WindowActionAdapter.java (javadocs)

The Java file WindowActionEvent.java (javadocs)

The Java file ChangeAction.java (javadocs)

The Java file ChangeActionAdapter.java (javadocs)

The Java file ChangeActionEvent.java (javadocs)

The Java file ComponentAction.java (javadocs)

The Java file ComponentActionAdapter.java (javadocs)

The Java file ComponentActionEvent.java (javadocs)

The Java file FocusAction.java (javadocs)

The Java file FocusActionAdapter.java (javadocs)

The Java file FocusActionEvent.java (javadocs)

The Java file ListSelectionAction.java (javadocs)

The Java file ListSelectionActionAdapter.java (javadocs)

The Java file ListSelectionActionEvent.java (javadocs)

The Java file PaintAction.java (javadocs)

The Java file PaintActionCapsule.java (javadocs)

The Java file PaintActionEvent.java (javadocs)

The Java file PropertyChangeAction.java (javadocs)

The Java file PropertyChangeActionAdapter.java (javadocs)

The Java file PropertyChangeActionEvent.java (javadocs)

Back to top of Action adapters or back to top of edu.neu.ccs.gui or back to top of page

GUIs for expressions, function definitions, and function plots

The Java file ExpressionEvaluationPane.java (javadocs)

ExpressionEvaluationPane defines a pane in which an expression can be evaluated to produce a BigInteger, double, or boolean value. The pane may be installed in a larger GUI or launched in a stand-alone frame.

To execute ExpressionEvaluationPane in an applet, click on the screen snapshot below.

ExpressionEvaluationPane snapshot

The Java file SimpleFunctionPane.java (javadocs)

SimpleFunctionPane defines a pane in which a SimpleFunction object may be defined or removed by an interactive user. The pane may be installed in a larger GUI or launched in a stand-alone frame.

The Java file SimpleFunctionBuilder.java (javadocs)

SimpleFunctionBuilder is a pane that combines a SimpleFunctionPane with an ExpressionEvaluationPane to permit both definition and testing of simple functions. The pane may be installed in a larger GUI or launched in a stand-alone frame.

To execute SimpleFunctionBuilder in an applet, click on the screen snapshot below.

SimpleFunctionBuilder snapshot

The Java file SimpleFunctionPaneWithIO.java (javadocs)

SimpleFunctionPaneWithIO defines a pane in which a SimpleFunction object may be defined or removed by an interactive user and, in addition, the user may save such definitions to a file and read them back into the parser at a later time. The pane may be installed in a larger GUI or launched in a stand-alone frame.

The Java file SimpleFunctionBuilderWithIO.java (javadocs)

SimpleFunctionBuilderWithIO is a pane that combines a SimpleFunctionPaneWithIO with an ExpressionEvaluationPane to permit both definition and testing of simple functions as well as saving and reading back such definitions. The pane may be installed in a larger GUI or launched in a stand-alone frame.

The Java file FunctionsPlotter.java (javadocs)

FunctionsPlotter is an end-user tool for plotting functions of one parameter. The tool provides two panes:

Functions are plotted in different colors and a MultiColorView object shows which colors are assigned to which functions. Using this view, the user may change the default color settings.

The FunctionsPlotter pane may be installed in a larger GUI, launched in a stand-alone frame, or executed in an applet.

To execute FunctionsPlotter in an applet, click on either screen snapshot below.

The first snapshot shows the definition of an example function expsin. The definition is completed by clicking “Define Function”. The second snapshot shows a plot of the built-in function exp and the newly defined function expsin on the range from -3 to +3.

Function Definition Pane: Definition of expsin

FunctionsPlotter function definition pane snapshot

Function Plot Pane: Plot of exp and expsin

FunctionsPlotter function plot pane snapshot

Back to top of GUIs or back to top of edu.neu.ccs.gui or back to top of page

Data and function plot tools

The Java file PlotTool.java (javadocs)

PlotTool encapsulates the transform between world and image coordinates for use in plotting data graphs.

The world coordinate space refers to the coordinate space inhabited by the data arrays or functions that are to be plotted.

The image coordinate space refers to the coordinate space of the graphics context on which the plots are painted.

Using its encapsulated transform, a PlotTool object provides methods to plot or mark data on a Java Graphics2D graphics context. PlotTool provides functions to plot or mark an array of Point2D data or an array of such Point2D arrays. PlotTool automatically handles the painting of grid lines, axes, and tick marks on the axes.

The Java file PlotMark.java (javadocs)

PlotMark is a helper class for drawing geometric shapes or marks at a specified point in a graphics context.

The Java file PlotMarkAlgorithm.java (javadocs)

PlotMarkAlgorithm defines the requirements for an algorithm that will produce a scalable shape defined in the neighborhood of a given point.

The Java file DataTables2D.java (javadocs)

Class DataTables2D provides static methods to create data tables from functions of type Function.OneArg.

The data tables may be used for plotting with the plot tools, for numerical processing, or for associating values with weights in probability.

The Java file Transform1D.java (javadocs)

Transform1D encapsulates a 1-dimensional transform for simple affine scaling and for working with the components of a Java 2-dimensional AffineTransform that is “rectilinear”, that is, has “zero values off the diagonal”.

A Transform1D has the mathematical form: z --> factorz + offset.

Back to top of Data and function plot tools or back to top of edu.neu.ccs.gui or back to top of page

Look and feel tools

The Java file LookAndFeelTools.java (javadocs)

LookAndFeelTools contains several static methods that assist in using the Java look-and-feel facilities.

The most important static method is showSelectLookAndFeelDialog that permits the user to select from among the installed look-and-feel options and that also permits the user to change the default font sizes in a systematic manner by a small increment or decrement. This functionality is particularly useful in teaching situations in which instructors and students wish to see what happens to a GUI using different look-and-feel choices.

Another important static method is adjustAllDefaultFontSizes that will increment all of the many default font sizes by the same amount. This functionality is particularly useful in teaching situations in which the default font sizes may be too small to be seen by students when using computer projection. An instructor may call this method once prior to opening any windows and all fonts will become suitably larger.

In general, the methods in this class must be called prior to the opening of any window frame or other dialog box to avoid having different look and feel settings in different windows.

Back to top of edu.neu.ccs.gui or back to top of page

Font tools for GUIs

The Java file Fonts.java (javadocs)

Fonts provides static methods to obtain the names of all installed fonts and also to provide better default fonts for monospaced, serif, and sans serif fonts.

The Java file FontSampler.java (javadocs)

FontSampler provides a GUI to enable a user to see samples of any installed font for the classical character range from ASCII 32 to ASCII 126.

Back to top of Font tools or back to top of edu.neu.ccs.gui or back to top of page

File IO and file dialogs

The Java file TextFileIO.java (javadocs)

TextFileIO automates the process of saving or reading text files including the file dialog steps.

The Java file StringableFileIO.java (javadocs)

StringableFileIO automates the process of saving or reading a Stringable object to and from text files including the file dialog steps.

The Java file FileView.java (file selection by dialog) (javadocs)

The FileView class is a TypedView for input of a filename that either represents a path to an existing file or a path to which a file could be written. Provides a button that brings up a JFileChooser for easy choice of an existing file.

Back to top of File IO and file dialogs or back to top of edu.neu.ccs.gui or back to top of page

Error handling

The Java file Fragile.java (javadocs)

Fragile is an interface to be implemented by classes of graphical interface components whose view state may be malformed. This is most appropriate for user editable fields, but also may be appropriate for other interface controls that may not be malformed but could have a view state outside of a valid range.

This interface only specifies that the component must be able to register and deregister objects from receiving notification when the component is found to have a malformed view state and when the view state of the component is returned to a well-formed value.

The Java file AlertEvent.java (javadocs)

AlertEvent is a class of AWTEvent's that designates that a graphical input object should enter or exit alert status.

The Java file AlertListener.java (javadocs)

AlertListener is an interface to be implemented by a graphical interface component capable of altering its visualization to signal a user alert state.

The Java file MalformedDataEvent.java (javadocs)

MalformedDataEvent extends AlertEvent and defines a class of events that designates that a graphical input object has just been verified to have a malformed view state, or has just had its previously malformed view state restored to a well-formed state.

The Java file MalformedDataListener.java (javadocs)

MalformedDataListener is an interface extending AlertListener that should be implemented by graphical interface components that desire to be notified when Fragile interface components encounter malformed data.

Back to top of Error handling or back to top of edu.neu.ccs.gui or back to top of page

Miscellaneous

The Java file KeyPressReleaseListener.java (javadocs)

KeyPressReleaseListener provides a listener that is capable of keeping track of the state of multiple keys pressed at once on the keyboard. This class works on a "best effort" basis since if too many keys are pressed at once the hardware ceases to deliver the information. The limit of keys that can be detected at once varies with the hardware.

The Java file Borders.java (javadocs)

Borders provides the static methods that underlie the border tools that have been integrated in 2.5.0 into DisplayPanel. This class may be seen as an elaboration on the Java class BorderFactory.

Back to top of edu.neu.ccs.gui or back to top of page

Java Source Files in edu.neu.ccs.jpf (7 files)
The Java Power Framework for Experiments and Tests

The Java file JPF.java (javadocs)

The Java Power Framework class JPF provides the foundation for creating an automatic Java GUI application with access to the JPT console and a graphics window and to automatically created action buttons. Specifically, the automatic objects available are:

The automatic action buttons are created from the public methods in the class (or chain of classes) derived from JPF that satisfy the following conditions.

The arguments and return types of the public methods may be chosen from the following types:

In addition, the return types of the public methods may also be chosen from the following types:

For each public method that satisfies the above conditions, there is an action button created that executes the method. Method names may be overloaded. The tooltip that is shown when the mouse hovers over an action button will give the full method signature. For a method that has non-trivial arguments or a non-void return type, the click of the action button will bring up an auxiliary GUI so the arguments may be provided and the return value may be shown.

The creation of the automatic Java GUI application is accomplished by a combination of Java reflection and the use of the rest of the Java Power Tools. Since these techniques are encapsulated, the Java Power Framework may be used equally for experiments by beginners and for testing by serious developers.

To use the Java Power Framework class JPF, simply define a class that extends JPF, directly or indirectly, and execute a constructor on that new class. The constructor may implicitly call the default JPF constructor or may call one of the non-default JPF constructors using super.

For example, if a class named Methods extends the class JPF, directly or indirectly, then all public methods that satisfy the above constraints and are defined either in the class Methods itself or in some intermediate class between Methods and JPF will give rise to action buttons in the automatically generated GUI application. These action buttons will execute the methods used to define them.

The structure of a typical Methods class that directly extends JPF will therefore look as follows:

public class Methods extends JPF {

    public static void main(String[] args) { new Methods(); }

    // enter here any member or static data declarations as desired

    // enter here the public methods to be made into action buttons

    // enter here any non-public helper methods as desired
}

The Java Power Framework may be used to create action buttons in an automatically generated application for any of the following purposes:

To illustrate how to define a method to launch a separate Java application that we will name, for convenience, Foo, here is the code:

public void LaunchFoo() { Foo.main(null); }

Placing this code in the Methods class will cause a button to be created in the automatic GUI that is labeled LaunchFoo and that launches the application Foo when clicked.

It is also possible to pass arguments to the main method of a class Foo in LaunchFoo. As on a typical command line, the arguments will be typed in by the user as a String which will then be converted to a String[] as required by main. The conversion of arguments to a String[] is done by the helper method Strings.tokenize.

public void LaunchFoo(String arguments) {
    Foo.main(Strings.tokenize(arguments, " \t\n", false));
}

Notice that the above code parses the arguments parameter using blank, tab, and newline. This actually enables multiline arguments should that be convenient. See Example 4 for more details.

It is sometimes desirable to set the look-and-feel via the tools in the class LookAndFeelTools. Calls to such methods should be made in main prior to any constructor invocation for class Methods.

We now give some concrete examples.

Example 1

Let us create a Methods class with one method ShowCircle() that creates a red circle with a black border and places this entity in the graphics window. For this example, we will use a small amount of JPT.

import edu.neu.ccs.*;
import edu.neu.ccs.gui.*;
import edu.neu.ccs.jpf.*;

import java.awt.*;

public class Methods extends JPF 
{
    public static void main(String[] args) { new Methods(); }
            
    public void ShowCircle() {
        Shape circle = new XCircle(100, 100, 50);
                
        ShapePaintable paintable =
            new ShapePaintable
                (circle, PaintMode.FILL_DRAW, Color.red, Color.black);
        
        window.clearSequence();
        window.appendPaintable(paintable);
        window.repaint();
    }
}

Here is a screen snapshot of the automatic GUI that is created when this class is executed and the button ShowCircle is clicked.

JPF Sample 1 Snapshot

The method ShowCircle() is used to automatically create the topmost green button labeled “ShowCircle”. When this button is clicked, the red and black circle is added to the graphics window as a ShapePaintable.

The 4 yellow buttons and the red button are automatically created for any JPF GUI. The yellow button Clear Graphics will clear the contents of the graphics window. The yellow button Graphics Snapshot will snapshot the current state of the graphics window and show that in a separate frame. The 2 yellow Toggle buttons will hide or show the graphics window and the JPT console window. As of 2.7.0, the console is initially hidden. The red Exit button will terminate the program.

Example 2

As we work, we keep a starter version of a Methods class that will make it easy to run experiments and tests. This file is:

Methods.java

The key features of this file are:

Here is a variation of this Methods class with some of the commented portions made active. The imports are not shown.

public class Methods extends JPF 
{
    public static void main(String[] args) {
        LookAndFeelTools.adjustAllDefaultFontSizes(6);
        
        Methods methods = new Methods();

        methods.window.installSimpleMouseActions(true);
    }
    
    public void Test() {
        Shape shape1 = new XRect(100, 100, 100, 50);
        
        Paintable paintable1 =
            new ShapePaintable
                (shape1, PaintMode.FILL_DRAW, Colors.red);
        
        Shape shape2 = new XOval(150, 125, 100, 50);
        
        Paintable paintable2 =
            new ShapePaintable
                (shape2, PaintMode.FILL_DRAW, Colors.yellow, Colors.blue);
        
        window.clearSequence();
        window.appendPaintable(paintable1);
        window.appendPaintable(paintable2);
        window.repaint();
    }
}

You will notice that default font sizes have been increased by 6. This will be apparent in the snapshots below. Also, the mouse dragging behavior has been installed in the graphics window. The parameter true requests that a clicked Paintable always be lifted to the top of the stack. Finally, the code for the Test method has been uncommented.

The Test method creates 2 Shape objects, a rectangle and an oval, and then encapsulates these in ShapePaintable objects that set the painting mode, the fill color, and the draw color when it is not the default of black. Here is a snapshot immediately after the Test method has been executed.

Snapshot 1 of the Test method

In the above snapshot, the rectangle is on top of the oval. In the second snapshot, we see the effect of dragging the paintables. In particular, the oval is now on top of the rectangle.

Snapshot 2 of the Test method

This example illustrates how much can be accomplished with a few lines of code in a JPF-based Methods class.

Example 3

Next, let us show how JPF deals with methods that have simple arguments and a simple return value. In the example, the method Evaluate accepts one double as an argument and returns double.

        import edu.neu.ccs.jpf.*;

        public class Methods extends JPF 
        {
            public static void main(String[] args) { new Methods(); }
            
            public double Evaluate(double x) { return x; }
        }

In the automatic JPF GUI, an “Evaluate” button will be created but when this button is clicked it must construct and display an auxiliary GUI to handle the argument and return. This auxiliary GUI is shown in the screen snapshot below:

JPF Sample 2 Snapshot

In the auxiliary GUI, the green-arrow input icon shows the user where to enter the argument while the red-arrow output icon shows the user where to find the return value. The yellow-loop icon stands for the work that will be done when the method executes. The method is executed by clicking the button named by the method, in this case, Evaluate, or by pressing return in an input text field.

This example also illustrates that anywhere in JPT one can enter a numeric argument as an arithmetic expression. The evaluation of the expression will be done automatically upon input. What is not illustrated but is also true is that if the user makes an error in input then an error dialog will automatically appear that allows the user to recover gracefully.

The ability of JPF to automatically generate GUIs for methods with arguments and/or return values makes JPF an extremely flexible tool for software testing. The example above shows input/output using a text field. This is suitable for the Java primitive types. If JPF detects that input or output could potentially require a multi-line string then a text area will be used with scrollbars available if needed.

Note: A more powerful version of the expression evaluation feature is provided by the class ExpressionEvaluationPane and by the related classes discussed immediately thereafter.

Example 4

In the introductory discussion above, we explained how JPF might be used to create a button LaunchFoo to launch a Java class Foo that has a method main. Let us illustrate this.

In the Methods class below, the method LaunchFoo will launch the main method of class Foo. The user will provide arguments as a whitespace separated String that will be converted to a String[] using the helper method Strings.tokenize. The array will then be passed to Foo.main. The sample includes a test class Foo that simply lists the number of arguments and then lists each argument individually on a separate line.

import edu.neu.ccs.*;
import edu.neu.ccs.jpf.*;

public class Methods extends JPF 
{
    
    public static void main(String[] args) { new Methods(); }
    
    // notice user enters one string not an array
    public void LaunchFoo(String arguments) {
        Foo.main(Strings.tokenize(arguments, " \t\n", false));
    }
    
}

class Foo {
    
    public static void main(String[] args) {
        if (args == null) {
            System.out.println("args is null");
            return;
        }
        
        int n = args.length;
        
        System.out.println("args length: " + n);
        
        for (int i = 0; i < n; i++)
            if (args[i] != null)
                System.out.println("args[" + i + "] = " + args[i]);
    }
}

Here is a screen snapshot of the automatic JPF GUI into which the user can enter the arguments as a whitespace separated String. In this example, the test String is The quick brown fox jumped over the lazy dog.

Snapshot of Launch Foo method

Here is the test output printed after the LaunchFoo button is clicked.

args length: 9
args[0] = The
args[1] = quick
args[2] = brown
args[3] = fox
args[4] = jumped
args[5] = over
args[6] = the
args[7] = lazy
args[8] = dog

If the user provides an empty String then the test output will correctly state:

args length: 0

Back to top of edu.neu.ccs.jpf or back to top of page

The Java file JPFApplet.java (javadocs)

The Java Power Framework class JPFApplet provides the ability to demonstrate JPF-like code in an applet. This can be useful for pedagogical purposes because it enables faculty to quickly create demonstration programs and then to deploy them for students as applets. The creation of the JPFApplet class was the primary motivation for the 2.7.0 release of JPT.

For general information, first read the documentation for JPF.

The graphics window is shown by default. Furthermore, there is no button to toggle the visibility of the graphics window. This is because the pane for the applet is embedded in a web page and we did not wish the dimensions of the pane to change after the pane is rendered on the page.

JPFApplet has some restrictions and some alternate facilities.

For samples of applets using JPFApplet, see the JPT 2.7.0 Applets Page.

As with JPF, there is starter file named MethodsApplet to make it easy to run experiments and tests in applets. This file is:

MethodsApplet.java

Back to top of edu.neu.ccs.jpf or back to top of page

The Java file JPFPane.java (javadocs)

The responsibility of JPFPane is to collect the common code for building the GUIs for JPF and JPFApplet. Among the tasks of JPFPane is to gather the methods that should be installed as buttons in the automatic GUI. This task uses the general tools of JPFHelper. The pane JPFPane is designed so that it may also be used in a standalone fashion to study the behavior of methods on objects of more general classes. For an example, see the JPT 2.7.0 Applets Page.

Back to top of edu.neu.ccs.jpf or back to top of page

The Java file MethodGUI.java (javadocs)

The responsibility of MethodGUI is to build the auxiliary GUI needed for a method that has parameters and/or a return value. For an example of a parameter-return GUI, see the screen snapshot above.

The Java file ActivityIcon.java (javadocs)

The responsibility of ActivityIcon is to build the three icons used when an auxiliary parameter-return GUI is displayed. For an example of each icon in a parameter-return GUI, see the screen snapshot above.

The Java file JPFHelper.java (javadocs)

The responsibility of JPFHelper is to adapt the tools provided by Java in class Class and in java.lang.reflect to the specific goals of the Java Power Framework.

The Java file MethodFilter.java (javadocs)

The responsibility of MethodFilter is to provide abstractions that help to prune the lists of methods produced by the method getPublicMethods() in class JPFHelper.

Back to top of edu.neu.ccs.jpf or back to top of page

Java Source Files in edu.neu.ccs.parser (11 files)
IO Parse Routines and Simple Functions

These classes implement the behind-the-scenes arithmetic and boolean expression evaluation that is used in all input operations from the console or from text fields. As a consequence, the user may type expressions rather than simply numbers or true/false when entering String input.

As of 2.5.0, the class AbstractParser was made concrete and renamed BaseParser. The algorithmic code which had been split between AbstractParser and JPTParser was refactored into BaseParser. The role of JPTParser changed into being the location for the definition of built-in functions, operations, and constants.

Several utility classes that had been embedded in the two parser classes were made into standalone classes.

Two classes emerged from this process which should be of direct interest to callers of these tools.

To see the GUI classes available in JPT to support the interactive definitions of simple functions by end users, click here.

The Java file Parser.java (javadocs)

Parser is an interface to be implemented by classes of objects that can parse String data and evaluate the contents of the data to an Object with the state defined by the data contained in the String.

As of 2.5.0 this interface is effectively obsolete because the key method that permits the installation of a parser requires that the parser be an object derived from BaseParser and not simply an object that implements the interface Parser.

The Java file BaseParser.java (javadocs)

BaseParser implements Parser and is the concrete base class for classes of objects that provide functionality for evaluating String's into primitive types and objects assuming an expression language with simple syntactic structure.

BaseParser contains all fundamental parsing algorithms but has no installed abstract functions, operations, or constants.

BaseParser has the ability to define special forms and five such forms are introduced: set, let, if, eval, and random. Here is a brief synopsis of these special forms.

Special Form Typical Usage
set set(identifier,expression)
let let(identifier,expression)
if if(test,expression-1,expression-2)
eval eval(expression-1,...,expression-n)
random random() or random(x) or random(x,y)

The special forms are interpreted as follows.

random is introduced as a special form since in our simple parsing scheme ordinary functions cannot be overloaded to take different numbers of arguments.

The Java file JPTParser.java (javadocs)

JPTParser extends BaseParser. This class defines the built-in constants, functions, and operations that will be parsed using the parsing algorithms of the base class.

Constant definitions:

Identifier Type Definition
true XBoolean true
false XBoolean false
pi XDouble Math.PI
e XDouble Math.E
MaxInt XInt Integer.MAX_VALUE
maxint XInt Integer.MAX_VALUE
MinInt XInt Integer.MIN_VALUE
minint XInt Integer.MIN_VALUE
MaxLong XLong Long.MAX_VALUE
maxlong XLong Long.MAX_VALUE
MinLong XLong Long.MIN_VALUE
minlong XLong Long.MIN_VALUE
MaxDouble XDouble Double.MAX_VALUE
maxdouble XDouble Double.MAX_VALUE
MinDouble XDouble Double.MIN_VALUE
mindouble XDouble Double.MIN_VALUE
Infinity XDouble Double.POSITIVE_INFINITY
infinity XDouble Double.POSITIVE_INFINITY
NaN XDouble Double.NaN
nan XDouble Double.NaN

Function definitions:

Function Name Typical Usage
abs abs(x)
ceiling ceiling(x)
floor floor(x)
round round(x)
max max(x,y)
min min(x,y)
sqrt sqrt(x)
power power(x,y)
root root(x,y)
todegrees todegrees(theta)
toradians toradians(angle)
sin sin(theta)
sindeg sindeg(angle)
cos cos(theta)
cosdeg cosdeg(angle)
tan tan(theta)
tandeg tandeg(angle)
asin asin(s)
asindeg asindeg(s)
acos acos(c)
acosdeg acosdeg(c)
atan atan(t)
atandeg(t) atandeg(t)
atan2 atan2(y,x)
atan2deg atan2deg(y,x)
exp exp(x)
log log(x)
ln ln(x)
log2 log2(x)
log10 log10(x)
logtobase logtobase(x,b)

In the above table:
    x and y stand for generic variables;
    theta is an angle in radians;
    angle is an angle in degrees;
    s, c, t stand for possible values of sin, cos, tan;
    and b is the base for a logarithm.

In 2.5.0, random was removed from the list of functions because as implemented in the class AbstractFunction a function has a fixed number of arguments. Instead, random is now implemented directly in BaseParser to take one of three forms with the following interpretations.

Function Name Typical Usage Interpretation
random random() Random number between 0 and 1
random random(x) Random number between 0 and x
random random(x,y) Random number between x and y

Operation definitions:

Precedence Operations Symbols
0 IDENTITY None
1 operationOR ||
2 operationAND &&
3 operationEQ
operationNE
==
!=
4 operationLT
operationGT
operationLE
operationGE
<
>
<=
>=
5 operationPlus
operationMinus
+
-
6 operationTimes
operationSlash
operationPercent
*
/
%
7 operationCaret ^
8 operationNOT !

The Java file ParserUtilities.java (javadocs)

ParserUtilities provides static utility methods for doing the parsing process. Its most useful method for the designer is the method getDefaultParser that returns the current parser.

The Java file AbstractFunction.java (javadocs)

AbstractFunction is the base class for defining function objects that implement a functionCall method that takes an array of objects as arguments and returns an object as result. In practice, both the arguments and the return will be Stringable.

The class JPTParser has numerous examples of functions that are defined by directly implementing the functionCall method in a derived object.

The Java file SimpleFunction.java (javadocs)

SimpleFunction is a concrete class that extends AbstractFunction in such a way that the information for defining a function may be provided if desired interactively. The easiest way to define a SimpleFunction is to provide 3 strings: the name, a comma separated list of the parameters, and a function body that uses the parameters in an expression to compute the function value. Since the body must be parsed, implicitly or explicitly, a SimpleFunction is defined with reference to an instance of BaseParser.

To see the GUI classes available in JPT to support the interactive definitions of simple functions by end users, click here.

The Java file Operation.java (javadocs)

Operation is an abstract class that defines the essentials of an operation.

The Java file BooleanOperation.java (javadocs)

BooleanOperation is a concrete Operation that produces boolean values.

The Java file NumericOperation.java (javadocs)

NumericOperation is a concrete Operation that produces numeric values.

The Java file ObjectOperationPair.java (javadocs)

ObjectOperationPair is a pair consisting of a binary operation and its already evaluated left hand argument. This class is used to implement the parser code that searches for and evaluates the right hand argument of the binary operation.

The Java file ParserContext.java (javadocs)

ParserContext is a class used the stack the parameters that must be saved during recursive calls to the parser. As of 2.5.0, what is saved is the string being parsed, the position within that string, and the context of temporary let variables. We make no commitment that this class will remain the same in future releases of JPT but we will preserve backward compatibility if at all possible.

Back to top of edu.neu.ccs.parser or back to top of page

Java Source Files in edu.neu.ccs.pedagogy (1 file)
Turtle Graphics

The Java file Turtle.java (javadocs)

Turtle is a class to implement turtle graphics that will allow one or more turtle objects to draw in a common BufferedPanel.

Back to top of page

Java Source Files in edu.neu.ccs.quick (15 files)
Assorted Data Structures

The Java file QuickVector.java (javadocs)

The Java file QuickArrayList.java (javadocs)

The Java file QuickLinkedList.java (javadocs)

The Java file QuickHashSet.java (javadocs)

The Java file QuickTreeSet.java (javadocs)

The Java file QuickHashtable.java (javadocs)

The Java file QuickHashMap.java (javadocs)

The Java file QuickTreeMap.java (javadocs)

The eight classes above extend the corresponding Java classes by adding constructors that allow the data structures to be initialized using appropriate arrays of objects.

The Java file Pair.java (javadocs)

Class Pair will create a pair consisting of two non-null Objects.

The Java file StringObjectPair.java (javadocs)

Class StringObjectPair will create a pair consisting of a non-null String and a non-null Object.

The Java file StringSet.java (javadocs)

Class StringSet encapsulates a structure that maintains a set of Strings both in the original order of entry and in sorted order.

The Java file StringObjectMap.java (javadocs)

Class StringObjectMap encapsulates a structure that maintains a collection of String and Object pairs in the original order of pair entry and nevertheless makes it efficient to map a string to an object and an object to a string.

The Java file IteratorFactory.java (javadocs)

Class IteratorFactory encapsulates a static method to construct a Java Iterator from an Object[] array.

The next two classes were specifically introduced to support KeyPressReleaseListener.

The Java file BooleanStateArray.java (javadocs)

Class BooleanStateArray maintains a data structure that permits a specified set of int values to be associated with a true or false state.

In the application to KeyPressReleaseListener, each int is a keycode for a key whose press or release state is being monitored.

The Java file StringIntPair.java (javadocs)

Class StringIntPair pairs a String and an int.

Back to top of edu.neu.ccs.quick or back to top of page

Java Source Files in edu.neu.ccs.util (21 files)
Assorted Utilities

The Java file TextTools.java (javadocs)

TextTools contains tools to read, write, and copy text files on the local file system. The class can also parse a text file that is read into a large internal string into an array of trimmed, non-empty lines. Using this tool, a method is available to read a disk file whose contents consist of file names and to produce an array of such file names. This latter method is applied to reading images from disk in the class ImageTools.

See also the Java file Strings in the edu.neu.ccs package.

The Java file WebTools.java (javadocs)

WebTools contains tools to read general data files and text files from the web. In a manner similar to TextTools, this class can read a file of file names from the web. This latter method is applied to reading images from the web in the class WebImageTools.

The Java file MathUtilities.java (javadocs)

MathUtilities collects several useful static mathematical functions including trigonometric functions in degrees, random numbers in bounded ranges, and the greatest common divisor functions. The class may be viewed as an extension of the tools found in java.lang.Math.

The Java file ProbStatTools.java (javadocs)

ProbStatTools provides methods for generating permutations or more generally random selections from an array of integer data. Since such data may be viewed as a set of indices into an array of more general object data, these tools permit permutations and selections for any kind of object.

The Java file Metric.java (javadocs)

Metric defines the notion of distance measure and nearness and provides three instances of itself EUCLID, MAX, and SUM. One application of this class is to measure when a mouse position is close to a vertex or control point in a general shape.

The Java file Hex.java (javadocs)

Hex provides methods for the conversion of numeric data to hexadecimal strings and vice versa. This class is used by the Stringable hexadecimal types and by the class XColor.

The Java file JPTConstants.java (javadocs)

JPTConstants extends SwingConstants and adds a few additional constants useful to JPT.

The Java file JPTUtilities.java (javadocs)

JPTUtilities defines methods for debug mode and defines the very useful method pauseThread.

The Java file StackTrace.java (javadocs)

StackTrace provides a static method to return the stack trace of a Throwable as a String. This is very useful when providing error or debug feedback.

See also StringViewer.

The Java file StringableFactory.java (javadocs)

StringableFactory provides both ordinary and static methods to construct a Stringable from its data type and appropriate String data. This class is used in JPT and may also be used by a designer to assist in the creation of new TypedView's or GeneralView's.

The Java file FloatArray.java (javadocs)

FloatArray encapsulates utilities for arrays of float. These utilities are used in the Shape classes.

The Java file StaticFields.java (javadocs)

StaticFields is a utility class that will extract information about the static fields in a class. This class was specifically introduced to support KeyPressReleaseListener.

The Java file DimensionUtilities.java (javadocs)

DimensionUtilities provides utilities for manipulating Dimension objects.

The Java file SystemUtilities.java (javadocs)

SystemUtilities provides utility methods for gathering information about the system and activating system components.

The Java file FileUtilities.java (javadocs)

FileUtilities provides utility methods that encapsulate file input and output operations.

The Java file FileExistsException.java (javadocs)

FileExistsException is an exception thrown to denote the existence of a file that could be inadvertently overwritten if no notification were made of its presence.

The Java file FileExtensionFilter.java (javadocs)

FileExtensionFilter is a file filter that can match files against one or more file extensions. It implements both of Java's definitions for a file filter java.io.FileFilter and javax.swing.filechooser.FileFilter. Thus this class can be used in all Java contexts.

The Java file Conversions.java (javadocs)

Conversions contains type conversion utility functions suitable for processing byte sequences and byte arrays and for conversion of integral values (short, int, or long) to floating values (float or double) that are between -1 and +1. The utilities may be useful for processing byte streams going into or coming out of disk files or external devices.

The Java file SoundUtilities.java (javadocs)

SoundUtilities provides static utility methods for playback of sound.

The Java file JPTError.java (javadocs)

JPTError is used internally in JPT to indicate a serious error in JPT.

Back to top of edu.neu.ccs.util or back to top of page

Contact Information

Richard Rasala
rasala@ccs.neu.edu
Tel: 617-373-2206
Fax: 617-373-5121
College of Computer & Information Science
202 West Village H
Northeastern University
Boston, MA 02115 USA

Back to top of page