Viewpublic abstract class View extends Object implements SwingConstants
A very important part of the text package is the View class.
As the name suggests it represents a view of the text model,
or a piece of the text model.
It is this class that is responsible for the look of the text component.
The view is not intended to be some completely new thing that one must
learn, but rather is much like a lightweight component.
By default, a view is very light. It contains a reference to the parent
view from which it can fetch many things without holding state, and it
contains a reference to a portion of the model (Element ).
A view does not
have to exactly represent an element in the model, that is simply a typical
and therefore convenient mapping. A view can alternatively maintain a couple
of Position objects to maintain its location in the model (i.e. represent
a fragment of an element). This is typically the result of formatting where
views have been broken down into pieces. The convenience of a substantial
relationship to the element makes it easier to build factories to produce the
views, and makes it easier to keep track of the view pieces as the model is
changed and the view must be changed to reflect the model. Simple views
therefore represent an Element directly and complex views do not.
A view has the following responsibilities:
- Participate in layout.
-
The view has a setSize method which is like
doLayout and setSize in Component combined.
The view has a preferenceChanged method which is
like invalidate in Component except that one can
invalidate just one axis
and the child requesting the change is identified.
A View expresses the size that it would like to be in terms of three
values, a minimum, a preferred, and a maximum span. Layout in a view is
can be done independently upon each axis. For a properly functioning View
implementation, the minimum span will be <= the preferred span which in turn
will be <= the maximum span.
The minimum set of methods for layout are:
The setSize method should be prepared to be called a number of times
(i.e. It may be called even if the size didn't change).
The setSize method
is generally called to make sure the View layout is complete prior to trying
to perform an operation on it that requires an up-to-date layout. A view's
size should always be set to a value within the minimum and maximum
span specified by that view. Additionally, the view must always call the
preferenceChanged method on the parent if it has changed the
values for the
layout it would like, and expects the parent to honor. The parent View is
not required to recognize a change until the preferenceChanged
has been sent.
This allows parent View implementations to cache the child requirements if
desired. The calling sequence looks something like the following:
The exact calling sequence is up to the layout functionality of
the parent view (if the view has any children). The view may collect
the preferences of the children prior to determining what it will give
each child, or it might iteratively update the children one at a time.
- Render a portion of the model.
-
This is done in the paint method, which is pretty much like a component
paint method. Views are expected to potentially populate a fairly large
tree. A View has the following semantics for rendering:
- The view gets its allocation from the parent at paint time, so it
must be prepared to redo layout if the allocated area is different from
what it is prepared to deal with.
- The coordinate system is the same as the hosting
Component
(i.e. the Component returned by the
getContainer method).
This means a child view lives in the same coordinate system as the parent
view unless the parent has explicitly changed the coordinate system.
To schedule itself to be repainted a view can call repaint on the hosting
Component .
- The default is to not clip the children. It is more efficient
to allow a view to clip only if it really feels it needs clipping.
- The
Graphics object given is not initialized in any way.
A view should set any settings needed.
- A
View is inherently transparent. While a view may render into its
entire allocation, typically a view does not. Rendering is performed by
tranversing down the tree of View implementations.
Each View is responsible
for rendering its children. This behavior is depended upon for thread
safety. While view implementations do not necessarily have to be implemented
with thread safety in mind, other view implementations that do make use of
concurrency can depend upon a tree traversal to guarantee thread safety.
- The order of views relative to the model is up to the implementation.
Although child views will typically be arranged in the same order that they
occur in the model, they may be visually arranged in an entirely different
order. View implementations may have Z-Order associated with them if the
children are overlapping.
The methods for rendering are:
- Translate between the model and view coordinate systems.
-
Because the view objects are produced from a factory and therefore cannot
necessarily be counted upon to be in a particular pattern, one must be able
to perform translation to properly locate spatial representation of the model.
The methods for doing this are:
The layout must be valid prior to attempting to make the translation.
The translation is not valid, and must not be attempted while changes
are being broadcasted from the model via a DocumentEvent .
- Respond to changes from the model.
-
If the overall view is represented by many pieces (which is the best situation
if one want to be able to change the view and write the least amount of new code),
it would be impractical to have a huge number of DocumentListener s.
If each
view listened to the model, only a few would actually be interested in the
changes broadcasted at any given time. Since the model has no knowledge of
views, it has no way to filter the broadcast of change information. The view
hierarchy itself is instead responsible for propagating the change information.
At any level in the view hierarchy, that view knows enough about its children to
best distribute the change information further. Changes are therefore broadcasted
starting from the root of the view hierarchy.
The methods for doing this are:
|
Fields Summary |
---|
public static final int | BadBreakWeightThe weight to indicate a view is a bad break
opportunity for the purpose of formatting. This
value indicates that no attempt should be made to
break the view into fragments as the view has
not been written to support fragmenting. | public static final int | GoodBreakWeightThe weight to indicate a view supports breaking,
but better opportunities probably exist. | public static final int | ExcellentBreakWeightThe weight to indicate a view supports breaking,
and this represents a very attractive place to
break. | public static final int | ForcedBreakWeightThe weight to indicate a view supports breaking,
and must be broken to be represented properly
when placed in a view that formats its children
by breaking them. | public static final int | X_AXISAxis for format/break operations. | public static final int | Y_AXISAxis for format/break operations. | static final Position$Bias[] | sharedBiasReturn | private View | parent | private Element | elem |
Constructors Summary |
---|
public View(Element elem)Creates a new View object.
this.elem = elem;
|
Methods Summary |
---|
public void | append(javax.swing.text.View v)Appends a single child view. This is a convenience
call to replace .
View[] one = new View[1];
one[0] = v;
replace(getViewCount(), 0, one);
| public javax.swing.text.View | breakView(int axis, int offset, float pos, float len)Tries to break this view on the given axis. This is
called by views that try to do formatting of their
children. For example, a view of a paragraph will
typically try to place its children into row and
views representing chunks of text can sometimes be
broken down into smaller pieces.
This is implemented to return the view itself, which
represents the default behavior on not being
breakable. If the view does support breaking, the
starting offset of the view returned should be the
given offset, and the end offset should be less than
or equal to the end offset of the view being broken.
return this;
| public void | changedUpdate(javax.swing.event.DocumentEvent e, java.awt.Shape a, javax.swing.text.ViewFactory f)Gives notification from the document that attributes were changed
in a location that this view is responsible for.
To reduce the burden to subclasses, this functionality is
spread out into the following calls that subclasses can
reimplement:
- updateChildren is called
if there were any changes to the element this view is
responsible for. If this view has child views that are
represent the child elements, then this method should do
whatever is necessary to make sure the child views correctly
represent the model.
- forwardUpdate is called
to forward the DocumentEvent to the appropriate child views.
- updateLayout is called to
give the view a chance to either repair its layout, to reschedule
layout, or do nothing.
if (getViewCount() > 0) {
Element elem = getElement();
DocumentEvent.ElementChange ec = e.getChange(elem);
if (ec != null) {
if (! updateChildren(ec, e, f)) {
// don't consider the element changes they
// are for a view further down.
ec = null;
}
}
forwardUpdate(ec, e, a, f);
updateLayout(ec, e, a);
}
| public javax.swing.text.View | createFragment(int p0, int p1)Creates a view that represents a portion of the element.
This is potentially useful during formatting operations
for taking measurements of fragments of the view. If
the view doesn't support fragmenting (the default), it
should return itself.
return this;
| protected void | forwardUpdate(javax.swing.event.DocumentEvent$ElementChange ec, javax.swing.event.DocumentEvent e, java.awt.Shape a, javax.swing.text.ViewFactory f)Forwards the given DocumentEvent to the child views
that need to be notified of the change to the model.
If there were changes to the element this view is
responsible for, that should be considered when
forwarding (i.e. new child views should not get
notified).
Element elem = getElement();
int pos = e.getOffset();
int index0 = getViewIndex(pos, Position.Bias.Forward);
if (index0 == -1 && e.getType() == DocumentEvent.EventType.REMOVE &&
pos >= getEndOffset()) {
// Event beyond our offsets. We may have represented this, that is
// the remove may have removed one of our child Elements that
// represented this, so, we should foward to last element.
index0 = getViewCount() - 1;
}
int index1 = index0;
View v = (index0 >= 0) ? getView(index0) : null;
if (v != null) {
if ((v.getStartOffset() == pos) && (pos > 0)) {
// If v is at a boundary, forward the event to the previous
// view too.
index0 = Math.max(index0 - 1, 0);
}
}
if (e.getType() != DocumentEvent.EventType.REMOVE) {
index1 = getViewIndex(pos + e.getLength(), Position.Bias.Forward);
if (index1 < 0) {
index1 = getViewCount() - 1;
}
}
int hole0 = index1 + 1;
int hole1 = hole0;
Element[] addedElems = (ec != null) ? ec.getChildrenAdded() : null;
if ((addedElems != null) && (addedElems.length > 0)) {
hole0 = ec.getIndex();
hole1 = hole0 + addedElems.length - 1;
}
// forward to any view not in the forwarding hole
// formed by added elements (i.e. they will be updated
// by initialization.
index0 = Math.max(index0, 0);
for (int i = index0; i <= index1; i++) {
if (! ((i >= hole0) && (i <= hole1))) {
v = getView(i);
if (v != null) {
Shape childAlloc = getChildAllocation(i, a);
forwardUpdateToView(v, e, childAlloc, f);
}
}
}
| protected void | forwardUpdateToView(javax.swing.text.View v, javax.swing.event.DocumentEvent e, java.awt.Shape a, javax.swing.text.ViewFactory f)Forwards the DocumentEvent to the give child view. This
simply messages the view with a call to insertUpdate ,
removeUpdate , or changedUpdate depending
upon the type of the event. This is called by
forwardUpdate to forward
the event to children that need it.
DocumentEvent.EventType type = e.getType();
if (type == DocumentEvent.EventType.INSERT) {
v.insertUpdate(e, a, f);
} else if (type == DocumentEvent.EventType.REMOVE) {
v.removeUpdate(e, a, f);
} else {
v.changedUpdate(e, a, f);
}
| public float | getAlignment(int axis)Determines the desired alignment for this view along an
axis. The desired alignment is returned. This should be
a value >= 0.0 and <= 1.0, where 0 indicates alignment at
the origin and 1.0 indicates alignment to the full span
away from the origin. An alignment of 0.5 would be the
center of the view.
return 0.5f;
| public javax.swing.text.AttributeSet | getAttributes()Fetches the attributes to use when rendering. By default
this simply returns the attributes of the associated element.
This method should be used rather than using the element
directly to obtain access to the attributes to allow
view-specific attributes to be mixed in or to allow the
view to have view-specific conversion of attributes by
subclasses.
Each view should document what attributes it recognizes
for the purpose of rendering or layout, and should always
access them through the AttributeSet returned
by this method.
return elem.getAttributes();
| public int | getBreakWeight(int axis, float pos, float len)Determines how attractive a break opportunity in
this view is. This can be used for determining which
view is the most attractive to call breakView
on in the process of formatting. A view that represents
text that has whitespace in it might be more attractive
than a view that has no whitespace, for example. The
higher the weight, the more attractive the break. A
value equal to or lower than BadBreakWeight
should not be considered for a break. A value greater
than or equal to ForcedBreakWeight should
be broken.
This is implemented to provide the default behavior
of returning BadBreakWeight unless the length
is greater than the length of the view in which case the
entire view represents the fragment. Unless a view has
been written to support breaking behavior, it is not
attractive to try and break the view. An example of
a view that does support breaking is LabelView .
An example of a view that uses break weight is
ParagraphView .
if (len > getPreferredSpan(axis)) {
return GoodBreakWeight;
}
return BadBreakWeight;
| public java.awt.Shape | getChildAllocation(int index, java.awt.Shape a)Fetches the allocation for the given child view.
This enables finding out where various views
are located, without assuming how the views store
their location. This returns null since the
default is to not have any child views.
return null;
| public java.awt.Container | getContainer()Fetches the container hosting the view. This is useful for
things like scheduling a repaint, finding out the host
components font, etc. The default implementation
of this is to forward the query to the parent view.
View v = getParent();
return (v != null) ? v.getContainer() : null;
| public javax.swing.text.Document | getDocument()Fetches the model associated with the view.
return elem.getDocument();
| public javax.swing.text.Element | getElement()Fetches the structural portion of the subject that this
view is mapped to. The view may not be responsible for the
entire portion of the element.
return elem;
| public int | getEndOffset()Fetches the portion of the model for which this view is
responsible.
return elem.getEndOffset();
| public java.awt.Graphics | getGraphics()Fetch a Graphics for rendering.
This can be used to determine
font characteristics, and will be different for a print view
than a component view.
// PENDING(prinz) this is a temporary implementation
Component c = getContainer();
return c.getGraphics();
| public float | getMaximumSpan(int axis)Determines the maximum span for this view along an
axis.
int w = getResizeWeight(axis);
if (w == 0) {
// can't resize
return getPreferredSpan(axis);
}
return Integer.MAX_VALUE;
| public float | getMinimumSpan(int axis)Determines the minimum span for this view along an
axis.
int w = getResizeWeight(axis);
if (w == 0) {
// can't resize
return getPreferredSpan(axis);
}
return 0;
| public int | getNextVisualPositionFrom(int pos, javax.swing.text.Position$Bias b, java.awt.Shape a, int direction, javax.swing.text.Position$Bias[] biasRet)Provides a way to determine the next visually represented model
location at which one might place a caret.
Some views may not be visible,
they might not be in the same order found in the model, or they just
might not allow access to some of the locations in the model.
biasRet[0] = Position.Bias.Forward;
switch (direction) {
case NORTH:
case SOUTH:
{
if (pos == -1) {
pos = (direction == NORTH) ? Math.max(0, getEndOffset() - 1) :
getStartOffset();
break;
}
JTextComponent target = (JTextComponent) getContainer();
Caret c = (target != null) ? target.getCaret() : null;
// YECK! Ideally, the x location from the magic caret position
// would be passed in.
Point mcp;
if (c != null) {
mcp = c.getMagicCaretPosition();
}
else {
mcp = null;
}
int x;
if (mcp == null) {
Rectangle loc = target.modelToView(pos);
x = (loc == null) ? 0 : loc.x;
}
else {
x = mcp.x;
}
if (direction == NORTH) {
pos = Utilities.getPositionAbove(target, pos, x);
}
else {
pos = Utilities.getPositionBelow(target, pos, x);
}
}
break;
case WEST:
if(pos == -1) {
pos = Math.max(0, getEndOffset() - 1);
}
else {
pos = Math.max(0, pos - 1);
}
break;
case EAST:
if(pos == -1) {
pos = getStartOffset();
}
else {
pos = Math.min(pos + 1, getDocument().getLength());
}
break;
default:
throw new IllegalArgumentException("Bad direction: " + direction);
}
return pos;
| public javax.swing.text.View | getParent()Returns the parent of the view.
return parent;
| public abstract float | getPreferredSpan(int axis)Determines the preferred span for this view along an
axis.
| public int | getResizeWeight(int axis)Determines the resizability of the view along the
given axis. A value of 0 or less is not resizable.
return 0;
| public int | getStartOffset()Fetches the portion of the model for which this view is
responsible.
return elem.getStartOffset();
| public java.lang.String | getToolTipText(float x, float y, java.awt.Shape allocation)Returns the tooltip text at the specified location. The default
implementation returns the value from the child View identified by
the passed in location.
int viewIndex = getViewIndex(x, y, allocation);
if (viewIndex >= 0) {
allocation = getChildAllocation(viewIndex, allocation);
Rectangle rect = (allocation instanceof Rectangle) ?
(Rectangle)allocation : allocation.getBounds();
if (rect.contains(x, y)) {
return getView(viewIndex).getToolTipText(x, y, allocation);
}
}
return null;
| public javax.swing.text.View | getView(int n)Gets the nth child view. Since there are no
children by default, this returns null .
return null;
| public int | getViewCount()Returns the number of views in this view. Since
the default is to not be a composite view this
returns 0.
return 0;
| public javax.swing.text.ViewFactory | getViewFactory()Fetches the ViewFactory implementation that is feeding
the view hierarchy. Normally the views are given this
as an argument to updates from the model when they
are most likely to need the factory, but this
method serves to provide it at other times.
View v = getParent();
return (v != null) ? v.getViewFactory() : null;
| public int | getViewIndex(int pos, javax.swing.text.Position$Bias b)Returns the child view index representing the given position in
the model. By default a view has no children so this is implemented
to return -1 to indicate there is no valid child index for any
position.
return -1;
| public int | getViewIndex(float x, float y, java.awt.Shape allocation)Returns the child view index representing the given position in
the view. This iterates over all the children returning the
first with a bounds that contains x , y .
for (int counter = getViewCount() - 1; counter >= 0; counter--) {
Shape childAllocation = getChildAllocation(counter, allocation);
if (childAllocation != null) {
Rectangle rect = (childAllocation instanceof Rectangle) ?
(Rectangle)childAllocation : childAllocation.getBounds();
if (rect.contains(x, y)) {
return counter;
}
}
}
return -1;
| public void | insert(int offs, javax.swing.text.View v)Inserts a single child view. This is a convenience
call to replace .
View[] one = new View[1];
one[0] = v;
replace(offs, 0, one);
| public void | insertUpdate(javax.swing.event.DocumentEvent e, java.awt.Shape a, javax.swing.text.ViewFactory f)Gives notification that something was inserted into
the document in a location that this view is responsible for.
To reduce the burden to subclasses, this functionality is
spread out into the following calls that subclasses can
reimplement:
- updateChildren is called
if there were any changes to the element this view is
responsible for. If this view has child views that are
represent the child elements, then this method should do
whatever is necessary to make sure the child views correctly
represent the model.
- forwardUpdate is called
to forward the DocumentEvent to the appropriate child views.
- updateLayout is called to
give the view a chance to either repair its layout, to reschedule
layout, or do nothing.
if (getViewCount() > 0) {
Element elem = getElement();
DocumentEvent.ElementChange ec = e.getChange(elem);
if (ec != null) {
if (! updateChildren(ec, e, f)) {
// don't consider the element changes they
// are for a view further down.
ec = null;
}
}
forwardUpdate(ec, e, a, f);
updateLayout(ec, e, a);
}
| public boolean | isVisible()Returns a boolean that indicates whether
the view is visible or not. By default
all views are visible.
return true;
| public abstract java.awt.Shape | modelToView(int pos, java.awt.Shape a, javax.swing.text.Position$Bias b)Provides a mapping, for a given character,
from the document model coordinate space
to the view coordinate space.
| public java.awt.Shape | modelToView(int p0, javax.swing.text.Position$Bias b0, int p1, javax.swing.text.Position$Bias b1, java.awt.Shape a)Provides a mapping, for a given region,
from the document model coordinate space
to the view coordinate space. The specified region is
created as a union of the first and last character positions.
Shape s0 = modelToView(p0, a, b0);
Shape s1;
if (p1 == getEndOffset()) {
try {
s1 = modelToView(p1, a, b1);
} catch (BadLocationException ble) {
s1 = null;
}
if (s1 == null) {
// Assume extends left to right.
Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a :
a.getBounds();
s1 = new Rectangle(alloc.x + alloc.width - 1, alloc.y,
1, alloc.height);
}
}
else {
s1 = modelToView(p1, a, b1);
}
Rectangle r0 = s0.getBounds();
Rectangle r1 = (s1 instanceof Rectangle) ? (Rectangle) s1 :
s1.getBounds();
if (r0.y != r1.y) {
// If it spans lines, force it to be the width of the view.
Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a :
a.getBounds();
r0.x = alloc.x;
r0.width = alloc.width;
}
r0.add(r1);
return r0;
| public java.awt.Shape | modelToView(int pos, java.awt.Shape a)Provides a mapping from the document model coordinate space
to the coordinate space of the view mapped to it. This is
implemented to default the bias to Position.Bias.Forward
which was previously implied.
return modelToView(pos, a, Position.Bias.Forward);
| public abstract void | paint(java.awt.Graphics g, java.awt.Shape allocation)Renders using the given rendering surface and area on that
surface. The view may need to do layout and create child
views to enable itself to render into the given allocation.
| public void | preferenceChanged(javax.swing.text.View child, boolean width, boolean height)Child views can call this on the parent to indicate that
the preference has changed and should be reconsidered
for layout. By default this just propagates upward to
the next parent. The root view will call
revalidate on the associated text component.
View parent = getParent();
if (parent != null) {
parent.preferenceChanged(this, width, height);
}
| public void | remove(int i)Removes one of the children at the given position.
This is a convenience call to replace .
replace(i, 1, null);
| public void | removeAll()Removes all of the children. This is a convenience
call to replace .
replace(0, getViewCount(), null);
| public void | removeUpdate(javax.swing.event.DocumentEvent e, java.awt.Shape a, javax.swing.text.ViewFactory f)Gives notification that something was removed from the document
in a location that this view is responsible for.
To reduce the burden to subclasses, this functionality is
spread out into the following calls that subclasses can
reimplement:
- updateChildren is called
if there were any changes to the element this view is
responsible for. If this view has child views that are
represent the child elements, then this method should do
whatever is necessary to make sure the child views correctly
represent the model.
- forwardUpdate is called
to forward the DocumentEvent to the appropriate child views.
- updateLayout is called to
give the view a chance to either repair its layout, to reschedule
layout, or do nothing.
if (getViewCount() > 0) {
Element elem = getElement();
DocumentEvent.ElementChange ec = e.getChange(elem);
if (ec != null) {
if (! updateChildren(ec, e, f)) {
// don't consider the element changes they
// are for a view further down.
ec = null;
}
}
forwardUpdate(ec, e, a, f);
updateLayout(ec, e, a);
}
| public void | replace(int offset, int length, javax.swing.text.View[] views)Replaces child views. If there are no views to remove
this acts as an insert. If there are no views to
add this acts as a remove. Views being removed will
have the parent set to null , and the internal reference
to them removed so that they can be garbage collected.
This is implemented to do nothing, because by default
a view has no children.
| public void | setParent(javax.swing.text.View parent)Establishes the parent view for this view. This is
guaranteed to be called before any other methods if the
parent view is functioning properly. This is also
the last method called, since it is called to indicate
the view has been removed from the hierarchy as
well. When this method is called to set the parent to
null, this method does the same for each of its children,
propogating the notification that they have been
disconnected from the view tree. If this is
reimplemented, super.setParent() should
be called.
// if the parent is null then propogate down the view tree
if (parent == null) {
for (int i = 0; i < getViewCount(); i++) {
if (getView(i).getParent() == this) {
// in FlowView.java view might be referenced
// from two super-views as a child. see logicalView
getView(i).setParent(null);
}
}
}
this.parent = parent;
| public void | setSize(float width, float height)Sets the size of the view. This should cause
layout of the view along the given axis, if it
has any layout duties.
| protected boolean | updateChildren(javax.swing.event.DocumentEvent$ElementChange ec, javax.swing.event.DocumentEvent e, javax.swing.text.ViewFactory f)Updates the child views in response to receiving notification
that the model changed, and there is change record for the
element this view is responsible for. This is implemented
to assume the child views are directly responsible for the
child elements of the element this view represents. The
ViewFactory is used to create child views for each element
specified as added in the ElementChange , starting at the
index specified in the given ElementChange . The number of
child views representing the removed elements specified are
removed.
Element[] removedElems = ec.getChildrenRemoved();
Element[] addedElems = ec.getChildrenAdded();
View[] added = null;
if (addedElems != null) {
added = new View[addedElems.length];
for (int i = 0; i < addedElems.length; i++) {
added[i] = f.create(addedElems[i]);
}
}
int nremoved = 0;
int index = ec.getIndex();
if (removedElems != null) {
nremoved = removedElems.length;
}
replace(index, nremoved, added);
return true;
| protected void | updateLayout(javax.swing.event.DocumentEvent$ElementChange ec, javax.swing.event.DocumentEvent e, java.awt.Shape a)Updates the layout in response to receiving notification of
change from the model. This is implemented to call
preferenceChanged to reschedule a new layout
if the ElementChange record is not null .
if ((ec != null) && (a != null)) {
// should damage more intelligently
preferenceChanged(null, true, true);
Container host = getContainer();
if (host != null) {
host.repaint();
}
}
| public abstract int | viewToModel(float x, float y, java.awt.Shape a, javax.swing.text.Position$Bias[] biasReturn)Provides a mapping from the view coordinate space to the logical
coordinate space of the model. The biasReturn
argument will be filled in to indicate that the point given is
closer to the next character in the model or the previous
character in the model.
| public int | viewToModel(float x, float y, java.awt.Shape a)Provides a mapping from the view coordinate space to the logical
coordinate space of the model.
sharedBiasReturn[0] = Position.Bias.Forward;
return viewToModel(x, y, a, sharedBiasReturn);
|
|