
Annotated Java Power Tools 2.6.0 Source
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:
Stringable classes
parse integer arithmetic expressions that may involve integer functions.
Stringable classes
parse floating point arithmetic expressions that may involve integer functions and
floating point functions such as sqrt, exp, log, trigonometic functions, and
hyperbolic functions.
Stringable numeric classes
permit the entry of numeric data via hexadecimal strings. This permits a user to set
numeric data accurately at the bit-level.
Stringable class
parses mixed boolean and arithmetic expressions whose final result is a boolean value.
Stringable class
parses color data as decimal or hexadecimal red, green, blue, and optional alpha data
or as named colors. Support for named colors is provided by the helper class
Colors.
Stringable classes for fundamental Shape objects
parse data in a number of useful specific formats.
Stringable classes for paths
parse path node data with the 5 possible segment types
MOVE, LINE, QUAD,
CUBIC, and CLOSE and parse
path list data with a winding rule and a sequence of
path nodes.
Stringable class for complex numbers
extends the class
XPoint2D,
by adding mathematical operations for complex numbers while using the underlying
x,y data representation of its base class.
Stringable classes for function objects
parse the function data as arrays of coefficients.
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.
Strings
in this package provides support for decoding a String into a
String[]. These tools go beyond the tools of the Java class
StringTokenizer. 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, the Strings class has several additional useful
utilities.
edu.neu.ccs.parser package contains
the tools for arithmetic and boolean expression parsing as well as the
tools for creating user-defined
SimpleFunction
objects that integrate seamlessly into the parser. For examples of parsing
that combines arithmetic and boolean expressions with user-defined functions,
see the
applets
listed below.
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
Stringable types by packing and unpacking
the data from internal Stringable member objects.
Stringable data from and to files
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
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
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
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
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
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
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
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
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:
[s0;s1;...](s0,s1,...){s0|s1|...}
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 name=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
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
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
Stringable
types by packing and unpacking
the data from internal
Stringable
member objects.
Stringable
data from and to files
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
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
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
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 calls are recommended:
console.setActivated(true);console.selectColorTextScheme();If you use the Java Power Framework (JPF) environment, then these calls will be done automatically.
The console object provides three data streams:
console.in for inputconsole.out for outputconsole.err for error outputIf the color text scheme has been enabled, then these streams will use the colors blue, black, and red respectively.
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 make an action such as user input run in its own thread.
If you use the Java Power Framework (JPF) environment, then separate threads are created automatically for all methods in the JPF GUI so there is no need to deal with separate threading manually.
Back to top of edu.neu.ccs.console or back to top of page
The Java file
ConsoleGateway.java
(javadocs)
The methods provided by ConsoleGateway itself fall into three
categories:
console settingsprompt, pressReturn,
and confirm that handle common input-output activitiesBack to top of edu.neu.ccs.console or back to top of page
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.
setDataType and getDataType
to control the class of the
Stringable
object being inputdemand, demandObject,
request, requestObject, and reading
for input of a
Stringable
object with various optionsdemandBytedemandShortdemandIntdemandLongdemandFloatdemandDoubledemandChardemandBooleandemandStringdemandBigIntegerdemandBigDecimaldemandColorrequestByterequestShortrequestIntrequestLongrequestFloatrequestDoublerequestCharrequestBooleanrequestStringrequestBigIntegerrequestBigDecimalrequestColorBack to top of edu.neu.ccs.console or back to top of page
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 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
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 in the
GeneralView
interface and in the 2 classes that implement this interface,
TextFieldView
and
DropdownView,
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
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
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
The Java file
StringableFilterSequence.java
(javadocs)
Back to top of edu.neu.ccs.filter or back to top of page
Back to top of edu.neu.ccs.gui or back to top of page
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:
StringableFilter to
restrict the data values permitted in the view.
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
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:
INPUT_PROMPT: the error dialog promptDIALOG_TITLE: the error dialog titleINPUT_MODEL: either JPTConstants.OPTIONAL
or JPTConstants.MANDATORYSUGGESTION: either null or a
String containing a suggestion to the user to help resolve
an error
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
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
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
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:
String.RadioPanel is a vertical
list. If some other layout is desired, a
LayoutManager may be supplied.ActionListener that will be
executed when any radio button is selected. Alternately, one
can supply an array of ActionListener objects,
one for each radio button, that targets each button specifically.
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:
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:
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:
TableLayout orientation of HORIZONTAL,
each column is filled to its capacity and then objects are placed
in the next column to the right. New columns are added if needed.TableLayout orientation of VERTICAL,
each row is filled to its capacity and then objects are placed
in the next row below. New rows are added if needed.
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
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
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.
JSlider, it
is not the default.SliderView provides what we
believe is a better algorithm for automatically computing
the location of tick marks and labels. Moreover, the
underlying methods for showing tick marks and labels are
public so the caller can manually fine tune these objects
to any degree desired.SliderView includes a text
field that shows the current slider value and may be used
to set that value if desired by the user. The text field
may, however, be omitted from the GUI by setting a certain
constructor parameter appropriately.SliderView provides many constructors
which allow the caller to exercise whatever degree of control
is needed in the slider construction.
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
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.
Next, we show the color dropdown list with “DarkOrange” about to be selected.
Next, we show the ColorView with “DarkOrange”.
Next, we show the ColorPaneDialog that is brought up with a
click on the color swatch in the ColorView.
Finally, we show the ColorView after the user has clicked OK
in the ColorPaneDialog.
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.
Back to top of Views: color selection or back to top of edu.neu.ccs.gui or back to top of page
The Java file
ComponentFactory.java
(javadocs)
ComponentFactory has 3 static methods:
makeComponent that constructs a Component
from an ObjectmakeIcon that constructs an Icon
from an ObjectmakePaintable that constructs a
Paintable
from an Object
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 |
||
|
PaintableComponent |
||
| otherwise | null |
The table below shows more about how makeIcon works.
| Argument | Return | ||
Icon |
The same Icon |
||
Paint |
PaintSwatch |
||
|
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
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 can also be used for other Java panels to provide
fine control of component layout.
Since the invention of TableLayout, we have found in practice
that we almost never 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
JPTFrame
since that frame normally has one object in its content pane.
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
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:
makeComponent that constructs a
Component from an Object by calling the
corresponding static method from
ComponentFactory.
addObject methods that add more general objects to
the panel by using the makeComponent method to automatically
convert these objects into suitable components. This permits a caller to
add more general entities to a GUI without the need to explicitly convert
these entities into components.
frame methods that permit a DisplayPanel
to create a frame (window) with various options and then to insert itself
into that frame. This is known as self-actualization.
generalDialog methods that permit a DisplayPanel
to create a dialog with various options and then to insert itself into that
dialog.
uniformizeSize method that forces all items in the
panel to have the same preferred size if that sizing policy is desired.
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
The Java file
TablePanel.java
(javadocs)
TablePanel is the most important panel in the Java Power Tools.
This panel is based on TableLayout.
TablePanel is designed to quickly build one or two dimensional tables
of components constructed from objects using the makeComponent method.
Due to the TableLayout algorithms,
TablePanel is able to
handle the alignment of objects within cells and the gaps between cells.
Furthermore, since TablePanel's nest within TablePanel's,
layouts of arbitrary complexity may be easily achieved.
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 components 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 components 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:
HORIZONTALVERTICAL
The parameters hgap and vgap represent the standard horizontal and vertical
gap 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:
CENTERNORTHNORTH_EASTEASTSOUTH_EASTSOUTHSOUTH_WESTWESTNORTH_WEST
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.
The Java file
VTable.java
(javadocs)
VTable is a derived class of TablePanel
that is constrained to be 1-dimensional and vertical.
Back to top of Panels: TablePanel and associated classes or back to top of edu.neu.ccs.gui or back to top of page
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.
BufferedImage object holds a bit-map that is used
to paint the background layer of the BufferedPanel.PaintableSequence object holds a collection of
Paintable objects that are painted above the background
layer in the sprite layer.
Since these objects are Paintable, they have all
of the properties of Paintable including the ability to
be mutated by arbitrary affine transforms.
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
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:
Annotation can display multi-line text.Annotation can be in an alert state.Annotation can have a separate icon to denote that it
is in an alert state.Back to top of Panels: Annotation or back to top of edu.neu.ccs.gui or back to top of page
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:
new Halo(view)
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.
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
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:
TypedView Class object.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:
viewType must not be null.viewType must extend JComponent
so a view may be directly inserted into its panel.viewType must implement
TypedView
so the model data can be extracted from a view by the standard
methods of the
TypedView interface.viewType class must have a default
constructor.
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
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
The Java file
JPTFrame.java
(javadocs)
JPTFrame extends the Java JFrame class for
the following purposes.
JFrame that is packed
and opened automatically.
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
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:
DialogAction.KEEP_OPEN:
The choice to keep the dialog open after the actionDialogAction.AUTO_CLOSE:
The choice to auto close the dialog after the actionDialogAction.SET_CANCEL:
The choice to both close the dialog and mark the dialog as cancelled
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
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.
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
Back to top of edu.neu.ccs.gui or back to top of page
The Java file
Paintable.java
(javadocs)
Paintable is an interface that describes an object that can
paint onto a graphics context. In addition, a Paintable can
return its bounds and center, can set its visibility on or off, can set
its opacity to a value between 0 and 1, and can determine if a point is
included in the region painted so that mouse manipulation is supported.
Furthermore, a Paintable may be mutated using an arbitrary
invertible AffineTransform.
Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page
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
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:
Strategy that defines a mutator
strategy that may be applied to a
Paintable objectMutator.Strategy
objectsMutator.Strategy
objects in a
PaintableSequence
The two Mutator.StrategyUsage constants for a
PaintableSequence are:
Mutator.StrategyUsage.MUTATE_AS_GROUPMutator.StrategyUsage.MUTATE_AS_ITEMS
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:
ComponentJComponentPropertyChangeSupportSwingPropertyChangeSupport
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
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.FILL: Fill the shapePaintMode.DRAW: Draw the shape boundaryPaintMode.FILL_DRAW: Fill the shape then
draw the shape boundaryPaintMode 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
The Java file
ImagePaintable.java
(javadocs)
ImagePaintable creates an
AbstractPaintable
using one of the following:
Image objectImageIcon object
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
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:
TextBounds.TIGHT to obtain a tight bounding boxTextBounds.LOOSE to obtain Java's default bounding box
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:
TextAnchor.LEFT_BASELINETextAnchor.CENTER_BASELINETextAnchor.RIGHT_BASELINETextAnchor.LEFT_ASCENTLINETextAnchor.CENTER_ASCENTLINETextAnchor.RIGHT_ASCENTLINETextAnchor.LEFT_DESCENTLINETextAnchor.CENTER_DESCENTLINETextAnchor.RIGHT_DESCENTLINETextAnchor.LEFT_LEADINGLINETextAnchor.CENTER_LEADINGLINETextAnchor.RIGHT_LEADINGLINEBack to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page
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
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.
Back to top of Paintable and its implementations or back to top of edu.neu.ccs.gui or back to top of page
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:
IconBufferedImageTexturePaintJButtonJPTComponent
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:
SupportsPropertyChange
that
are not already (publically) implemented in JComponentKeyActionAdapter for this componentMouseActionAdapter for this component
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
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.
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:
Paint object
that is used to paint the background initially.
Paintable
that will tile the background repeatedly.
Paintable
that will be painted once and that may be centered in the component if desired.
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
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
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.
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.
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.
Back to top of Graphics tools or back to top of edu.neu.ccs.gui or back to top of page
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:
Image objectImageIcon object
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
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
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:
ClosureMode.CLOSEDClosureMode.OPEN
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:
WindingRule.WIND_NON_ZEROWindingRule.WIND_EVEN_ODDBack to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page
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:
Path.Strategy settingClosureMode settingWindingRule setting
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:
ClosureModeWindingRule
Path also provides some examples of Strategy objects
and some useful static methods. The Strategy objects are:
Path.POLYGON: make a polygon path joining the
vertex points and ignore the tangent arrayPath.POLYGON_DOTS: make a path consisting of
the polygon dots at the vertex points and ignore the tangent arrayPath.BEZIER_CUBIC: use the vertex and tangent
arrays to construct a Bézier cubic curvePath.BEZIER_FRAME: use the vertex and tangent
arrays to construct the polygonal frame that is used in the Bézier
cubic algorithmPath.BEZIER_TANGENT_SEGMENTS: use the vertex
and tangent arrays to construct a sequence of disjoint tangent segments
at each of the vertex points
The most useful static methods in Path are:
append
that will append an array of Shape objects to a Java
GeneralPath object using specified connectivity
constraintsshowShapeStructure that will display the structure of
a Shape including its dots, control dots, and
Bézier frameBack to top of Shape classes or back to top of edu.neu.ccs.gui or back to top of page
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.
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
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
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
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:
nameActionnameActionAdapternameActionEvent
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:
public void addMouseMovedAction (ActionListener a)
public void addMousePressedAction (ActionListener a)
public void addMouseDraggedAction (ActionListener a)
public void addMouseReleasedAction(ActionListener a)
public void addMouseClickedAction (ActionListener a)
public void addMouseEnteredAction (ActionListener a)
public void addMouseExitedAction (ActionListener a)
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
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.
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.
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:
JPTParser.
The function definition pane is implemented using a
SimpleFunctionBuilder
pane.
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
Function Plot Pane: Plot of exp and expsin
Back to top of GUIs or back to top of edu.neu.ccs.gui or back to top of page
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 --> factor * z + 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
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
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
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
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
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
The Java file
JPF.java
(javadocs)
The Java Power Framework class JPF provides the
foundation (base class) for the creation of a Java GUI application
whose action buttons are constructed automatically from the
public methods of a suitable derived Methods class.
A click on such an automatic button will execute the corresponding
method. To allow for easy experimentation and testing, the automatic
GUI application will have access to:
console I/O via the interface
ConsoleAwarewindow pane based on the class
BufferedPanel
A typical derived class of JPF has the following simple
structure:
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 GUI buttons
// enter here any non-public helper methods as desired
}
In the automatic Java GUI application generated from such a class, the
action buttons are created automatically from the public
methods whose arguments and return type are one of the following types:
voidboolean, char, byte, short, int, long, float, doubleString, Color, BigInteger, BigDecimalStringable interface
and whose input may be typed using a single line of text
In addition, Paint may be used as a return type. In that case,
the application will display a paint swatch.
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 user of the Java Power Framework need not have any significant knowledge of the JPT. Thus 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 the default constructor on that new class. The derived
class need not be named Methods but that is frequently
the name used in practice.
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.addPaintable(paintable);
window.repaint();
}
}
Here is a screen snapshot of the automatic GUI that is created when this class is executed.
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.
This button was indeed clicked before the screen snapshot was taken.
The 4 yellow and red buttons are automatically created for any JPF GUI. The yellow button “Clear Graphics” will clear the contents of the graphics window. The yellow “Toggle” buttons will hide or show the graphics window or the associated console pane window. 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:
The key features of this file are:
import statements so that one does
not have to stop experimental work to look up an import.
LookAndFeelTools.
These statements permit a programmer to allow the look and feel to be
chosen by the end user or, more simply, to adjust all default font sizes.
Paintable objects in the
graphics window.
Test that may be uncommented and
run in the JPF GUI to test that everything works.
Here is a variation of this Methods class with some of the commented
portions made active:
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 and the parameter true requests that
a clicked Paintable be lifted to the top of the stack. Finally,
the Test method is 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.
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.
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:
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.
Summary
To summarize, the Java Power Framework may be used to create GUI buttons in an automatically generated application for any of the following purposes:
Example 4
To illustrate how to define a method to launch a separate Java application,
we assume that the application is associated with a class that we will name,
for convenience, Foo. Suppose that Foo has a static
method main that requires no arguments. We can write the JPF
method to launch the Foo application as follows:
public void LaunchFoo() { Foo.main(null); }
Placing this code in a JPF Methods class will cause a button to be
created in the automatic GUI that is labeled “LaunchFoo” and that
launches the application Foo in a separate thread when clicked.
The fact that separate threading is automatic is quite convenient.
Example 5
Alternatively, suppose that Foo extends the JPT class
DisplayPanel which is the base class
for most JPT panels. This base class has a collection of frame
methods that will install an instance in a frame and make that frame visible.
Thus, to display an instance of Foo, we can use the following
method:
public void ShowFoo() { new Foo().frame("Foo"); }
Placing this code in the JPF Methods class will cause a button to
be created in the automatic GUI that is labeled “ShowFoo”. When
the button is clicked, it will instatiate a new Foo object and
display that object in a frame whose title is “Foo”. In fact, the
“ShowFoo” button may be clicked more than once to instantiate
several instances of Foo.
Example 6
In both techniques for launching an application, we have ignored parameters
to the main method or the Foo constructor. It is
easy to add such parameters either as hard-wired arguments or as a parameter
passed into the corresponding JPF method. Let us illustrate how to do the
latter.
In the Methods class below, the method
LaunchFooWithArgs will launch the
main method of another class Foo.
The user will provide arguments as a single blank separated
String which will be converted to a
String[] using
Strings.tokenize and then be passed to
Foo.main. The sample includes a test class
Foo that simply lists the number of arguments
and then each argument individually.
import edu.neu.ccs.*;
import edu.neu.ccs.jpf.*;
public class Methods extends JPF
{
public static void main(String[] args) { Methods methods = new Methods(); }
// notice user enters one string not an array
public void LaunchFooWithArgs(String args) {
Foo.main(Strings.tokenize(args, " ", 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 blank separated String. In
this example, the test String is
this is an argument list.
Here is the test output printed:
args length: 5 args[0] = this args[1] = is args[2] = an args[3] = argument args[4] = list
If the user provides an empty String then the test output
will correctly state:
args length: 0
As a final comment, we note that the class JPF itself extends
JPFBase. This base class
provides a series of methods that may be used to
determine if a class possesses a required set of constructors and/or methods.
These testing methods are automatically inherited by any class Methods
that extends JPF and may be used to create unit test suites.
The Java file
JPFBase.java
(javadocs)
JPFBase provides the base utility methods for use in the
Java Power Framework. These methods may be used to test if a class
contains a required set of constructors and/or methods and may be used to
provide interactive feedback to a user via a dialog box if desired.
In the following examples, Foo will represent the name of some
class being tested. In all examples, a dialog will be shown if some required
constructor or method is missing.
Example 1: To test if Foo declares certain constructors, use:
return declaresConstructors(Foo.class,
new String[] {
"public Foo()",
"public Foo(int x)",
"public Foo(int x, int y)" } );
Example 2: To test if Foo declares certain methods, use:
return declaresMethods(Foo.class,
new String[] {
"public void setX(int x)",
"public int xValue()",
"public void setY(int y)",
"public int yValue()" } );
Example 3: To test if Foo declares certain constructors and methods,
use:
return declaresConstructorsAndMethods(Foo.class,
new String[] {
"public Foo()",
"public Foo(int x)",
"public Foo(int x, int y)" },
new String[] {
"public void setX(int x)",
"public int xValue()",
"public void setY(int y)",
"public int yValue()" } );
Example 4: To test if Foo or a super class of Foo
provides certain constructors and methods, replace declares...
with provides... in Example 3.
The Java file
JPFApplication.java
(javadocs)
This class is package private.
The responsibility of JPFApplication is to build the automatic JPF
GUI whose buttons correspond to the methods returned by
MethodGUI.
The Java file
MethodGUI.java
(javadocs)
This class is package private.
The responsibility of MethodGUI is to collect the methods that
should be installed as buttons in the automatic JPF GUI.
The Java file
ActivityIcon.java
(javadocs)
This class is package private.
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, see the screen snapshot above.
Back to top of edu.neu.ccs.jpf or back to top of page
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.
AbstractFunction which is the
abstract base case for defining functions
that may be installed in the parser either
algorithmically or via user interaction.SimpleFunction which is a
derived class of
AbstractFunction designed to
support interactive definitions of simple
functions by end users.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.
set evaluates the expression and assigns it to
the identifier in a persistant fashion that will be available
across invocations of the parser.
set returns the
evaluated expression as its value.let evaluates the expression and assigns it to
the identifier in a temporary fashion that will be available
only in this invocation of the parser.
let
returns the evaluated expression as its value.if evaluates the test expression as a boolean.
If the result is true,
expression-1 is evaluated and returned
and expression-2 is skipped.
If the result is false,
expression-2 is evaluated and returned
and expression-1 is skipped.eval evaluates all expressions from left to right
and returns the value of the last expression.random() returns a random double between 0 and 1.random(x) returns a random double between 0 and x. random(x,y) returns a random double between x and y.
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 |
== |
| 4 | operationLT |
< |
| 5 | operationPlus |
+ |
| 6 | operationTimes |
* |
| 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
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
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
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
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