code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html.parser;
import java.util.BitSet;
import java.util.Vector;
import java.io.*;
/** {@collect.stats}
* A stack of tags. Used while parsing an HTML document.
* It, together with the ContentModelStates, defines the
* complete state of the parser while reading a document.
* When a start tag is encountered an element is pushed onto
* the stack, when an end tag is enountered an element is popped
* of the stack.
*
* @see Parser
* @see DTD
* @see ContentModelState
* @author Arthur van Hoff
*/
final
class TagStack implements DTDConstants {
TagElement tag;
Element elem;
ContentModelState state;
TagStack next;
BitSet inclusions;
BitSet exclusions;
boolean net;
boolean pre;
/** {@collect.stats}
* Construct a stack element.
*/
TagStack(TagElement tag, TagStack next) {
this.tag = tag;
this.elem = tag.getElement();
this.next = next;
Element elem = tag.getElement();
if (elem.getContent() != null) {
this.state = new ContentModelState(elem.getContent());
}
if (next != null) {
inclusions = next.inclusions;
exclusions = next.exclusions;
pre = next.pre;
}
if (tag.isPreformatted()) {
pre = true;
}
if (elem.inclusions != null) {
if (inclusions != null) {
inclusions = (BitSet)inclusions.clone();
inclusions.or(elem.inclusions);
} else {
inclusions = elem.inclusions;
}
}
if (elem.exclusions != null) {
if (exclusions != null) {
exclusions = (BitSet)exclusions.clone();
exclusions.or(elem.exclusions);
} else {
exclusions = elem.exclusions;
}
}
}
/** {@collect.stats}
* Return the element that must come next in the
* input stream.
*/
public Element first() {
return (state != null) ? state.first() : null;
}
/** {@collect.stats}
* Return the ContentModel that must be satisfied by
* what comes next in the input stream.
*/
public ContentModel contentModel() {
if (state == null) {
return null;
} else {
return state.getModel();
}
}
/** {@collect.stats}
* Return true if the element that is contained at
* the index specified by the parameter is part of
* the exclusions specified in the DTD for the element
* currently on the TagStack.
*/
boolean excluded(int elemIndex) {
return (exclusions != null) && exclusions.get(elem.getIndex());
}
/** {@collect.stats}
* Update the Vector elemVec with all the elements that
* are part of the inclusions listed in DTD for the element
* currently on the TagStack.
*/
boolean included(Vector elemVec, DTD dtd) {
for (int i = 0 ; i < inclusions.size(); i++) {
if (inclusions.get(i)) {
elemVec.addElement(dtd.getElement(i));
System.out.println("Element add thru' inclusions: " + dtd.getElement(i).getName());
}
}
return (!elemVec.isEmpty());
}
/** {@collect.stats}
* Advance the state by reducing the given element.
* Returns false if the element is not legal and the
* state is not advanced.
*/
boolean advance(Element elem) {
if ((exclusions != null) && exclusions.get(elem.getIndex())) {
return false;
}
if (state != null) {
ContentModelState newState = state.advance(elem);
if (newState != null) {
state = newState;
return true;
}
} else if (this.elem.getType() == ANY) {
return true;
}
return (inclusions != null) && inclusions.get(elem.getIndex());
}
/** {@collect.stats}
* Return true if the current state can be terminated.
*/
boolean terminate() {
return (state == null) || state.terminate();
}
/** {@collect.stats}
* Convert to a string.
*/
public String toString() {
return (next == null) ?
"<" + tag.getElement().getName() + ">" :
next + " <" + tag.getElement().getName() + ">";
}
}
class NPrintWriter extends PrintWriter {
private int numLines = 5;
private int numPrinted = 0;
public NPrintWriter (int numberOfLines) {
super(System.out);
numLines = numberOfLines;
}
public void println(char[] array) {
if (numPrinted >= numLines) {
return;
}
char[] partialArray = null;
for (int i = 0; i < array.length; i++) {
if (array[i] == '\n') {
numPrinted++;
}
if (numPrinted == numLines) {
System.arraycopy(array, 0, partialArray, 0, i);
}
}
if (partialArray != null) {
super.print(partialArray);
}
if (numPrinted == numLines) {
return;
}
super.println(array);
numPrinted++;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html.parser;
import sun.awt.AppContext;
import java.io.PrintStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.util.Hashtable;
import java.util.Vector;
import java.util.BitSet;
import java.util.StringTokenizer;
import java.util.Enumeration;
import java.util.Properties;
import java.net.URL;
/** {@collect.stats}
* The representation of an SGML DTD. DTD describes a document
* syntax and is used in parsing of HTML documents. It contains
* a list of elements and their attributes as well as a list of
* entities defined in the DTD.
*
* @see Element
* @see AttributeList
* @see ContentModel
* @see Parser
* @author Arthur van Hoff
*/
public
class DTD implements DTDConstants {
public String name;
public Vector<Element> elements = new Vector<Element>();
public Hashtable<String,Element> elementHash
= new Hashtable<String,Element>();
public Hashtable<Object,Entity> entityHash
= new Hashtable<Object,Entity>();
public final Element pcdata = getElement("#pcdata");
public final Element html = getElement("html");
public final Element meta = getElement("meta");
public final Element base = getElement("base");
public final Element isindex = getElement("isindex");
public final Element head = getElement("head");
public final Element body = getElement("body");
public final Element applet = getElement("applet");
public final Element param = getElement("param");
public final Element p = getElement("p");
public final Element title = getElement("title");
final Element style = getElement("style");
final Element link = getElement("link");
final Element script = getElement("script");
public static final int FILE_VERSION = 1;
/** {@collect.stats}
* Creates a new DTD with the specified name.
* @param name the name, as a <code>String</code> of the new DTD
*/
protected DTD(String name) {
this.name = name;
defEntity("#RE", GENERAL, '\r');
defEntity("#RS", GENERAL, '\n');
defEntity("#SPACE", GENERAL, ' ');
defineElement("unknown", EMPTY, false, true, null, null, null, null);
}
/** {@collect.stats}
* Gets the name of the DTD.
* @return the name of the DTD
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Gets an entity by name.
* @return the <code>Entity</code> corresponding to the
* <code>name</code> <code>String</code>
*/
public Entity getEntity(String name) {
return (Entity)entityHash.get(name);
}
/** {@collect.stats}
* Gets a character entity.
* @return the <code>Entity</code> corresponding to the
* <code>ch</code> character
*/
public Entity getEntity(int ch) {
return (Entity)entityHash.get(new Integer(ch));
}
/** {@collect.stats}
* Returns <code>true</code> if the element is part of the DTD,
* otherwise returns <code>false</code>.
*
* @param name the requested <code>String</code>
* @return <code>true</code> if <code>name</code> exists as
* part of the DTD, otherwise returns <code>false</code>
*/
boolean elementExists(String name) {
return !"unknown".equals(name) && (elementHash.get(name) != null);
}
/** {@collect.stats}
* Gets an element by name. A new element is
* created if the element doesn't exist.
*
* @param name the requested <code>String</code>
* @return the <code>Element</code> corresponding to
* <code>name</code>, which may be newly created
*/
public Element getElement(String name) {
Element e = (Element)elementHash.get(name);
if (e == null) {
e = new Element(name, elements.size());
elements.addElement(e);
elementHash.put(name, e);
}
return e;
}
/** {@collect.stats}
* Gets an element by index.
*
* @param index the requested index
* @return the <code>Element</code> corresponding to
* <code>index</code>
*/
public Element getElement(int index) {
return (Element)elements.elementAt(index);
}
/** {@collect.stats}
* Defines an entity. If the <code>Entity</code> specified
* by <code>name</code>, <code>type</code>, and <code>data</code>
* exists, it is returned; otherwise a new <code>Entity</code>
* is created and is returned.
*
* @param name the name of the <code>Entity</code> as a <code>String</code>
* @param type the type of the <code>Entity</code>
* @param data the <code>Entity</code>'s data
* @return the <code>Entity</code> requested or a new <code>Entity</code>
* if not found
*/
public Entity defineEntity(String name, int type, char data[]) {
Entity ent = (Entity)entityHash.get(name);
if (ent == null) {
ent = new Entity(name, type, data);
entityHash.put(name, ent);
if (((type & GENERAL) != 0) && (data.length == 1)) {
switch (type & ~GENERAL) {
case CDATA:
case SDATA:
entityHash.put(new Integer(data[0]), ent);
break;
}
}
}
return ent;
}
/** {@collect.stats}
* Returns the <code>Element</code> which matches the
* specified parameters. If one doesn't exist, a new
* one is created and returned.
*
* @param name the name of the <code>Element</code>
* @param type the type of the <code>Element</code>
* @param omitStart <code>true</code> if start should be omitted
* @param omitEnd <code>true</code> if end should be omitted
* @param content the <code>ContentModel</code>
* @param atts the <code>AttributeList</code> specifying the
* <code>Element</code>
* @return the <code>Element</code> specified
*/
public Element defineElement(String name, int type,
boolean omitStart, boolean omitEnd, ContentModel content,
BitSet exclusions, BitSet inclusions, AttributeList atts) {
Element e = getElement(name);
e.type = type;
e.oStart = omitStart;
e.oEnd = omitEnd;
e.content = content;
e.exclusions = exclusions;
e.inclusions = inclusions;
e.atts = atts;
return e;
}
/** {@collect.stats}
* Defines attributes for an {@code Element}.
*
* @param name the name of the <code>Element</code>
* @param atts the <code>AttributeList</code> specifying the
* <code>Element</code>
*/
public void defineAttributes(String name, AttributeList atts) {
Element e = getElement(name);
e.atts = atts;
}
/** {@collect.stats}
* Creates and returns a character <code>Entity</code>.
* @param name the entity's name
* @return the new character <code>Entity</code>
*/
public Entity defEntity(String name, int type, int ch) {
char data[] = {(char)ch};
return defineEntity(name, type, data);
}
/** {@collect.stats}
* Creates and returns an <code>Entity</code>.
* @param name the entity's name
* @return the new <code>Entity</code>
*/
protected Entity defEntity(String name, int type, String str) {
int len = str.length();
char data[] = new char[len];
str.getChars(0, len, data, 0);
return defineEntity(name, type, data);
}
/** {@collect.stats}
* Creates and returns an <code>Element</code>.
* @param name the element's name
* @return the new <code>Element</code>
*/
protected Element defElement(String name, int type,
boolean omitStart, boolean omitEnd, ContentModel content,
String[] exclusions, String[] inclusions, AttributeList atts) {
BitSet excl = null;
if (exclusions != null && exclusions.length > 0) {
excl = new BitSet();
for (int i = 0; i < exclusions.length; i++) {
String str = exclusions[i];
if (str.length() > 0) {
excl.set(getElement(str).getIndex());
}
}
}
BitSet incl = null;
if (inclusions != null && inclusions.length > 0) {
incl = new BitSet();
for (int i = 0; i < inclusions.length; i++) {
String str = inclusions[i];
if (str.length() > 0) {
incl.set(getElement(str).getIndex());
}
}
}
return defineElement(name, type, omitStart, omitEnd, content, excl, incl, atts);
}
/** {@collect.stats}
* Creates and returns an <code>AttributeList</code>.
* @param name the attribute list's name
* @return the new <code>AttributeList</code>
*/
protected AttributeList defAttributeList(String name, int type, int modifier, String value, String values, AttributeList atts) {
Vector vals = null;
if (values != null) {
vals = new Vector();
for (StringTokenizer s = new StringTokenizer(values, "|") ; s.hasMoreTokens() ;) {
String str = s.nextToken();
if (str.length() > 0) {
vals.addElement(str);
}
}
}
return new AttributeList(name, type, modifier, value, vals, atts);
}
/** {@collect.stats}
* Creates and returns a new content model.
* @param type the type of the new content model
* @return the new <code>ContentModel</code>
*/
protected ContentModel defContentModel(int type, Object obj, ContentModel next) {
return new ContentModel(type, obj, next);
}
/** {@collect.stats}
* Returns a string representation of this DTD.
* @return the string representation of this DTD
*/
public String toString() {
return name;
}
/** {@collect.stats}
* The hashtable key of DTDs in AppContext.
*/
private static final Object DTD_HASH_KEY = new Object();
public static void putDTDHash(String name, DTD dtd) {
getDtdHash().put(name, dtd);
}
/** {@collect.stats}
* Returns a DTD with the specified <code>name</code>. If
* a DTD with that name doesn't exist, one is created
* and returned. Any uppercase characters in the name
* are converted to lowercase.
*
* @param name the name of the DTD
* @return the DTD which corresponds to <code>name</code>
*/
public static DTD getDTD(String name) throws IOException {
name = name.toLowerCase();
DTD dtd = getDtdHash().get(name);
if (dtd == null)
dtd = new DTD(name);
return dtd;
}
private static Hashtable<String, DTD> getDtdHash() {
AppContext appContext = AppContext.getAppContext();
Hashtable<String, DTD> result = (Hashtable<String, DTD>) appContext.get(DTD_HASH_KEY);
if (result == null) {
result = new Hashtable<String, DTD>();
appContext.put(DTD_HASH_KEY, result);
}
return result;
}
/** {@collect.stats}
* Recreates a DTD from an archived format.
* @param in the <code>DataInputStream</code> to read from
*/
public void read(DataInputStream in) throws IOException {
if (in.readInt() != FILE_VERSION) {
}
//
// Read the list of names
//
String[] names = new String[in.readShort()];
for (int i = 0; i < names.length; i++) {
names[i] = in.readUTF();
}
//
// Read the entities
//
int num = in.readShort();
for (int i = 0; i < num; i++) {
short nameId = in.readShort();
int type = in.readByte();
String name = in.readUTF();
defEntity(names[nameId], type | GENERAL, name);
}
// Read the elements
//
num = in.readShort();
for (int i = 0; i < num; i++) {
short nameId = in.readShort();
int type = in.readByte();
byte flags = in.readByte();
ContentModel m = readContentModel(in, names);
String[] exclusions = readNameArray(in, names);
String[] inclusions = readNameArray(in, names);
AttributeList atts = readAttributeList(in, names);
defElement(names[nameId], type,
((flags & 0x01) != 0), ((flags & 0x02) != 0),
m, exclusions, inclusions, atts);
}
}
private ContentModel readContentModel(DataInputStream in, String[] names)
throws IOException {
byte flag = in.readByte();
switch(flag) {
case 0: // null
return null;
case 1: { // content_c
int type = in.readByte();
ContentModel m = readContentModel(in, names);
ContentModel next = readContentModel(in, names);
return defContentModel(type, m, next);
}
case 2: { // content_e
int type = in.readByte();
Element el = getElement(names[in.readShort()]);
ContentModel next = readContentModel(in, names);
return defContentModel(type, el, next);
}
default:
throw new IOException("bad bdtd");
}
}
private String[] readNameArray(DataInputStream in, String[] names)
throws IOException {
int num = in.readShort();
if (num == 0) {
return null;
}
String[] result = new String[num];
for (int i = 0; i < num; i++) {
result[i] = names[in.readShort()];
}
return result;
}
private AttributeList readAttributeList(DataInputStream in, String[] names)
throws IOException {
AttributeList result = null;
for (int num = in.readByte(); num > 0; --num) {
short nameId = in.readShort();
int type = in.readByte();
int modifier = in.readByte();
short valueId = in.readShort();
String value = (valueId == -1) ? null : names[valueId];
Vector values = null;
short numValues = in.readShort();
if (numValues > 0) {
values = new Vector(numValues);
for (int i = 0; i < numValues; i++) {
values.addElement(names[in.readShort()]);
}
}
result = new AttributeList(names[nameId], type, modifier, value,
values, result);
// We reverse the order of the linked list by doing this, but
// that order isn't important.
}
return result;
}
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html.parser;
import javax.swing.text.html.HTML;
/** {@collect.stats}
* A generic HTML TagElement class. The methods define how white
* space is interpreted around the tag.
*
* @author Sunita Mani
*/
public class TagElement {
Element elem;
HTML.Tag htmlTag;
boolean insertedByErrorRecovery;
public TagElement ( Element elem ) {
this(elem, false);
}
public TagElement (Element elem, boolean fictional) {
this.elem = elem;
htmlTag = HTML.getTag(elem.getName());
if (htmlTag == null) {
htmlTag = new HTML.UnknownTag(elem.getName());
}
insertedByErrorRecovery = fictional;
}
public boolean breaksFlow() {
return htmlTag.breaksFlow();
}
public boolean isPreformatted() {
return htmlTag.isPreformatted();
}
public Element getElement() {
return elem;
}
public HTML.Tag getHTMLTag() {
return htmlTag;
}
public boolean fictional() {
return insertedByErrorRecovery;
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html.parser;
import java.io.InputStream;
/** {@collect.stats}
* Simple class to load resources using the 1.2
* security model. Since the html support is loaded
* lazily, it's resources are potentially fetched with
* applet code in the call stack. By providing this
* functionality in a class that is only built on 1.2,
* reflection can be used from the code that is also
* built on 1.1 to call this functionality (and avoid
* the evils of preprocessing). This functionality
* is called from ParserDelegator.getResourceAsStream.
*
* @author Timothy Prinzing
*/
class ResourceLoader implements java.security.PrivilegedAction {
ResourceLoader(String name) {
this.name = name;
}
public Object run() {
Object o = ParserDelegator.class.getResourceAsStream(name);
return o;
}
public static InputStream getResourceAsStream(String name) {
java.security.PrivilegedAction a = new ResourceLoader(name);
return (InputStream) java.security.AccessController.doPrivileged(a);
}
private String name;
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.util.Enumeration;
import java.awt.*;
import javax.swing.SizeRequirements;
import javax.swing.border.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.*;
/** {@collect.stats}
* A view implementation to display a block (as a box)
* with CSS specifications.
*
* @author Timothy Prinzing
*/
public class BlockView extends BoxView {
/** {@collect.stats}
* Creates a new view that represents an
* html box. This can be used for a number
* of elements.
*
* @param elem the element to create a view for
* @param axis either View.X_AXIS or View.Y_AXIS
*/
public BlockView(Element elem, int axis) {
super(elem, axis);
}
/** {@collect.stats}
* Establishes the parent view for this view. This is
* guaranteed to be called before any other methods if the
* parent view is functioning properly.
* <p>
* This is implemented
* to forward to the superclass as well as call the
* {@link #setPropertiesFromAttributes()}
* method to set the paragraph properties from the css
* attributes. The call is made at this time to ensure
* the ability to resolve upward through the parents
* view attributes.
*
* @param parent the new parent, or null if the view is
* being removed from a parent it was previously added
* to
*/
public void setParent(View parent) {
super.setParent(parent);
if (parent != null) {
setPropertiesFromAttributes();
}
}
/** {@collect.stats}
* Calculate the requirements of the block along the major
* axis (i.e. the axis along with it tiles). This is implemented
* to provide the superclass behavior and then adjust it if the
* CSS width or height attribute is specified and applicable to
* the axis.
*/
protected SizeRequirements calculateMajorAxisRequirements(int axis, SizeRequirements r) {
if (r == null) {
r = new SizeRequirements();
}
if (! spanSetFromAttributes(axis, r, cssWidth, cssHeight)) {
r = super.calculateMajorAxisRequirements(axis, r);
}
else {
// Offset by the margins so that pref/min/max return the
// right value.
SizeRequirements parentR = super.calculateMajorAxisRequirements(
axis, null);
int margin = (axis == X_AXIS) ? getLeftInset() + getRightInset() :
getTopInset() + getBottomInset();
r.minimum -= margin;
r.preferred -= margin;
r.maximum -= margin;
constrainSize(axis, r, parentR);
}
return r;
}
/** {@collect.stats}
* Calculate the requirements of the block along the minor
* axis (i.e. the axis orthoginal to the axis along with it tiles).
* This is implemented
* to provide the superclass behavior and then adjust it if the
* CSS width or height attribute is specified and applicable to
* the axis.
*/
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
if (r == null) {
r = new SizeRequirements();
}
if (! spanSetFromAttributes(axis, r, cssWidth, cssHeight)) {
/*
* The requirements were not directly specified by attributes, so
* compute the aggregate of the requirements of the children. The
* children that have a percentage value specified will be treated
* as completely stretchable since that child is not limited in any
* way.
*/
/*
int min = 0;
long pref = 0;
int max = 0;
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
min = Math.max((int) v.getMinimumSpan(axis), min);
pref = Math.max((int) v.getPreferredSpan(axis), pref);
if (
max = Math.max((int) v.getMaximumSpan(axis), max);
}
r.preferred = (int) pref;
r.minimum = min;
r.maximum = max;
*/
r = super.calculateMinorAxisRequirements(axis, r);
}
else {
// Offset by the margins so that pref/min/max return the
// right value.
SizeRequirements parentR = super.calculateMinorAxisRequirements(
axis, null);
int margin = (axis == X_AXIS) ? getLeftInset() + getRightInset() :
getTopInset() + getBottomInset();
r.minimum -= margin;
r.preferred -= margin;
r.maximum -= margin;
constrainSize(axis, r, parentR);
}
/*
* Set the alignment based upon the CSS properties if it is
* specified. For X_AXIS this would be text-align, for
* Y_AXIS this would be vertical-align.
*/
if (axis == X_AXIS) {
Object o = getAttributes().getAttribute(CSS.Attribute.TEXT_ALIGN);
if (o != null) {
String align = o.toString();
if (align.equals("center")) {
r.alignment = 0.5f;
} else if (align.equals("right")) {
r.alignment = 1.0f;
} else {
r.alignment = 0.0f;
}
}
}
// Y_AXIS TBD
return r;
}
boolean isPercentage(int axis, AttributeSet a) {
if (axis == X_AXIS) {
if (cssWidth != null) {
return cssWidth.isPercentage();
}
} else {
if (cssHeight != null) {
return cssHeight.isPercentage();
}
}
return false;
}
/** {@collect.stats}
* Adjust the given requirements to the CSS width or height if
* it is specified along the applicable axis. Return true if the
* size is exactly specified, false if the span is not specified
* in an attribute or the size specified is a percentage.
*/
static boolean spanSetFromAttributes(int axis, SizeRequirements r,
CSS.LengthValue cssWidth,
CSS.LengthValue cssHeight) {
if (axis == X_AXIS) {
if ((cssWidth != null) && (! cssWidth.isPercentage())) {
r.minimum = r.preferred = r.maximum = (int) cssWidth.getValue();
return true;
}
} else {
if ((cssHeight != null) && (! cssHeight.isPercentage())) {
r.minimum = r.preferred = r.maximum = (int) cssHeight.getValue();
return true;
}
}
return false;
}
/** {@collect.stats}
* Performs layout for the minor axis of the box (i.e. the
* axis orthoginal to the axis that it represents). The results
* of the layout (the offset and span for each children) are
* placed in the given arrays which represent the allocations to
* the children along the minor axis.
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the childre.
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views; this is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
*/
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
int n = getViewCount();
Object key = (axis == X_AXIS) ? CSS.Attribute.WIDTH : CSS.Attribute.HEIGHT;
for (int i = 0; i < n; i++) {
View v = getView(i);
int min = (int) v.getMinimumSpan(axis);
int max;
// check for percentage span
AttributeSet a = v.getAttributes();
CSS.LengthValue lv = (CSS.LengthValue) a.getAttribute(key);
if ((lv != null) && lv.isPercentage()) {
// bound the span to the percentage specified
min = Math.max((int) lv.getValue(targetSpan), min);
max = min;
} else {
max = (int)v.getMaximumSpan(axis);
}
// assign the offset and span for the child
if (max < targetSpan) {
// can't make the child this wide, align it
float align = v.getAlignment(axis);
offsets[i] = (int) ((targetSpan - max) * align);
spans[i] = max;
} else {
// make it the target width, or as small as it can get.
offsets[i] = 0;
spans[i] = Math.max(min, targetSpan);
}
}
}
/** {@collect.stats}
* Renders using the given rendering surface and area on that
* surface. This is implemented to delegate to the css box
* painter to paint the border and background prior to the
* interior.
*
* @param g the rendering surface to use
* @param allocation the allocated region to render into
* @see View#paint
*/
public void paint(Graphics g, Shape allocation) {
Rectangle a = (Rectangle) allocation;
painter.paint(g, a.x, a.y, a.width, a.height, this);
super.paint(g, a);
}
/** {@collect.stats}
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
if (attr == null) {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
}
return attr;
}
/** {@collect.stats}
* Gets the resize weight.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the weight
* @exception IllegalArgumentException for an invalid axis
*/
public int getResizeWeight(int axis) {
switch (axis) {
case View.X_AXIS:
return 1;
case View.Y_AXIS:
return 0;
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
/** {@collect.stats}
* Gets the alignment.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the alignment
*/
public float getAlignment(int axis) {
switch (axis) {
case View.X_AXIS:
return 0;
case View.Y_AXIS:
if (getViewCount() == 0) {
return 0;
}
float span = getPreferredSpan(View.Y_AXIS);
View v = getView(0);
float above = v.getPreferredSpan(View.Y_AXIS);
float a = (((int)span) != 0) ? (above * v.getAlignment(View.Y_AXIS)) / span: 0;
return a;
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
super.changedUpdate(changes, a, f);
int pos = changes.getOffset();
if (pos <= getStartOffset() && (pos + changes.getLength()) >=
getEndOffset()) {
setPropertiesFromAttributes();
}
}
/** {@collect.stats}
* Determines the preferred span for this view along an
* axis.
*
* @param axis may be either <code>View.X_AXIS</code>
* or <code>View.Y_AXIS</code>
* @return the span the view would like to be rendered into >= 0;
* typically the view is told to render into the span
* that is returned, although there is no guarantee;
* the parent may choose to resize or break the view
* @exception IllegalArgumentException for an invalid axis type
*/
public float getPreferredSpan(int axis) {
return super.getPreferredSpan(axis);
}
/** {@collect.stats}
* Determines the minimum span for this view along an
* axis.
*
* @param axis may be either <code>View.X_AXIS</code>
* or <code>View.Y_AXIS</code>
* @return the span the view would like to be rendered into >= 0;
* typically the view is told to render into the span
* that is returned, although there is no guarantee;
* the parent may choose to resize or break the view
* @exception IllegalArgumentException for an invalid axis type
*/
public float getMinimumSpan(int axis) {
return super.getMinimumSpan(axis);
}
/** {@collect.stats}
* Determines the maximum span for this view along an
* axis.
*
* @param axis may be either <code>View.X_AXIS</code>
* or <code>View.Y_AXIS</code>
* @return the span the view would like to be rendered into >= 0;
* typically the view is told to render into the span
* that is returned, although there is no guarantee;
* the parent may choose to resize or break the view
* @exception IllegalArgumentException for an invalid axis type
*/
public float getMaximumSpan(int axis) {
return super.getMaximumSpan(axis);
}
/** {@collect.stats}
* Update any cached values that come from attributes.
*/
protected void setPropertiesFromAttributes() {
// update attributes
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
// Reset the painter
painter = sheet.getBoxPainter(attr);
if (attr != null) {
setInsets((short) painter.getInset(TOP, this),
(short) painter.getInset(LEFT, this),
(short) painter.getInset(BOTTOM, this),
(short) painter.getInset(RIGHT, this));
}
// Get the width/height
cssWidth = (CSS.LengthValue) attr.getAttribute(CSS.Attribute.WIDTH);
cssHeight = (CSS.LengthValue) attr.getAttribute(CSS.Attribute.HEIGHT);
}
protected StyleSheet getStyleSheet() {
HTMLDocument doc = (HTMLDocument) getDocument();
return doc.getStyleSheet();
}
/** {@collect.stats}
* Constrains <code>want</code> to fit in the minimum size specified
* by <code>min</code>.
*/
private void constrainSize(int axis, SizeRequirements want,
SizeRequirements min) {
if (min.minimum > want.minimum) {
want.minimum = want.preferred = min.minimum;
want.maximum = Math.max(want.maximum, min.maximum);
}
}
private AttributeSet attr;
private StyleSheet.BoxPainter painter;
private CSS.LengthValue cssWidth;
private CSS.LengthValue cssHeight;
}
|
Java
|
/*
* Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import javax.swing.text.*;
import javax.swing.event.HyperlinkEvent;
import java.net.URL;
/** {@collect.stats}
* HTMLFrameHyperlinkEvent is used to notify interested
* parties that link was activated in a frame.
*
* @author Sunita Mani
*/
public class HTMLFrameHyperlinkEvent extends HyperlinkEvent {
/** {@collect.stats}
* Creates a new object representing a html frame
* hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param targetURL the affected URL
* @param targetFrame the Frame to display the document in
*/
public HTMLFrameHyperlinkEvent(Object source, EventType type, URL targetURL,
String targetFrame) {
super(source, type, targetURL);
this.targetFrame = targetFrame;
}
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param targetURL the affected URL
* @param desc a description
* @param targetFrame the Frame to display the document in
*/
public HTMLFrameHyperlinkEvent(Object source, EventType type, URL targetURL, String desc,
String targetFrame) {
super(source, type, targetURL, desc);
this.targetFrame = targetFrame;
}
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param targetURL the affected URL
* @param sourceElement the element that corresponds to the source
* of the event
* @param targetFrame the Frame to display the document in
*/
public HTMLFrameHyperlinkEvent(Object source, EventType type, URL targetURL,
Element sourceElement, String targetFrame) {
super(source, type, targetURL, null, sourceElement);
this.targetFrame = targetFrame;
}
/** {@collect.stats}
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param targetURL the affected URL
* @param desc a desription
* @param sourceElement the element that corresponds to the source
* of the event
* @param targetFrame the Frame to display the document in
*/
public HTMLFrameHyperlinkEvent(Object source, EventType type, URL targetURL, String desc,
Element sourceElement, String targetFrame) {
super(source, type, targetURL, desc, sourceElement);
this.targetFrame = targetFrame;
}
/** {@collect.stats}
* returns the target for the link.
*/
public String getTarget() {
return targetFrame;
}
private String targetFrame;
}
|
Java
|
/*
* Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.awt.*;
import javax.swing.SizeRequirements;
import javax.swing.event.DocumentEvent;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
/** {@collect.stats}
* Displays the a paragraph, and uses css attributes for its
* configuration.
*
* @author Timothy Prinzing
*/
public class ParagraphView extends javax.swing.text.ParagraphView {
/** {@collect.stats}
* Constructs a ParagraphView for the given element.
*
* @param elem the element that this view is responsible for
*/
public ParagraphView(Element elem) {
super(elem);
}
/** {@collect.stats}
* Establishes the parent view for this view. This is
* guaranteed to be called before any other methods if the
* parent view is functioning properly.
* <p>
* This is implemented
* to forward to the superclass as well as call the
* <a href="#setPropertiesFromAttributes">setPropertiesFromAttributes</a>
* method to set the paragraph properties from the css
* attributes. The call is made at this time to ensure
* the ability to resolve upward through the parents
* view attributes.
*
* @param parent the new parent, or null if the view is
* being removed from a parent it was previously added
* to
*/
public void setParent(View parent) {
super.setParent(parent);
if (parent != null) {
setPropertiesFromAttributes();
}
}
/** {@collect.stats}
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
if (attr == null) {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
}
return attr;
}
/** {@collect.stats}
* Sets up the paragraph from css attributes instead of
* the values found in StyleConstants (i.e. which are used
* by the superclass). Since
*/
protected void setPropertiesFromAttributes() {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
painter = sheet.getBoxPainter(attr);
if (attr != null) {
super.setPropertiesFromAttributes();
setInsets((short) painter.getInset(TOP, this),
(short) painter.getInset(LEFT, this),
(short) painter.getInset(BOTTOM, this),
(short) painter.getInset(RIGHT, this));
Object o = attr.getAttribute(CSS.Attribute.TEXT_ALIGN);
if (o != null) {
// set horizontal alignment
String ta = o.toString();
if (ta.equals("left")) {
setJustification(StyleConstants.ALIGN_LEFT);
} else if (ta.equals("center")) {
setJustification(StyleConstants.ALIGN_CENTER);
} else if (ta.equals("right")) {
setJustification(StyleConstants.ALIGN_RIGHT);
} else if (ta.equals("justify")) {
setJustification(StyleConstants.ALIGN_JUSTIFIED);
}
}
// Get the width/height
cssWidth = (CSS.LengthValue)attr.getAttribute(
CSS.Attribute.WIDTH);
cssHeight = (CSS.LengthValue)attr.getAttribute(
CSS.Attribute.HEIGHT);
}
}
protected StyleSheet getStyleSheet() {
HTMLDocument doc = (HTMLDocument) getDocument();
return doc.getStyleSheet();
}
/** {@collect.stats}
* Calculate the needs for the paragraph along the minor axis.
* This implemented to use the requirements of the superclass,
* modified slightly to set a minimum span allowed. Typical
* html rendering doesn't let the view size shrink smaller than
* the length of the longest word.
*/
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
r = super.calculateMinorAxisRequirements(axis, r);
if (!BlockView.spanSetFromAttributes(axis, r, cssWidth, cssHeight)) {
// PENDING(prinz) Need to make this better so it doesn't require
// InlineView and works with font changes within the word.
// find the longest minimum span.
float min = 0;
int n = getLayoutViewCount();
for (int i = 0; i < n; i++) {
View v = getLayoutView(i);
if (v instanceof InlineView) {
float wordSpan = ((InlineView) v).getLongestWordSpan();
min = Math.max(wordSpan, min);
} else {
min = Math.max(v.getMinimumSpan(axis), min);
}
}
r.minimum = Math.max(r.minimum, (int) min);
r.preferred = Math.max(r.minimum, r.preferred);
r.maximum = Math.max(r.preferred, r.maximum);
}
else {
// Offset by the margins so that pref/min/max return the
// right value.
int margin = (axis == X_AXIS) ? getLeftInset() + getRightInset() :
getTopInset() + getBottomInset();
r.minimum -= margin;
r.preferred -= margin;
r.maximum -= margin;
}
return r;
}
/** {@collect.stats}
* Indicates whether or not this view should be
* displayed. If none of the children wish to be
* displayed and the only visible child is the
* break that ends the paragraph, the paragraph
* will not be considered visible. Otherwise,
* it will be considered visible and return true.
*
* @return true if the paragraph should be displayed
*/
public boolean isVisible() {
int n = getLayoutViewCount() - 1;
for (int i = 0; i < n; i++) {
View v = getLayoutView(i);
if (v.isVisible()) {
return true;
}
}
if (n > 0) {
View v = getLayoutView(n);
if ((v.getEndOffset() - v.getStartOffset()) == 1) {
return false;
}
}
// If it's the last paragraph and not editable, it shouldn't
// be visible.
if (getStartOffset() == getDocument().getLength()) {
boolean editable = false;
Component c = getContainer();
if (c instanceof JTextComponent) {
editable = ((JTextComponent)c).isEditable();
}
if (!editable) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Renders using the given rendering surface and area on that
* surface. This is implemented to delgate to the superclass
* after stashing the base coordinate for tab calculations.
*
* @param g the rendering surface to use
* @param a the allocated region to render into
* @see View#paint
*/
public void paint(Graphics g, Shape a) {
if (a == null) {
return;
}
Rectangle r;
if (a instanceof Rectangle) {
r = (Rectangle) a;
} else {
r = a.getBounds();
}
painter.paint(g, r.x, r.y, r.width, r.height, this);
super.paint(g, a);
}
/** {@collect.stats}
* Determines the preferred span for this view. Returns
* 0 if the view is not visible, otherwise it calls the
* superclass method to get the preferred span.
* axis.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the span the view would like to be rendered into;
* typically the view is told to render into the span
* that is returned, although there is no guarantee;
* the parent may choose to resize or break the view
* @see javax.swing.text.ParagraphView#getPreferredSpan
*/
public float getPreferredSpan(int axis) {
if (!isVisible()) {
return 0;
}
return super.getPreferredSpan(axis);
}
/** {@collect.stats}
* Determines the minimum span for this view along an
* axis. Returns 0 if the view is not visible, otherwise
* it calls the superclass method to get the minimum span.
*
* @param axis may be either <code>View.X_AXIS</code> or
* <code>View.Y_AXIS</code>
* @return the minimum span the view can be rendered into
* @see javax.swing.text.ParagraphView#getMinimumSpan
*/
public float getMinimumSpan(int axis) {
if (!isVisible()) {
return 0;
}
return super.getMinimumSpan(axis);
}
/** {@collect.stats}
* Determines the maximum span for this view along an
* axis. Returns 0 if the view is not visible, otherwise
* it calls the superclass method ot get the maximum span.
*
* @param axis may be either <code>View.X_AXIS</code> or
* <code>View.Y_AXIS</code>
* @return the maximum span the view can be rendered into
* @see javax.swing.text.ParagraphView#getMaximumSpan
*/
public float getMaximumSpan(int axis) {
if (!isVisible()) {
return 0;
}
return super.getMaximumSpan(axis);
}
private AttributeSet attr;
private StyleSheet.BoxPainter painter;
private CSS.LengthValue cssWidth;
private CSS.LengthValue cssHeight;
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.awt.*;
import java.util.BitSet;
import java.util.Vector;
import java.util.Arrays;
import javax.swing.SizeRequirements;
import javax.swing.event.DocumentEvent;
import javax.swing.text.*;
/** {@collect.stats}
* HTML table view.
*
* @author Timothy Prinzing
* @see View
*/
/*public*/ class TableView extends BoxView implements ViewFactory {
/** {@collect.stats}
* Constructs a TableView for the given element.
*
* @param elem the element that this view is responsible for
*/
public TableView(Element elem) {
super(elem, View.Y_AXIS);
rows = new Vector();
gridValid = false;
captionIndex = -1;
totalColumnRequirements = new SizeRequirements();
}
/** {@collect.stats}
* Creates a new table row.
*
* @param elem an element
* @return the row
*/
protected RowView createTableRow(Element elem) {
// PENDING(prinz) need to add support for some of the other
// elements, but for now just ignore anything that is not
// a TR.
Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
if (o == HTML.Tag.TR) {
return new RowView(elem);
}
return null;
}
/** {@collect.stats}
* The number of columns in the table.
*/
public int getColumnCount() {
return columnSpans.length;
}
/** {@collect.stats}
* Fetches the span (width) of the given column.
* This is used by the nested cells to query the
* sizes of grid locations outside of themselves.
*/
public int getColumnSpan(int col) {
if (col < columnSpans.length) {
return columnSpans[col];
}
return 0;
}
/** {@collect.stats}
* The number of rows in the table.
*/
public int getRowCount() {
return rows.size();
}
/** {@collect.stats}
* Fetch the span of multiple rows. This includes
* the border area.
*/
public int getMultiRowSpan(int row0, int row1) {
RowView rv0 = getRow(row0);
RowView rv1 = getRow(row1);
if ((rv0 != null) && (rv1 != null)) {
int index0 = rv0.viewIndex;
int index1 = rv1.viewIndex;
int span = getOffset(Y_AXIS, index1) - getOffset(Y_AXIS, index0) +
getSpan(Y_AXIS, index1);
return span;
}
return 0;
}
/** {@collect.stats}
* Fetches the span (height) of the given row.
*/
public int getRowSpan(int row) {
RowView rv = getRow(row);
if (rv != null) {
return getSpan(Y_AXIS, rv.viewIndex);
}
return 0;
}
RowView getRow(int row) {
if (row < rows.size()) {
return (RowView) rows.elementAt(row);
}
return null;
}
protected View getViewAtPoint(int x, int y, Rectangle alloc) {
int n = getViewCount();
View v = null;
Rectangle allocation = new Rectangle();
for (int i = 0; i < n; i++) {
allocation.setBounds(alloc);
childAllocation(i, allocation);
v = getView(i);
if (v instanceof RowView) {
v = ((RowView)v).findViewAtPoint(x, y, allocation);
if (v != null) {
alloc.setBounds(allocation);
return v;
}
}
}
return super.getViewAtPoint(x, y, alloc);
}
/** {@collect.stats}
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
protected int getColumnsOccupied(View v) {
AttributeSet a = v.getElement().getAttributes();
if (a.isDefined(HTML.Attribute.COLSPAN)) {
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
}
return 1;
}
/** {@collect.stats}
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
protected int getRowsOccupied(View v) {
AttributeSet a = v.getElement().getAttributes();
if (a.isDefined(HTML.Attribute.ROWSPAN)) {
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
}
return 1;
}
protected void invalidateGrid() {
gridValid = false;
}
protected StyleSheet getStyleSheet() {
HTMLDocument doc = (HTMLDocument) getDocument();
return doc.getStyleSheet();
}
/** {@collect.stats}
* Update the insets, which contain the caption if there
* is a caption.
*/
void updateInsets() {
short top = (short) painter.getInset(TOP, this);
short bottom = (short) painter.getInset(BOTTOM, this);
if (captionIndex != -1) {
View caption = getView(captionIndex);
short h = (short) caption.getPreferredSpan(Y_AXIS);
AttributeSet a = caption.getAttributes();
Object align = a.getAttribute(CSS.Attribute.CAPTION_SIDE);
if ((align != null) && (align.equals("bottom"))) {
bottom += h;
} else {
top += h;
}
}
setInsets(top, (short) painter.getInset(LEFT, this),
bottom, (short) painter.getInset(RIGHT, this));
}
/** {@collect.stats}
* Update any cached values that come from attributes.
*/
protected void setPropertiesFromAttributes() {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
painter = sheet.getBoxPainter(attr);
if (attr != null) {
setInsets((short) painter.getInset(TOP, this),
(short) painter.getInset(LEFT, this),
(short) painter.getInset(BOTTOM, this),
(short) painter.getInset(RIGHT, this));
CSS.LengthValue lv = (CSS.LengthValue)
attr.getAttribute(CSS.Attribute.BORDER_SPACING);
if (lv != null) {
cellSpacing = (int) lv.getValue();
} else {
cellSpacing = 0;
}
lv = (CSS.LengthValue)
attr.getAttribute(CSS.Attribute.BORDER_TOP_WIDTH);
if (lv != null) {
borderWidth = (int) lv.getValue();
} else {
borderWidth = 0;
}
}
}
/** {@collect.stats}
* Fill in the grid locations that are placeholders
* for multi-column, multi-row, and missing grid
* locations.
*/
void updateGrid() {
if (! gridValid) {
relativeCells = false;
multiRowCells = false;
// determine which views are table rows and clear out
// grid points marked filled.
captionIndex = -1;
rows.removeAllElements();
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
if (v instanceof RowView) {
rows.addElement(v);
RowView rv = (RowView) v;
rv.clearFilledColumns();
rv.rowIndex = rows.size() - 1;
rv.viewIndex = i;
} else {
Object o = v.getElement().getAttributes().getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag) o;
if (kind == HTML.Tag.CAPTION) {
captionIndex = i;
}
}
}
}
int maxColumns = 0;
int nrows = rows.size();
for (int row = 0; row < nrows; row++) {
RowView rv = getRow(row);
int col = 0;
for (int cell = 0; cell < rv.getViewCount(); cell++, col++) {
View cv = rv.getView(cell);
if (! relativeCells) {
AttributeSet a = cv.getAttributes();
CSS.LengthValue lv = (CSS.LengthValue)
a.getAttribute(CSS.Attribute.WIDTH);
if ((lv != null) && (lv.isPercentage())) {
relativeCells = true;
}
}
// advance to a free column
for (; rv.isFilled(col); col++);
int rowSpan = getRowsOccupied(cv);
if (rowSpan > 1) {
multiRowCells = true;
}
int colSpan = getColumnsOccupied(cv);
if ((colSpan > 1) || (rowSpan > 1)) {
// fill in the overflow entries for this cell
int rowLimit = row + rowSpan;
int colLimit = col + colSpan;
for (int i = row; i < rowLimit; i++) {
for (int j = col; j < colLimit; j++) {
if (i != row || j != col) {
addFill(i, j);
}
}
}
if (colSpan > 1) {
col += colSpan - 1;
}
}
}
maxColumns = Math.max(maxColumns, col);
}
// setup the column layout/requirements
columnSpans = new int[maxColumns];
columnOffsets = new int[maxColumns];
columnRequirements = new SizeRequirements[maxColumns];
for (int i = 0; i < maxColumns; i++) {
columnRequirements[i] = new SizeRequirements();
columnRequirements[i].maximum = Integer.MAX_VALUE;
}
gridValid = true;
}
}
/** {@collect.stats}
* Mark a grid location as filled in for a cells overflow.
*/
void addFill(int row, int col) {
RowView rv = getRow(row);
if (rv != null) {
rv.fillColumn(col);
}
}
/** {@collect.stats}
* Layout the columns to fit within the given target span.
*
* @param targetSpan the given span for total of all the table
* columns
* @param reqs the requirements desired for each column. This
* is the column maximum of the cells minimum, preferred, and
* maximum requested span
* @param spans the return value of how much to allocated to
* each column
* @param offsets the return value of the offset from the
* origin for each column
* @return the offset from the origin and the span for each column
* in the offsets and spans parameters
*/
protected void layoutColumns(int targetSpan, int[] offsets, int[] spans,
SizeRequirements[] reqs) {
//clean offsets and spans
Arrays.fill(offsets, 0);
Arrays.fill(spans, 0);
colIterator.setLayoutArrays(offsets, spans, targetSpan);
CSS.calculateTiledLayout(colIterator, targetSpan);
}
/** {@collect.stats}
* Calculate the requirements for each column. The calculation
* is done as two passes over the table. The table cells that
* occupy a single column are scanned first to determine the
* maximum of minimum, preferred, and maximum spans along the
* give axis. Table cells that span multiple columns are excluded
* from the first pass. A second pass is made to determine if
* the cells that span multiple columns are satisfied. If the
* column requirements are not satisified, the needs of the
* multi-column cell is mixed into the existing column requirements.
* The calculation of the multi-column distribution is based upon
* the proportions of the existing column requirements and taking
* into consideration any constraining maximums.
*/
void calculateColumnRequirements(int axis) {
// clean columnRequirements
for (SizeRequirements req : columnRequirements) {
req.minimum = 0;
req.preferred = 0;
req.maximum = Integer.MAX_VALUE;
}
Container host = getContainer();
if (host != null) {
if (host instanceof JTextComponent) {
skipComments = !((JTextComponent)host).isEditable();
} else {
skipComments = true;
}
}
// pass 1 - single column cells
boolean hasMultiColumn = false;
int nrows = getRowCount();
for (int i = 0; i < nrows; i++) {
RowView row = getRow(i);
int col = 0;
int ncells = row.getViewCount();
for (int cell = 0; cell < ncells; cell++) {
View cv = row.getView(cell);
if (skipComments && !(cv instanceof CellView)) {
continue;
}
for (; row.isFilled(col); col++); // advance to a free column
int rowSpan = getRowsOccupied(cv);
int colSpan = getColumnsOccupied(cv);
if (colSpan == 1) {
checkSingleColumnCell(axis, col, cv);
} else {
hasMultiColumn = true;
col += colSpan - 1;
}
col++;
}
}
// pass 2 - multi-column cells
if (hasMultiColumn) {
for (int i = 0; i < nrows; i++) {
RowView row = getRow(i);
int col = 0;
int ncells = row.getViewCount();
for (int cell = 0; cell < ncells; cell++) {
View cv = row.getView(cell);
if (skipComments && !(cv instanceof CellView)) {
continue;
}
for (; row.isFilled(col); col++); // advance to a free column
int colSpan = getColumnsOccupied(cv);
if (colSpan > 1) {
checkMultiColumnCell(axis, col, colSpan, cv);
col += colSpan - 1;
}
col++;
}
}
}
}
/** {@collect.stats}
* check the requirements of a table cell that spans a single column.
*/
void checkSingleColumnCell(int axis, int col, View v) {
SizeRequirements req = columnRequirements[col];
req.minimum = Math.max((int) v.getMinimumSpan(axis), req.minimum);
req.preferred = Math.max((int) v.getPreferredSpan(axis), req.preferred);
}
/** {@collect.stats}
* check the requirements of a table cell that spans multiple
* columns.
*/
void checkMultiColumnCell(int axis, int col, int ncols, View v) {
// calculate the totals
long min = 0;
long pref = 0;
long max = 0;
for (int i = 0; i < ncols; i++) {
SizeRequirements req = columnRequirements[col + i];
min += req.minimum;
pref += req.preferred;
max += req.maximum;
}
// check if the minimum size needs adjustment.
int cmin = (int) v.getMinimumSpan(axis);
if (cmin > min) {
/*
* the columns that this cell spans need adjustment to fit
* this table cell.... calculate the adjustments.
*/
SizeRequirements[] reqs = new SizeRequirements[ncols];
for (int i = 0; i < ncols; i++) {
reqs[i] = columnRequirements[col + i];
}
int[] spans = new int[ncols];
int[] offsets = new int[ncols];
SizeRequirements.calculateTiledPositions(cmin, null, reqs,
offsets, spans);
// apply the adjustments
for (int i = 0; i < ncols; i++) {
SizeRequirements req = reqs[i];
req.minimum = Math.max(spans[i], req.minimum);
req.preferred = Math.max(req.minimum, req.preferred);
req.maximum = Math.max(req.preferred, req.maximum);
}
}
// check if the preferred size needs adjustment.
int cpref = (int) v.getPreferredSpan(axis);
if (cpref > pref) {
/*
* the columns that this cell spans need adjustment to fit
* this table cell.... calculate the adjustments.
*/
SizeRequirements[] reqs = new SizeRequirements[ncols];
for (int i = 0; i < ncols; i++) {
reqs[i] = columnRequirements[col + i];
}
int[] spans = new int[ncols];
int[] offsets = new int[ncols];
SizeRequirements.calculateTiledPositions(cpref, null, reqs,
offsets, spans);
// apply the adjustments
for (int i = 0; i < ncols; i++) {
SizeRequirements req = reqs[i];
req.preferred = Math.max(spans[i], req.preferred);
req.maximum = Math.max(req.preferred, req.maximum);
}
}
}
// --- BoxView methods -----------------------------------------
/** {@collect.stats}
* Calculate the requirements for the minor axis. This is called by
* the superclass whenever the requirements need to be updated (i.e.
* a preferenceChanged was messaged through this view).
* <p>
* This is implemented to calculate the requirements as the sum of the
* requirements of the columns and then adjust it if the
* CSS width or height attribute is specified and applicable to
* the axis.
*/
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
updateGrid();
// calculate column requirements for each column
calculateColumnRequirements(axis);
// the requirements are the sum of the columns.
if (r == null) {
r = new SizeRequirements();
}
long min = 0;
long pref = 0;
int n = columnRequirements.length;
for (int i = 0; i < n; i++) {
SizeRequirements req = columnRequirements[i];
min += req.minimum;
pref += req.preferred;
}
int adjust = (n + 1) * cellSpacing + 2 * borderWidth;
min += adjust;
pref += adjust;
r.minimum = (int) min;
r.preferred = (int) pref;
r.maximum = (int) pref;
AttributeSet attr = getAttributes();
CSS.LengthValue cssWidth = (CSS.LengthValue)attr.getAttribute(
CSS.Attribute.WIDTH);
if (BlockView.spanSetFromAttributes(axis, r, cssWidth, null)) {
if (r.minimum < (int)min) {
// The user has requested a smaller size than is needed to
// show the table, override it.
r.maximum = r.minimum = r.preferred = (int) min;
}
}
totalColumnRequirements.minimum = r.minimum;
totalColumnRequirements.preferred = r.preferred;
totalColumnRequirements.maximum = r.maximum;
// set the alignment
Object o = attr.getAttribute(CSS.Attribute.TEXT_ALIGN);
if (o != null) {
// set horizontal alignment
String ta = o.toString();
if (ta.equals("left")) {
r.alignment = 0;
} else if (ta.equals("center")) {
r.alignment = 0.5f;
} else if (ta.equals("right")) {
r.alignment = 1;
} else {
r.alignment = 0;
}
} else {
r.alignment = 0;
}
return r;
}
/** {@collect.stats}
* Calculate the requirements for the major axis. This is called by
* the superclass whenever the requirements need to be updated (i.e.
* a preferenceChanged was messaged through this view).
* <p>
* This is implemented to provide the superclass behavior adjusted for
* multi-row table cells.
*/
protected SizeRequirements calculateMajorAxisRequirements(int axis, SizeRequirements r) {
updateInsets();
rowIterator.updateAdjustments();
r = CSS.calculateTiledRequirements(rowIterator, r);
r.maximum = r.preferred;
return r;
}
/** {@collect.stats}
* Perform layout for the minor axis of the box (i.e. the
* axis orthoginal to the axis that it represents). The results
* of the layout should be placed in the given arrays which represent
* the allocations to the children along the minor axis. This
* is called by the superclass whenever the layout needs to be
* updated along the minor axis.
* <p>
* This is implemented to call the
* <a href="#layoutColumns">layoutColumns</a> method, and then
* forward to the superclass to actually carry out the layout
* of the tables rows.
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the children
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views. This is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
* @return the offset and span for each child view in the
* offsets and spans parameters
*/
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
// make grid is properly represented
updateGrid();
// all of the row layouts are invalid, so mark them that way
int n = getRowCount();
for (int i = 0; i < n; i++) {
RowView row = getRow(i);
row.layoutChanged(axis);
}
// calculate column spans
layoutColumns(targetSpan, columnOffsets, columnSpans, columnRequirements);
// continue normal layout
super.layoutMinorAxis(targetSpan, axis, offsets, spans);
}
/** {@collect.stats}
* Perform layout for the major axis of the box (i.e. the
* axis that it represents). The results
* of the layout should be placed in the given arrays which represent
* the allocations to the children along the minor axis. This
* is called by the superclass whenever the layout needs to be
* updated along the minor axis.
* <p>
* This method is where the layout of the table rows within the
* table takes place. This method is implemented to call the use
* the RowIterator and the CSS collapsing tile to layout
* with border spacing and border collapsing capabilities.
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the children
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views; this is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
* @return the offset and span for each child view in the
* offsets and spans parameters
*/
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
rowIterator.setLayoutArrays(offsets, spans);
CSS.calculateTiledLayout(rowIterator, targetSpan);
if (captionIndex != -1) {
// place the caption
View caption = getView(captionIndex);
int h = (int) caption.getPreferredSpan(Y_AXIS);
spans[captionIndex] = h;
short boxBottom = (short) painter.getInset(BOTTOM, this);
if (boxBottom != getBottomInset()) {
offsets[captionIndex] = targetSpan + boxBottom;
} else {
offsets[captionIndex] = - getTopInset();
}
}
}
/** {@collect.stats}
* Fetches the child view that represents the given position in
* the model. This is implemented to walk through the children
* looking for a range that contains the given position. In this
* view the children do not necessarily have a one to one mapping
* with the child elements.
*
* @param pos the search position >= 0
* @param a the allocation to the table on entry, and the
* allocation of the view containing the position on exit
* @return the view representing the given position, or
* null if there isn't one
*/
protected View getViewAtPosition(int pos, Rectangle a) {
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
int p0 = v.getStartOffset();
int p1 = v.getEndOffset();
if ((pos >= p0) && (pos < p1)) {
// it's in this view.
if (a != null) {
childAllocation(i, a);
}
return v;
}
}
if (pos == getEndOffset()) {
View v = getView(n - 1);
if (a != null) {
this.childAllocation(n - 1, a);
}
return v;
}
return null;
}
// --- View methods ---------------------------------------------
/** {@collect.stats}
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
if (attr == null) {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
}
return attr;
}
/** {@collect.stats}
* Renders using the given rendering surface and area on that
* surface. This is implemented to delegate to the css box
* painter to paint the border and background prior to the
* interior. The superclass culls rendering the children
* that don't directly intersect the clip and the row may
* have cells hanging from a row above in it. The table
* does not use the superclass rendering behavior and instead
* paints all of the rows and lets the rows cull those
* cells not intersecting the clip region.
*
* @param g the rendering surface to use
* @param allocation the allocated region to render into
* @see View#paint
*/
public void paint(Graphics g, Shape allocation) {
// paint the border
Rectangle a = allocation.getBounds();
setSize(a.width, a.height);
if (captionIndex != -1) {
// adjust the border for the caption
short top = (short) painter.getInset(TOP, this);
short bottom = (short) painter.getInset(BOTTOM, this);
if (top != getTopInset()) {
int h = getTopInset() - top;
a.y += h;
a.height -= h;
} else {
a.height -= getBottomInset() - bottom;
}
}
painter.paint(g, a.x, a.y, a.width, a.height, this);
// paint interior
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
v.paint(g, getChildAllocation(i, allocation));
}
//super.paint(g, a);
}
/** {@collect.stats}
* Establishes the parent view for this view. This is
* guaranteed to be called before any other methods if the
* parent view is functioning properly.
* <p>
* This is implemented
* to forward to the superclass as well as call the
* <a href="#setPropertiesFromAttributes">setPropertiesFromAttributes</a>
* method to set the paragraph properties from the css
* attributes. The call is made at this time to ensure
* the ability to resolve upward through the parents
* view attributes.
*
* @param parent the new parent, or null if the view is
* being removed from a parent it was previously added
* to
*/
public void setParent(View parent) {
super.setParent(parent);
if (parent != null) {
setPropertiesFromAttributes();
}
}
/** {@collect.stats}
* Fetches the ViewFactory implementation that is feeding
* the view hierarchy.
* This replaces the ViewFactory with an implementation that
* calls through to the createTableRow and createTableCell
* methods. If the element given to the factory isn't a
* table row or cell, the request is delegated to the factory
* produced by the superclass behavior.
*
* @return the factory, null if none
*/
public ViewFactory getViewFactory() {
return this;
}
/** {@collect.stats}
* Gives notification that something was inserted into
* the document in a location that this view is responsible for.
* This replaces the ViewFactory with an implementation that
* calls through to the createTableRow and createTableCell
* methods. If the element given to the factory isn't a
* table row or cell, the request is delegated to the factory
* passed as an argument.
*
* @param e the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#insertUpdate
*/
public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) {
super.insertUpdate(e, a, this);
}
/** {@collect.stats}
* Gives notification that something was removed from the document
* in a location that this view is responsible for.
* This replaces the ViewFactory with an implementation that
* calls through to the createTableRow and createTableCell
* methods. If the element given to the factory isn't a
* table row or cell, the request is delegated to the factory
* passed as an argument.
*
* @param e the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#removeUpdate
*/
public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) {
super.removeUpdate(e, a, this);
}
/** {@collect.stats}
* Gives notification from the document that attributes were changed
* in a location that this view is responsible for.
* This replaces the ViewFactory with an implementation that
* calls through to the createTableRow and createTableCell
* methods. If the element given to the factory isn't a
* table row or cell, the request is delegated to the factory
* passed as an argument.
*
* @param e the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#changedUpdate
*/
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
super.changedUpdate(e, a, this);
}
protected void forwardUpdate(DocumentEvent.ElementChange ec,
DocumentEvent e, Shape a, ViewFactory f) {
super.forwardUpdate(ec, e, a, f);
// A change in any of the table cells usually effects the whole table,
// so redraw it all!
if (a != null) {
Component c = getContainer();
if (c != null) {
Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a :
a.getBounds();
c.repaint(alloc.x, alloc.y, alloc.width, alloc.height);
}
}
}
/** {@collect.stats}
* Change the child views. This is implemented to
* provide the superclass behavior and invalidate the
* grid so that rows and columns will be recalculated.
*/
public void replace(int offset, int length, View[] views) {
super.replace(offset, length, views);
invalidateGrid();
}
// --- ViewFactory methods ------------------------------------------
/** {@collect.stats}
* The table itself acts as a factory for the various
* views that actually represent pieces of the table.
* All other factory activity is delegated to the factory
* returned by the parent of the table.
*/
public View create(Element elem) {
Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag) o;
if (kind == HTML.Tag.TR) {
return createTableRow(elem);
} else if ((kind == HTML.Tag.TD) || (kind == HTML.Tag.TH)) {
return new CellView(elem);
} else if (kind == HTML.Tag.CAPTION) {
return new javax.swing.text.html.ParagraphView(elem);
}
}
// default is to delegate to the normal factory
View p = getParent();
if (p != null) {
ViewFactory f = p.getViewFactory();
if (f != null) {
return f.create(elem);
}
}
return null;
}
// ---- variables ----------------------------------------------------
private AttributeSet attr;
private StyleSheet.BoxPainter painter;
private int cellSpacing;
private int borderWidth;
/** {@collect.stats}
* The index of the caption view if there is a caption.
* This has a value of -1 if there is no caption. The
* caption lives in the inset area of the table, and is
* updated with each time the grid is recalculated.
*/
private int captionIndex;
/** {@collect.stats}
* Do any of the table cells contain a relative size
* specification? This is updated with each call to
* updateGrid(). If this is true, the ColumnIterator
* will do extra work to calculate relative cell
* specifications.
*/
private boolean relativeCells;
/** {@collect.stats}
* Do any of the table cells span multiple rows? If
* true, the RowRequirementIterator will do additional
* work to adjust the requirements of rows spanned by
* a single table cell. This is updated with each call to
* updateGrid().
*/
private boolean multiRowCells;
int[] columnSpans;
int[] columnOffsets;
/** {@collect.stats}
* SizeRequirements for all the columns.
*/
SizeRequirements totalColumnRequirements;
SizeRequirements[] columnRequirements;
RowIterator rowIterator = new RowIterator();
ColumnIterator colIterator = new ColumnIterator();
Vector rows;
// whether to display comments inside table or not.
boolean skipComments = false;
boolean gridValid;
static final private BitSet EMPTY = new BitSet();
class ColumnIterator implements CSS.LayoutIterator {
/** {@collect.stats}
* Disable percentage adjustments which should only apply
* when calculating layout, not requirements.
*/
void disablePercentages() {
percentages = null;
}
/** {@collect.stats}
* Update percentage adjustments if they are needed.
*/
private void updatePercentagesAndAdjustmentWeights(int span) {
adjustmentWeights = new int[columnRequirements.length];
for (int i = 0; i < columnRequirements.length; i++) {
adjustmentWeights[i] = 0;
}
if (relativeCells) {
percentages = new int[columnRequirements.length];
} else {
percentages = null;
}
int nrows = getRowCount();
for (int rowIndex = 0; rowIndex < nrows; rowIndex++) {
RowView row = getRow(rowIndex);
int col = 0;
int ncells = row.getViewCount();
for (int cell = 0; cell < ncells; cell++, col++) {
View cv = row.getView(cell);
for (; row.isFilled(col); col++); // advance to a free column
int rowSpan = getRowsOccupied(cv);
int colSpan = getColumnsOccupied(cv);
AttributeSet a = cv.getAttributes();
CSS.LengthValue lv = (CSS.LengthValue)
a.getAttribute(CSS.Attribute.WIDTH);
if ( lv != null ) {
int len = (int) (lv.getValue(span) / colSpan + 0.5f);
for (int i = 0; i < colSpan; i++) {
if (lv.isPercentage()) {
// add a percentage requirement
percentages[col+i] = Math.max(percentages[col+i], len);
adjustmentWeights[col + i] = Math.max(adjustmentWeights[col + i], WorstAdjustmentWeight);
} else {
adjustmentWeights[col + i] = Math.max(adjustmentWeights[col + i], WorstAdjustmentWeight - 1);
}
}
}
col += colSpan - 1;
}
}
}
/** {@collect.stats}
* Set the layout arrays to use for holding layout results
*/
public void setLayoutArrays(int offsets[], int spans[], int targetSpan) {
this.offsets = offsets;
this.spans = spans;
updatePercentagesAndAdjustmentWeights(targetSpan);
}
// --- RequirementIterator methods -------------------
public int getCount() {
return columnRequirements.length;
}
public void setIndex(int i) {
col = i;
}
public void setOffset(int offs) {
offsets[col] = offs;
}
public int getOffset() {
return offsets[col];
}
public void setSpan(int span) {
spans[col] = span;
}
public int getSpan() {
return spans[col];
}
public float getMinimumSpan(float parentSpan) {
// do not care for percentages, since min span can't
// be less than columnRequirements[col].minimum,
// but can be less than percentage value.
return columnRequirements[col].minimum;
}
public float getPreferredSpan(float parentSpan) {
if ((percentages != null) && (percentages[col] != 0)) {
return Math.max(percentages[col], columnRequirements[col].minimum);
}
return columnRequirements[col].preferred;
}
public float getMaximumSpan(float parentSpan) {
return columnRequirements[col].maximum;
}
public float getBorderWidth() {
return borderWidth;
}
public float getLeadingCollapseSpan() {
return cellSpacing;
}
public float getTrailingCollapseSpan() {
return cellSpacing;
}
public int getAdjustmentWeight() {
return adjustmentWeights[col];
}
/** {@collect.stats}
* Current column index
*/
private int col;
/** {@collect.stats}
* percentage values (may be null since there
* might not be any).
*/
private int[] percentages;
private int[] adjustmentWeights;
private int[] offsets;
private int[] spans;
}
class RowIterator implements CSS.LayoutIterator {
RowIterator() {
}
void updateAdjustments() {
int axis = Y_AXIS;
if (multiRowCells) {
// adjust requirements of multi-row cells
int n = getRowCount();
adjustments = new int[n];
for (int i = 0; i < n; i++) {
RowView rv = getRow(i);
if (rv.multiRowCells == true) {
int ncells = rv.getViewCount();
for (int j = 0; j < ncells; j++) {
View v = rv.getView(j);
int nrows = getRowsOccupied(v);
if (nrows > 1) {
int spanNeeded = (int) v.getPreferredSpan(axis);
adjustMultiRowSpan(spanNeeded, nrows, i);
}
}
}
}
} else {
adjustments = null;
}
}
/** {@collect.stats}
* Fixup preferences to accomodate a multi-row table cell
* if not already covered by existing preferences. This is
* a no-op if not all of the rows needed (to do this check/fixup)
* have arrived yet.
*/
void adjustMultiRowSpan(int spanNeeded, int nrows, int rowIndex) {
if ((rowIndex + nrows) > getCount()) {
// rows are missing (could be a bad rowspan specification)
// or not all the rows have arrived. Do the best we can with
// the current set of rows.
nrows = getCount() - rowIndex;
if (nrows < 1) {
return;
}
}
int span = 0;
for (int i = 0; i < nrows; i++) {
RowView rv = getRow(rowIndex + i);
span += rv.getPreferredSpan(Y_AXIS);
}
if (spanNeeded > span) {
int adjust = (spanNeeded - span);
int rowAdjust = adjust / nrows;
int firstAdjust = rowAdjust + (adjust - (rowAdjust * nrows));
RowView rv = getRow(rowIndex);
adjustments[rowIndex] = Math.max(adjustments[rowIndex],
firstAdjust);
for (int i = 1; i < nrows; i++) {
adjustments[rowIndex + i] = Math.max(
adjustments[rowIndex + i], rowAdjust);
}
}
}
void setLayoutArrays(int[] offsets, int[] spans) {
this.offsets = offsets;
this.spans = spans;
}
// --- RequirementIterator methods -------------------
public void setOffset(int offs) {
RowView rv = getRow(row);
if (rv != null) {
offsets[rv.viewIndex] = offs;
}
}
public int getOffset() {
RowView rv = getRow(row);
if (rv != null) {
return offsets[rv.viewIndex];
}
return 0;
}
public void setSpan(int span) {
RowView rv = getRow(row);
if (rv != null) {
spans[rv.viewIndex] = span;
}
}
public int getSpan() {
RowView rv = getRow(row);
if (rv != null) {
return spans[rv.viewIndex];
}
return 0;
}
public int getCount() {
return rows.size();
}
public void setIndex(int i) {
row = i;
}
public float getMinimumSpan(float parentSpan) {
return getPreferredSpan(parentSpan);
}
public float getPreferredSpan(float parentSpan) {
RowView rv = getRow(row);
if (rv != null) {
int adjust = (adjustments != null) ? adjustments[row] : 0;
return rv.getPreferredSpan(TableView.this.getAxis()) + adjust;
}
return 0;
}
public float getMaximumSpan(float parentSpan) {
return getPreferredSpan(parentSpan);
}
public float getBorderWidth() {
return borderWidth;
}
public float getLeadingCollapseSpan() {
return cellSpacing;
}
public float getTrailingCollapseSpan() {
return cellSpacing;
}
public int getAdjustmentWeight() {
return 0;
}
/** {@collect.stats}
* Current row index
*/
private int row;
/** {@collect.stats}
* Adjustments to the row requirements to handle multi-row
* table cells.
*/
private int[] adjustments;
private int[] offsets;
private int[] spans;
}
/** {@collect.stats}
* View of a row in a row-centric table.
*/
public class RowView extends BoxView {
/** {@collect.stats}
* Constructs a TableView for the given element.
*
* @param elem the element that this view is responsible for
*/
public RowView(Element elem) {
super(elem, View.X_AXIS);
fillColumns = new BitSet();
RowView.this.setPropertiesFromAttributes();
}
void clearFilledColumns() {
fillColumns.and(EMPTY);
}
void fillColumn(int col) {
fillColumns.set(col);
}
boolean isFilled(int col) {
return fillColumns.get(col);
}
/** {@collect.stats}
* The number of columns present in this row.
*/
int getColumnCount() {
int nfill = 0;
int n = fillColumns.size();
for (int i = 0; i < n; i++) {
if (fillColumns.get(i)) {
nfill ++;
}
}
return getViewCount() + nfill;
}
/** {@collect.stats}
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
return attr;
}
View findViewAtPoint(int x, int y, Rectangle alloc) {
int n = getViewCount();
for (int i = 0; i < n; i++) {
if (getChildAllocation(i, alloc).contains(x, y)) {
childAllocation(i, alloc);
return getView(i);
}
}
return null;
}
protected StyleSheet getStyleSheet() {
HTMLDocument doc = (HTMLDocument) getDocument();
return doc.getStyleSheet();
}
/** {@collect.stats}
* This is called by a child to indicate its
* preferred span has changed. This is implemented to
* execute the superclass behavior and well as try to
* determine if a row with a multi-row cell hangs across
* this row. If a multi-row cell covers this row it also
* needs to propagate a preferenceChanged so that it will
* recalculate the multi-row cell.
*
* @param child the child view
* @param width true if the width preference should change
* @param height true if the height preference should change
*/
public void preferenceChanged(View child, boolean width, boolean height) {
super.preferenceChanged(child, width, height);
if (TableView.this.multiRowCells && height) {
for (int i = rowIndex - 1; i >= 0; i--) {
RowView rv = TableView.this.getRow(i);
if (rv.multiRowCells) {
rv.preferenceChanged(null, false, true);
break;
}
}
}
}
// The major axis requirements for a row are dictated by the column
// requirements. These methods use the value calculated by
// TableView.
protected SizeRequirements calculateMajorAxisRequirements(int axis, SizeRequirements r) {
SizeRequirements req = new SizeRequirements();
req.minimum = totalColumnRequirements.minimum;
req.maximum = totalColumnRequirements.maximum;
req.preferred = totalColumnRequirements.preferred;
req.alignment = 0f;
return req;
}
public float getMinimumSpan(int axis) {
float value;
if (axis == View.X_AXIS) {
value = totalColumnRequirements.minimum + getLeftInset() +
getRightInset();
}
else {
value = super.getMinimumSpan(axis);
}
return value;
}
public float getMaximumSpan(int axis) {
float value;
if (axis == View.X_AXIS) {
// We're flexible.
value = (float)Integer.MAX_VALUE;
}
else {
value = super.getMaximumSpan(axis);
}
return value;
}
public float getPreferredSpan(int axis) {
float value;
if (axis == View.X_AXIS) {
value = totalColumnRequirements.preferred + getLeftInset() +
getRightInset();
}
else {
value = super.getPreferredSpan(axis);
}
return value;
}
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
super.changedUpdate(e, a, f);
int pos = e.getOffset();
if (pos <= getStartOffset() && (pos + e.getLength()) >=
getEndOffset()) {
RowView.this.setPropertiesFromAttributes();
}
}
/** {@collect.stats}
* Renders using the given rendering surface and area on that
* surface. This is implemented to delegate to the css box
* painter to paint the border and background prior to the
* interior.
*
* @param g the rendering surface to use
* @param allocation the allocated region to render into
* @see View#paint
*/
public void paint(Graphics g, Shape allocation) {
Rectangle a = (Rectangle) allocation;
painter.paint(g, a.x, a.y, a.width, a.height, this);
super.paint(g, a);
}
/** {@collect.stats}
* Change the child views. This is implemented to
* provide the superclass behavior and invalidate the
* grid so that rows and columns will be recalculated.
*/
public void replace(int offset, int length, View[] views) {
super.replace(offset, length, views);
invalidateGrid();
}
/** {@collect.stats}
* Calculate the height requirements of the table row. The
* requirements of multi-row cells are not considered for this
* calculation. The table itself will check and adjust the row
* requirements for all the rows that have multi-row cells spanning
* them. This method updates the multi-row flag that indicates that
* this row and rows below need additional consideration.
*/
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
// return super.calculateMinorAxisRequirements(axis, r);
long min = 0;
long pref = 0;
long max = 0;
multiRowCells = false;
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
if (getRowsOccupied(v) > 1) {
multiRowCells = true;
max = Math.max((int) v.getMaximumSpan(axis), max);
} else {
min = Math.max((int) v.getMinimumSpan(axis), min);
pref = Math.max((int) v.getPreferredSpan(axis), pref);
max = Math.max((int) v.getMaximumSpan(axis), max);
}
}
if (r == null) {
r = new SizeRequirements();
r.alignment = 0.5f;
}
r.preferred = (int) pref;
r.minimum = (int) min;
r.maximum = (int) max;
return r;
}
/** {@collect.stats}
* Perform layout for the major axis of the box (i.e. the
* axis that it represents). The results of the layout should
* be placed in the given arrays which represent the allocations
* to the children along the major axis.
* <p>
* This is re-implemented to give each child the span of the column
* width for the table, and to give cells that span multiple columns
* the multi-column span.
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the children
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views; this is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
* @return the offset and span for each child view in the
* offsets and spans parameters
*/
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
int col = 0;
int ncells = getViewCount();
for (int cell = 0; cell < ncells; cell++) {
View cv = getView(cell);
if (skipComments && !(cv instanceof CellView)) {
continue;
}
for (; isFilled(col); col++); // advance to a free column
int colSpan = getColumnsOccupied(cv);
spans[cell] = columnSpans[col];
offsets[cell] = columnOffsets[col];
if (colSpan > 1) {
int n = columnSpans.length;
for (int j = 1; j < colSpan; j++) {
// Because the table may be only partially formed, some
// of the columns may not yet exist. Therefore we check
// the bounds.
if ((col+j) < n) {
spans[cell] += columnSpans[col+j];
spans[cell] += cellSpacing;
}
}
col += colSpan - 1;
}
col++;
}
}
/** {@collect.stats}
* Perform layout for the minor axis of the box (i.e. the
* axis orthoginal to the axis that it represents). The results
* of the layout should be placed in the given arrays which represent
* the allocations to the children along the minor axis. This
* is called by the superclass whenever the layout needs to be
* updated along the minor axis.
* <p>
* This is implemented to delegate to the superclass, then adjust
* the span for any cell that spans multiple rows.
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the children
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views; this is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
* @return the offset and span for each child view in the
* offsets and spans parameters
*/
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
super.layoutMinorAxis(targetSpan, axis, offsets, spans);
int col = 0;
int ncells = getViewCount();
for (int cell = 0; cell < ncells; cell++, col++) {
View cv = getView(cell);
for (; isFilled(col); col++); // advance to a free column
int colSpan = getColumnsOccupied(cv);
int rowSpan = getRowsOccupied(cv);
if (rowSpan > 1) {
int row0 = rowIndex;
int row1 = Math.min(rowIndex + rowSpan - 1, getRowCount()-1);
spans[cell] = getMultiRowSpan(row0, row1);
}
if (colSpan > 1) {
col += colSpan - 1;
}
}
}
/** {@collect.stats}
* Determines the resizability of the view along the
* given axis. A value of 0 or less is not resizable.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the resize weight
* @exception IllegalArgumentException for an invalid axis
*/
public int getResizeWeight(int axis) {
return 1;
}
/** {@collect.stats}
* Fetches the child view that represents the given position in
* the model. This is implemented to walk through the children
* looking for a range that contains the given position. In this
* view the children do not necessarily have a one to one mapping
* with the child elements.
*
* @param pos the search position >= 0
* @param a the allocation to the table on entry, and the
* allocation of the view containing the position on exit
* @return the view representing the given position, or
* null if there isn't one
*/
protected View getViewAtPosition(int pos, Rectangle a) {
int n = getViewCount();
for (int i = 0; i < n; i++) {
View v = getView(i);
int p0 = v.getStartOffset();
int p1 = v.getEndOffset();
if ((pos >= p0) && (pos < p1)) {
// it's in this view.
if (a != null) {
childAllocation(i, a);
}
return v;
}
}
if (pos == getEndOffset()) {
View v = getView(n - 1);
if (a != null) {
this.childAllocation(n - 1, a);
}
return v;
}
return null;
}
/** {@collect.stats}
* Update any cached values that come from attributes.
*/
void setPropertiesFromAttributes() {
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
painter = sheet.getBoxPainter(attr);
}
private StyleSheet.BoxPainter painter;
private AttributeSet attr;
/** {@collect.stats} columns filled by multi-column or multi-row cells */
BitSet fillColumns;
/** {@collect.stats}
* The row index within the overall grid
*/
int rowIndex;
/** {@collect.stats}
* The view index (for row index to view index conversion).
* This is set by the updateGrid method.
*/
int viewIndex;
/** {@collect.stats}
* Does this table row have cells that span multiple rows?
*/
boolean multiRowCells;
}
/** {@collect.stats}
* Default view of an html table cell. This needs to be moved
* somewhere else.
*/
class CellView extends BlockView {
/** {@collect.stats}
* Constructs a TableCell for the given element.
*
* @param elem the element that this view is responsible for
*/
public CellView(Element elem) {
super(elem, Y_AXIS);
}
/** {@collect.stats}
* Perform layout for the major axis of the box (i.e. the
* axis that it represents). The results of the layout should
* be placed in the given arrays which represent the allocations
* to the children along the major axis. This is called by the
* superclass to recalculate the positions of the child views
* when the layout might have changed.
* <p>
* This is implemented to delegate to the superclass to
* tile the children. If the target span is greater than
* was needed, the offsets are adjusted to align the children
* (i.e. position according to the html valign attribute).
*
* @param targetSpan the total span given to the view, which
* whould be used to layout the children
* @param axis the axis being layed out
* @param offsets the offsets from the origin of the view for
* each of the child views; this is a return value and is
* filled in by the implementation of this method
* @param spans the span of each child view; this is a return
* value and is filled in by the implementation of this method
* @return the offset and span for each child view in the
* offsets and spans parameters
*/
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
super.layoutMajorAxis(targetSpan, axis, offsets, spans);
// calculate usage
int used = 0;
int n = spans.length;
for (int i = 0; i < n; i++) {
used += spans[i];
}
// calculate adjustments
int adjust = 0;
if (used < targetSpan) {
// PENDING(prinz) change to use the css alignment.
String valign = (String) getElement().getAttributes().getAttribute(
HTML.Attribute.VALIGN);
if (valign == null) {
AttributeSet rowAttr = getElement().getParentElement().getAttributes();
valign = (String) rowAttr.getAttribute(HTML.Attribute.VALIGN);
}
if ((valign == null) || valign.equals("middle")) {
adjust = (targetSpan - used) / 2;
} else if (valign.equals("bottom")) {
adjust = targetSpan - used;
}
}
// make adjustments.
if (adjust != 0) {
for (int i = 0; i < n; i++) {
offsets[i] += adjust;
}
}
}
/** {@collect.stats}
* Calculate the requirements needed along the major axis.
* This is called by the superclass whenever the requirements
* need to be updated (i.e. a preferenceChanged was messaged
* through this view).
* <p>
* This is implemented to delegate to the superclass, but
* indicate the maximum size is very large (i.e. the cell
* is willing to expend to occupy the full height of the row).
*
* @param axis the axis being layed out.
* @param r the requirements to fill in. If null, a new one
* should be allocated.
*/
protected SizeRequirements calculateMajorAxisRequirements(int axis,
SizeRequirements r) {
SizeRequirements req = super.calculateMajorAxisRequirements(axis, r);
req.maximum = Integer.MAX_VALUE;
return req;
}
@Override
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
SizeRequirements rv = super.calculateMinorAxisRequirements(axis, r);
//for the cell the minimum should be derived from the child views
//the parent behaviour is to use CSS for that
int n = getViewCount();
int min = 0;
for (int i = 0; i < n; i++) {
View v = getView(i);
min = Math.max((int) v.getMinimumSpan(axis), min);
}
rv.minimum = Math.min(rv.minimum, min);
return rv;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import sun.awt.AppContext;
import java.lang.reflect.Method;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.text.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.TextUI;
import java.util.*;
import javax.accessibility.*;
import java.lang.ref.*;
/** {@collect.stats}
* The Swing JEditorPane text component supports different kinds
* of content via a plug-in mechanism called an EditorKit. Because
* HTML is a very popular format of content, some support is provided
* by default. The default support is provided by this class, which
* supports HTML version 3.2 (with some extensions), and is migrating
* toward version 4.0.
* The <applet> tag is not supported, but some support is provided
* for the <object> tag.
* <p>
* There are several goals of the HTML EditorKit provided, that have
* an effect upon the way that HTML is modeled. These
* have influenced its design in a substantial way.
* <dl>
* <p>
* <dt>
* Support editing
* <dd>
* It might seem fairly obvious that a plug-in for JEditorPane
* should provide editing support, but that fact has several
* design considerations. There are a substantial number of HTML
* documents that don't properly conform to an HTML specification.
* These must be normalized somewhat into a correct form if one
* is to edit them. Additionally, users don't like to be presented
* with an excessive amount of structure editing, so using traditional
* text editing gestures is preferred over using the HTML structure
* exactly as defined in the HTML document.
* <p>
* The modeling of HTML is provided by the class <code>HTMLDocument</code>.
* Its documention describes the details of how the HTML is modeled.
* The editing support leverages heavily off of the text package.
* <p>
* <dt>
* Extendable/Scalable
* <dd>
* To maximize the usefulness of this kit, a great deal of effort
* has gone into making it extendable. These are some of the
* features.
* <ol>
* <li>
* The parser is replacable. The default parser is the Hot Java
* parser which is DTD based. A different DTD can be used, or an
* entirely different parser can be used. To change the parser,
* reimplement the getParser method. The default parser is
* dynamically loaded when first asked for, so the class files
* will never be loaded if an alternative parser is used. The
* default parser is in a separate package called parser below
* this package.
* <li>
* The parser drives the ParserCallback, which is provided by
* HTMLDocument. To change the callback, subclass HTMLDocument
* and reimplement the createDefaultDocument method to return
* document that produces a different reader. The reader controls
* how the document is structured. Although the Document provides
* HTML support by default, there is nothing preventing support of
* non-HTML tags that result in alternative element structures.
* <li>
* The default view of the models are provided as a hierarchy of
* View implementations, so one can easily customize how a particular
* element is displayed or add capabilities for new kinds of elements
* by providing new View implementations. The default set of views
* are provided by the <code>HTMLFactory</code> class. This can
* be easily changed by subclassing or replacing the HTMLFactory
* and reimplementing the getViewFactory method to return the alternative
* factory.
* <li>
* The View implementations work primarily off of CSS attributes,
* which are kept in the views. This makes it possible to have
* multiple views mapped over the same model that appear substantially
* different. This can be especially useful for printing. For
* most HTML attributes, the HTML attributes are converted to CSS
* attributes for display. This helps make the View implementations
* more general purpose
* </ol>
* <p>
* <dt>
* Asynchronous Loading
* <dd>
* Larger documents involve a lot of parsing and take some time
* to load. By default, this kit produces documents that will be
* loaded asynchronously if loaded using <code>JEditorPane.setPage</code>.
* This is controlled by a property on the document. The method
* <a href="#createDefaultDocument">createDefaultDocument</a> can
* be overriden to change this. The batching of work is done
* by the <code>HTMLDocument.HTMLReader</code> class. The actual
* work is done by the <code>DefaultStyledDocument</code> and
* <code>AbstractDocument</code> classes in the text package.
* <p>
* <dt>
* Customization from current LAF
* <dd>
* HTML provides a well known set of features without exactly
* specifying the display characteristics. Swing has a theme
* mechanism for its look-and-feel implementations. It is desirable
* for the look-and-feel to feed display characteristics into the
* HTML views. An user with poor vision for example would want
* high contrast and larger than typical fonts.
* <p>
* The support for this is provided by the <code>StyleSheet</code>
* class. The presentation of the HTML can be heavily influenced
* by the setting of the StyleSheet property on the EditorKit.
* <p>
* <dt>
* Not lossy
* <dd>
* An EditorKit has the ability to be read and save documents.
* It is generally the most pleasing to users if there is no loss
* of data between the two operation. The policy of the HTMLEditorKit
* will be to store things not recognized or not necessarily visible
* so they can be subsequently written out. The model of the HTML document
* should therefore contain all information discovered while reading the
* document. This is constrained in some ways by the need to support
* editing (i.e. incorrect documents sometimes must be normalized).
* The guiding principle is that information shouldn't be lost, but
* some might be synthesized to produce a more correct model or it might
* be rearranged.
* </dl>
*
* @author Timothy Prinzing
*/
public class HTMLEditorKit extends StyledEditorKit implements Accessible {
private JEditorPane theEditor;
/** {@collect.stats}
* Constructs an HTMLEditorKit, creates a StyleContext,
* and loads the style sheet.
*/
public HTMLEditorKit() {
}
/** {@collect.stats}
* Get the MIME type of the data that this
* kit represents support for. This kit supports
* the type <code>text/html</code>.
*
* @return the type
*/
public String getContentType() {
return "text/html";
}
/** {@collect.stats}
* Fetch a factory that is suitable for producing
* views of any models that are produced by this
* kit.
*
* @return the factory
*/
public ViewFactory getViewFactory() {
return defaultFactory;
}
/** {@collect.stats}
* Create an uninitialized text storage model
* that is appropriate for this type of editor.
*
* @return the model
*/
public Document createDefaultDocument() {
StyleSheet styles = getStyleSheet();
StyleSheet ss = new StyleSheet();
ss.addStyleSheet(styles);
HTMLDocument doc = new HTMLDocument(ss);
doc.setParser(getParser());
doc.setAsynchronousLoadPriority(4);
doc.setTokenThreshold(100);
return doc;
}
/** {@collect.stats}
* Try to get an HTML parser from the document. If no parser is set for
* the document, return the editor kit's default parser. It is an error
* if no parser could be obtained from the editor kit.
*/
private Parser ensureParser(HTMLDocument doc) throws IOException {
Parser p = doc.getParser();
if (p == null) {
p = getParser();
}
if (p == null) {
throw new IOException("Can't load parser");
}
return p;
}
/** {@collect.stats}
* Inserts content from the given stream. If <code>doc</code> is
* an instance of HTMLDocument, this will read
* HTML 3.2 text. Inserting HTML into a non-empty document must be inside
* the body Element, if you do not insert into the body an exception will
* be thrown. When inserting into a non-empty document all tags outside
* of the body (head, title) will be dropped.
*
* @param in the stream to read from
* @param doc the destination for the insertion
* @param pos the location in the document to place the
* content
* @exception IOException on any I/O error
* @exception BadLocationException if pos represents an invalid
* location within the document
* @exception RuntimeException (will eventually be a BadLocationException)
* if pos is invalid
*/
public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException {
if (doc instanceof HTMLDocument) {
HTMLDocument hdoc = (HTMLDocument) doc;
if (pos > doc.getLength()) {
throw new BadLocationException("Invalid location", pos);
}
Parser p = ensureParser(hdoc);
ParserCallback receiver = hdoc.getReader(pos);
Boolean ignoreCharset = (Boolean)doc.getProperty("IgnoreCharsetDirective");
p.parse(in, receiver, (ignoreCharset == null) ? false : ignoreCharset.booleanValue());
receiver.flush();
} else {
super.read(in, doc, pos);
}
}
/** {@collect.stats}
* Inserts HTML into an existing document.
*
* @param doc the document to insert into
* @param offset the offset to insert HTML at
* @param popDepth the number of ElementSpec.EndTagTypes to generate before
* inserting
* @param pushDepth the number of ElementSpec.StartTagTypes with a direction
* of ElementSpec.JoinNextDirection that should be generated
* before inserting, but after the end tags have been generated
* @param insertTag the first tag to start inserting into document
* @exception RuntimeException (will eventually be a BadLocationException)
* if pos is invalid
*/
public void insertHTML(HTMLDocument doc, int offset, String html,
int popDepth, int pushDepth,
HTML.Tag insertTag) throws
BadLocationException, IOException {
if (offset > doc.getLength()) {
throw new BadLocationException("Invalid location", offset);
}
Parser p = ensureParser(doc);
ParserCallback receiver = doc.getReader(offset, popDepth, pushDepth,
insertTag);
Boolean ignoreCharset = (Boolean)doc.getProperty
("IgnoreCharsetDirective");
p.parse(new StringReader(html), receiver, (ignoreCharset == null) ?
false : ignoreCharset.booleanValue());
receiver.flush();
}
/** {@collect.stats}
* Write content from a document to the given stream
* in a format appropriate for this kind of content handler.
*
* @param out the stream to write to
* @param doc the source for the write
* @param pos the location in the document to fetch the
* content
* @param len the amount to write out
* @exception IOException on any I/O error
* @exception BadLocationException if pos represents an invalid
* location within the document
*/
public void write(Writer out, Document doc, int pos, int len)
throws IOException, BadLocationException {
if (doc instanceof HTMLDocument) {
HTMLWriter w = new HTMLWriter(out, (HTMLDocument)doc, pos, len);
w.write();
} else if (doc instanceof StyledDocument) {
MinimalHTMLWriter w = new MinimalHTMLWriter(out, (StyledDocument)doc, pos, len);
w.write();
} else {
super.write(out, doc, pos, len);
}
}
/** {@collect.stats}
* Called when the kit is being installed into the
* a JEditorPane.
*
* @param c the JEditorPane
*/
public void install(JEditorPane c) {
c.addMouseListener(linkHandler);
c.addMouseMotionListener(linkHandler);
c.addCaretListener(nextLinkAction);
super.install(c);
theEditor = c;
}
/** {@collect.stats}
* Called when the kit is being removed from the
* JEditorPane. This is used to unregister any
* listeners that were attached.
*
* @param c the JEditorPane
*/
public void deinstall(JEditorPane c) {
c.removeMouseListener(linkHandler);
c.removeMouseMotionListener(linkHandler);
c.removeCaretListener(nextLinkAction);
super.deinstall(c);
theEditor = null;
}
/** {@collect.stats}
* Default Cascading Style Sheet file that sets
* up the tag views.
*/
public static final String DEFAULT_CSS = "default.css";
/** {@collect.stats}
* Set the set of styles to be used to render the various
* HTML elements. These styles are specified in terms of
* CSS specifications. Each document produced by the kit
* will have a copy of the sheet which it can add the
* document specific styles to. By default, the StyleSheet
* specified is shared by all HTMLEditorKit instances.
* This should be reimplemented to provide a finer granularity
* if desired.
*/
public void setStyleSheet(StyleSheet s) {
if (s == null) {
AppContext.getAppContext().remove(DEFAULT_STYLES_KEY);
} else {
AppContext.getAppContext().put(DEFAULT_STYLES_KEY, s);
}
}
/** {@collect.stats}
* Get the set of styles currently being used to render the
* HTML elements. By default the resource specified by
* DEFAULT_CSS gets loaded, and is shared by all HTMLEditorKit
* instances.
*/
public StyleSheet getStyleSheet() {
AppContext appContext = AppContext.getAppContext();
StyleSheet defaultStyles = (StyleSheet) appContext.get(DEFAULT_STYLES_KEY);
if (defaultStyles == null) {
defaultStyles = new StyleSheet();
appContext.put(DEFAULT_STYLES_KEY, defaultStyles);
try {
InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS);
Reader r = new BufferedReader(
new InputStreamReader(is, "ISO-8859-1"));
defaultStyles.loadRules(r, null);
r.close();
} catch (Throwable e) {
// on error we simply have no styles... the html
// will look mighty wrong but still function.
}
}
return defaultStyles;
}
/** {@collect.stats}
* Fetch a resource relative to the HTMLEditorKit classfile.
* If this is called on 1.2 the loading will occur under the
* protection of a doPrivileged call to allow the HTMLEditorKit
* to function when used in an applet.
*
* @param name the name of the resource, relative to the
* HTMLEditorKit class
* @return a stream representing the resource
*/
static InputStream getResourceAsStream(String name) {
try {
return ResourceLoader.getResourceAsStream(name);
} catch (Throwable e) {
// If the class doesn't exist or we have some other
// problem we just try to call getResourceAsStream directly.
return HTMLEditorKit.class.getResourceAsStream(name);
}
}
/** {@collect.stats}
* Fetches the command list for the editor. This is
* the list of commands supported by the superclass
* augmented by the collection of commands defined
* locally for style operations.
*
* @return the command list
*/
public Action[] getActions() {
return TextAction.augmentList(super.getActions(), this.defaultActions);
}
/** {@collect.stats}
* Copies the key/values in <code>element</code>s AttributeSet into
* <code>set</code>. This does not copy component, icon, or element
* names attributes. Subclasses may wish to refine what is and what
* isn't copied here. But be sure to first remove all the attributes that
* are in <code>set</code>.<p>
* This is called anytime the caret moves over a different location.
*
*/
protected void createInputAttributes(Element element,
MutableAttributeSet set) {
set.removeAttributes(set);
set.addAttributes(element.getAttributes());
set.removeAttribute(StyleConstants.ComposedTextAttribute);
Object o = set.getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag tag = (HTML.Tag)o;
// PENDING: we need a better way to express what shouldn't be
// copied when editing...
if(tag == HTML.Tag.IMG) {
// Remove the related image attributes, src, width, height
set.removeAttribute(HTML.Attribute.SRC);
set.removeAttribute(HTML.Attribute.HEIGHT);
set.removeAttribute(HTML.Attribute.WIDTH);
set.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
}
else if (tag == HTML.Tag.HR || tag == HTML.Tag.BR) {
// Don't copy HRs or BRs either.
set.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
}
else if (tag == HTML.Tag.COMMENT) {
// Don't copy COMMENTs either
set.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
set.removeAttribute(HTML.Attribute.COMMENT);
}
else if (tag == HTML.Tag.INPUT) {
// or INPUT either
set.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
set.removeAttribute(HTML.Tag.INPUT);
}
else if (tag instanceof HTML.UnknownTag) {
// Don't copy unknowns either:(
set.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.CONTENT);
set.removeAttribute(HTML.Attribute.ENDTAG);
}
}
}
/** {@collect.stats}
* Gets the input attributes used for the styled
* editing actions.
*
* @return the attribute set
*/
public MutableAttributeSet getInputAttributes() {
if (input == null) {
input = getStyleSheet().addStyle(null, null);
}
return input;
}
/** {@collect.stats}
* Sets the default cursor.
*
* @since 1.3
*/
public void setDefaultCursor(Cursor cursor) {
defaultCursor = cursor;
}
/** {@collect.stats}
* Returns the default cursor.
*
* @since 1.3
*/
public Cursor getDefaultCursor() {
return defaultCursor;
}
/** {@collect.stats}
* Sets the cursor to use over links.
*
* @since 1.3
*/
public void setLinkCursor(Cursor cursor) {
linkCursor = cursor;
}
/** {@collect.stats}
* Returns the cursor to use over hyper links.
* @since 1.3
*/
public Cursor getLinkCursor() {
return linkCursor;
}
/** {@collect.stats}
* Indicates whether an html form submission is processed automatically
* or only <code>FormSubmitEvent</code> is fired.
*
* @return true if html form submission is processed automatically,
* false otherwise.
*
* @see #setAutoFormSubmission
* @since 1.5
*/
public boolean isAutoFormSubmission() {
return isAutoFormSubmission;
}
/** {@collect.stats}
* Specifies if an html form submission is processed
* automatically or only <code>FormSubmitEvent</code> is fired.
* By default it is set to true.
*
* @see #isAutoFormSubmission
* @see FormSubmitEvent
* @since 1.5
*/
public void setAutoFormSubmission(boolean isAuto) {
isAutoFormSubmission = isAuto;
}
/** {@collect.stats}
* Creates a copy of the editor kit.
*
* @return the copy
*/
public Object clone() {
HTMLEditorKit o = (HTMLEditorKit)super.clone();
if (o != null) {
o.input = null;
o.linkHandler = new LinkController();
}
return o;
}
/** {@collect.stats}
* Fetch the parser to use for reading HTML streams.
* This can be reimplemented to provide a different
* parser. The default implementation is loaded dynamically
* to avoid the overhead of loading the default parser if
* it's not used. The default parser is the HotJava parser
* using an HTML 3.2 DTD.
*/
protected Parser getParser() {
if (defaultParser == null) {
try {
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
defaultParser = (Parser) c.newInstance();
} catch (Throwable e) {
}
}
return defaultParser;
}
// ----- Accessibility support -----
private AccessibleContext accessibleContext;
/** {@collect.stats}
* returns the AccessibleContext associated with this editor kit
*
* @return the AccessibleContext associated with this editor kit
* @since 1.4
*/
public AccessibleContext getAccessibleContext() {
if (theEditor == null) {
return null;
}
if (accessibleContext == null) {
AccessibleHTML a = new AccessibleHTML(theEditor);
accessibleContext = a.getAccessibleContext();
}
return accessibleContext;
}
// --- variables ------------------------------------------
private static final Cursor MoveCursor = Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR);
private static final Cursor DefaultCursor = Cursor.getPredefinedCursor
(Cursor.DEFAULT_CURSOR);
/** {@collect.stats} Shared factory for creating HTML Views. */
private static final ViewFactory defaultFactory = new HTMLFactory();
MutableAttributeSet input;
private static final Object DEFAULT_STYLES_KEY = new Object();
private LinkController linkHandler = new LinkController();
private static Parser defaultParser = null;
private Cursor defaultCursor = DefaultCursor;
private Cursor linkCursor = MoveCursor;
private boolean isAutoFormSubmission = true;
/** {@collect.stats}
* Class to watch the associated component and fire
* hyperlink events on it when appropriate.
*/
public static class LinkController extends MouseAdapter implements MouseMotionListener, Serializable {
private Element curElem = null;
/** {@collect.stats}
* If true, the current element (curElem) represents an image.
*/
private boolean curElemImage = false;
private String href = null;
/** {@collect.stats} This is used by viewToModel to avoid allocing a new array each
* time. */
private transient Position.Bias[] bias = new Position.Bias[1];
/** {@collect.stats}
* Current offset.
*/
private int curOffset;
/** {@collect.stats}
* Called for a mouse click event.
* If the component is read-only (ie a browser) then
* the clicked event is used to drive an attempt to
* follow the reference specified by a link.
*
* @param e the mouse event
* @see MouseListener#mouseClicked
*/
public void mouseClicked(MouseEvent e) {
JEditorPane editor = (JEditorPane) e.getSource();
if (! editor.isEditable() && editor.isEnabled() &&
SwingUtilities.isLeftMouseButton(e)) {
Point pt = new Point(e.getX(), e.getY());
int pos = editor.viewToModel(pt);
if (pos >= 0) {
activateLink(pos, editor, e.getX(), e.getY());
}
}
}
// ignore the drags
public void mouseDragged(MouseEvent e) {
}
// track the moving of the mouse.
public void mouseMoved(MouseEvent e) {
JEditorPane editor = (JEditorPane) e.getSource();
if (!editor.isEnabled()) {
return;
}
HTMLEditorKit kit = (HTMLEditorKit)editor.getEditorKit();
boolean adjustCursor = true;
Cursor newCursor = kit.getDefaultCursor();
if (!editor.isEditable()) {
Point pt = new Point(e.getX(), e.getY());
int pos = editor.getUI().viewToModel(editor, pt, bias);
if (bias[0] == Position.Bias.Backward && pos > 0) {
pos--;
}
if (pos >= 0 &&(editor.getDocument() instanceof HTMLDocument)){
HTMLDocument hdoc = (HTMLDocument)editor.getDocument();
Element elem = hdoc.getCharacterElement(pos);
if (!doesElementContainLocation(editor, elem, pos,
e.getX(), e.getY())) {
elem = null;
}
if (curElem != elem || curElemImage) {
Element lastElem = curElem;
curElem = elem;
String href = null;
curElemImage = false;
if (elem != null) {
AttributeSet a = elem.getAttributes();
AttributeSet anchor = (AttributeSet)a.
getAttribute(HTML.Tag.A);
if (anchor == null) {
curElemImage = (a.getAttribute(StyleConstants.
NameAttribute) == HTML.Tag.IMG);
if (curElemImage) {
href = getMapHREF(editor, hdoc, elem, a,
pos, e.getX(), e.getY());
}
}
else {
href = (String)anchor.getAttribute
(HTML.Attribute.HREF);
}
}
if (href != this.href) {
// reference changed, fire event(s)
fireEvents(editor, hdoc, href, lastElem);
this.href = href;
if (href != null) {
newCursor = kit.getLinkCursor();
}
}
else {
adjustCursor = false;
}
}
else {
adjustCursor = false;
}
curOffset = pos;
}
}
if (adjustCursor && editor.getCursor() != newCursor) {
editor.setCursor(newCursor);
}
}
/** {@collect.stats}
* Returns a string anchor if the passed in element has a
* USEMAP that contains the passed in location.
*/
private String getMapHREF(JEditorPane html, HTMLDocument hdoc,
Element elem, AttributeSet attr, int offset,
int x, int y) {
Object useMap = attr.getAttribute(HTML.Attribute.USEMAP);
if (useMap != null && (useMap instanceof String)) {
Map m = hdoc.getMap((String)useMap);
if (m != null && offset < hdoc.getLength()) {
Rectangle bounds;
TextUI ui = html.getUI();
try {
Shape lBounds = ui.modelToView(html, offset,
Position.Bias.Forward);
Shape rBounds = ui.modelToView(html, offset + 1,
Position.Bias.Backward);
bounds = lBounds.getBounds();
bounds.add((rBounds instanceof Rectangle) ?
(Rectangle)rBounds : rBounds.getBounds());
} catch (BadLocationException ble) {
bounds = null;
}
if (bounds != null) {
AttributeSet area = m.getArea(x - bounds.x,
y - bounds.y,
bounds.width,
bounds.height);
if (area != null) {
return (String)area.getAttribute(HTML.Attribute.
HREF);
}
}
}
}
return null;
}
/** {@collect.stats}
* Returns true if the View representing <code>e</code> contains
* the location <code>x</code>, <code>y</code>. <code>offset</code>
* gives the offset into the Document to check for.
*/
private boolean doesElementContainLocation(JEditorPane editor,
Element e, int offset,
int x, int y) {
if (e != null && offset > 0 && e.getStartOffset() == offset) {
try {
TextUI ui = editor.getUI();
Shape s1 = ui.modelToView(editor, offset,
Position.Bias.Forward);
if (s1 == null) {
return false;
}
Rectangle r1 = (s1 instanceof Rectangle) ? (Rectangle)s1 :
s1.getBounds();
Shape s2 = ui.modelToView(editor, e.getEndOffset(),
Position.Bias.Backward);
if (s2 != null) {
Rectangle r2 = (s2 instanceof Rectangle) ? (Rectangle)s2 :
s2.getBounds();
r1.add(r2);
}
return r1.contains(x, y);
} catch (BadLocationException ble) {
}
}
return true;
}
/** {@collect.stats}
* Calls linkActivated on the associated JEditorPane
* if the given position represents a link.<p>This is implemented
* to forward to the method with the same name, but with the following
* args both == -1.
*
* @param pos the position
* @param editor the editor pane
*/
protected void activateLink(int pos, JEditorPane editor) {
activateLink(pos, editor, -1, -1);
}
/** {@collect.stats}
* Calls linkActivated on the associated JEditorPane
* if the given position represents a link. If this was the result
* of a mouse click, <code>x</code> and
* <code>y</code> will give the location of the mouse, otherwise
* they will be < 0.
*
* @param pos the position
* @param html the editor pane
*/
void activateLink(int pos, JEditorPane html, int x, int y) {
Document doc = html.getDocument();
if (doc instanceof HTMLDocument) {
HTMLDocument hdoc = (HTMLDocument) doc;
Element e = hdoc.getCharacterElement(pos);
AttributeSet a = e.getAttributes();
AttributeSet anchor = (AttributeSet)a.getAttribute(HTML.Tag.A);
HyperlinkEvent linkEvent = null;
String description;
if (anchor == null) {
href = getMapHREF(html, hdoc, e, a, pos, x, y);
}
else {
href = (String)anchor.getAttribute(HTML.Attribute.HREF);
}
if (href != null) {
linkEvent = createHyperlinkEvent(html, hdoc, href, anchor,
e);
}
if (linkEvent != null) {
html.fireHyperlinkUpdate(linkEvent);
}
}
}
/** {@collect.stats}
* Creates and returns a new instance of HyperlinkEvent. If
* <code>hdoc</code> is a frame document a HTMLFrameHyperlinkEvent
* will be created.
*/
HyperlinkEvent createHyperlinkEvent(JEditorPane html,
HTMLDocument hdoc, String href,
AttributeSet anchor,
Element element) {
URL u;
try {
URL base = hdoc.getBase();
u = new URL(base, href);
// Following is a workaround for 1.2, in which
// new URL("file://...", "#...") causes the filename to
// be lost.
if (href != null && "file".equals(u.getProtocol()) &&
href.startsWith("#")) {
String baseFile = base.getFile();
String newFile = u.getFile();
if (baseFile != null && newFile != null &&
!newFile.startsWith(baseFile)) {
u = new URL(base, baseFile + href);
}
}
} catch (MalformedURLException m) {
u = null;
}
HyperlinkEvent linkEvent = null;
if (!hdoc.isFrameDocument()) {
linkEvent = new HyperlinkEvent(html, HyperlinkEvent.EventType.
ACTIVATED, u, href, element);
} else {
String target = (anchor != null) ?
(String)anchor.getAttribute(HTML.Attribute.TARGET) : null;
if ((target == null) || (target.equals(""))) {
target = hdoc.getBaseTarget();
}
if ((target == null) || (target.equals(""))) {
target = "_self";
}
linkEvent = new HTMLFrameHyperlinkEvent(html, HyperlinkEvent.
EventType.ACTIVATED, u, href, element, target);
}
return linkEvent;
}
void fireEvents(JEditorPane editor, HTMLDocument doc, String href,
Element lastElem) {
if (this.href != null) {
// fire an exited event on the old link
URL u;
try {
u = new URL(doc.getBase(), this.href);
} catch (MalformedURLException m) {
u = null;
}
HyperlinkEvent exit = new HyperlinkEvent(editor,
HyperlinkEvent.EventType.EXITED, u, this.href,
lastElem);
editor.fireHyperlinkUpdate(exit);
}
if (href != null) {
// fire an entered event on the new link
URL u;
try {
u = new URL(doc.getBase(), href);
} catch (MalformedURLException m) {
u = null;
}
HyperlinkEvent entered = new HyperlinkEvent(editor,
HyperlinkEvent.EventType.ENTERED,
u, href, curElem);
editor.fireHyperlinkUpdate(entered);
}
}
}
/** {@collect.stats}
* Interface to be supported by the parser. This enables
* providing a different parser while reusing some of the
* implementation provided by this editor kit.
*/
public static abstract class Parser {
/** {@collect.stats}
* Parse the given stream and drive the given callback
* with the results of the parse. This method should
* be implemented to be thread-safe.
*/
public abstract void parse(Reader r, ParserCallback cb, boolean ignoreCharSet) throws IOException;
}
/** {@collect.stats}
* The result of parsing drives these callback methods.
* The open and close actions should be balanced. The
* <code>flush</code> method will be the last method
* called, to give the receiver a chance to flush any
* pending data into the document.
* <p>Refer to DocumentParser, the default parser used, for further
* information on the contents of the AttributeSets, the positions, and
* other info.
*
* @see javax.swing.text.html.parser.DocumentParser
*/
public static class ParserCallback {
/** {@collect.stats}
* This is passed as an attribute in the attributeset to indicate
* the element is implied eg, the string '<>foo<\t>'
* contains an implied html element and an implied body element.
*
* @since 1.3
*/
public static final Object IMPLIED = "_implied_";
public void flush() throws BadLocationException {
}
public void handleText(char[] data, int pos) {
}
public void handleComment(char[] data, int pos) {
}
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
}
public void handleEndTag(HTML.Tag t, int pos) {
}
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
}
public void handleError(String errorMsg, int pos){
}
/** {@collect.stats}
* This is invoked after the stream has been parsed, but before
* <code>flush</code>. <code>eol</code> will be one of \n, \r
* or \r\n, which ever is encountered the most in parsing the
* stream.
*
* @since 1.3
*/
public void handleEndOfLineString(String eol) {
}
}
/** {@collect.stats}
* A factory to build views for HTML. The following
* table describes what this factory will build by
* default.
*
* <table summary="Describes the tag and view created by this factory by default">
* <tr>
* <th align=left>Tag<th align=left>View created
* </tr><tr>
* <td>HTML.Tag.CONTENT<td>InlineView
* </tr><tr>
* <td>HTML.Tag.IMPLIED<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.P<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H1<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H2<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H3<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H4<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H5<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.H6<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.DT<td>javax.swing.text.html.ParagraphView
* </tr><tr>
* <td>HTML.Tag.MENU<td>ListView
* </tr><tr>
* <td>HTML.Tag.DIR<td>ListView
* </tr><tr>
* <td>HTML.Tag.UL<td>ListView
* </tr><tr>
* <td>HTML.Tag.OL<td>ListView
* </tr><tr>
* <td>HTML.Tag.LI<td>BlockView
* </tr><tr>
* <td>HTML.Tag.DL<td>BlockView
* </tr><tr>
* <td>HTML.Tag.DD<td>BlockView
* </tr><tr>
* <td>HTML.Tag.BODY<td>BlockView
* </tr><tr>
* <td>HTML.Tag.HTML<td>BlockView
* </tr><tr>
* <td>HTML.Tag.CENTER<td>BlockView
* </tr><tr>
* <td>HTML.Tag.DIV<td>BlockView
* </tr><tr>
* <td>HTML.Tag.BLOCKQUOTE<td>BlockView
* </tr><tr>
* <td>HTML.Tag.PRE<td>BlockView
* </tr><tr>
* <td>HTML.Tag.BLOCKQUOTE<td>BlockView
* </tr><tr>
* <td>HTML.Tag.PRE<td>BlockView
* </tr><tr>
* <td>HTML.Tag.IMG<td>ImageView
* </tr><tr>
* <td>HTML.Tag.HR<td>HRuleView
* </tr><tr>
* <td>HTML.Tag.BR<td>BRView
* </tr><tr>
* <td>HTML.Tag.TABLE<td>javax.swing.text.html.TableView
* </tr><tr>
* <td>HTML.Tag.INPUT<td>FormView
* </tr><tr>
* <td>HTML.Tag.SELECT<td>FormView
* </tr><tr>
* <td>HTML.Tag.TEXTAREA<td>FormView
* </tr><tr>
* <td>HTML.Tag.OBJECT<td>ObjectView
* </tr><tr>
* <td>HTML.Tag.FRAMESET<td>FrameSetView
* </tr><tr>
* <td>HTML.Tag.FRAME<td>FrameView
* </tr>
* </table>
*/
public static class HTMLFactory implements ViewFactory {
/** {@collect.stats}
* Creates a view from an element.
*
* @param elem the element
* @return the view
*/
public View create(Element elem) {
AttributeSet attrs = elem.getAttributes();
Object elementName =
attrs.getAttribute(AbstractDocument.ElementNameAttribute);
Object o = (elementName != null) ?
null : attrs.getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag) o;
if (kind == HTML.Tag.CONTENT) {
return new InlineView(elem);
} else if (kind == HTML.Tag.IMPLIED) {
String ws = (String) elem.getAttributes().getAttribute(
CSS.Attribute.WHITE_SPACE);
if ((ws != null) && ws.equals("pre")) {
return new LineView(elem);
}
return new javax.swing.text.html.ParagraphView(elem);
} else if ((kind == HTML.Tag.P) ||
(kind == HTML.Tag.H1) ||
(kind == HTML.Tag.H2) ||
(kind == HTML.Tag.H3) ||
(kind == HTML.Tag.H4) ||
(kind == HTML.Tag.H5) ||
(kind == HTML.Tag.H6) ||
(kind == HTML.Tag.DT)) {
// paragraph
return new javax.swing.text.html.ParagraphView(elem);
} else if ((kind == HTML.Tag.MENU) ||
(kind == HTML.Tag.DIR) ||
(kind == HTML.Tag.UL) ||
(kind == HTML.Tag.OL)) {
return new ListView(elem);
} else if (kind == HTML.Tag.BODY) {
return new BodyBlockView(elem);
} else if (kind == HTML.Tag.HTML) {
return new BlockView(elem, View.Y_AXIS);
} else if ((kind == HTML.Tag.LI) ||
(kind == HTML.Tag.CENTER) ||
(kind == HTML.Tag.DL) ||
(kind == HTML.Tag.DD) ||
(kind == HTML.Tag.DIV) ||
(kind == HTML.Tag.BLOCKQUOTE) ||
(kind == HTML.Tag.PRE) ||
(kind == HTML.Tag.FORM)) {
// vertical box
return new BlockView(elem, View.Y_AXIS);
} else if (kind == HTML.Tag.NOFRAMES) {
return new NoFramesView(elem, View.Y_AXIS);
} else if (kind==HTML.Tag.IMG) {
return new ImageView(elem);
} else if (kind == HTML.Tag.ISINDEX) {
return new IsindexView(elem);
} else if (kind == HTML.Tag.HR) {
return new HRuleView(elem);
} else if (kind == HTML.Tag.BR) {
return new BRView(elem);
} else if (kind == HTML.Tag.TABLE) {
return new javax.swing.text.html.TableView(elem);
} else if ((kind == HTML.Tag.INPUT) ||
(kind == HTML.Tag.SELECT) ||
(kind == HTML.Tag.TEXTAREA)) {
return new FormView(elem);
} else if (kind == HTML.Tag.OBJECT) {
return new ObjectView(elem);
} else if (kind == HTML.Tag.FRAMESET) {
if (elem.getAttributes().isDefined(HTML.Attribute.ROWS)) {
return new FrameSetView(elem, View.Y_AXIS);
} else if (elem.getAttributes().isDefined(HTML.Attribute.COLS)) {
return new FrameSetView(elem, View.X_AXIS);
}
throw new RuntimeException("Can't build a" + kind + ", " + elem + ":" +
"no ROWS or COLS defined.");
} else if (kind == HTML.Tag.FRAME) {
return new FrameView(elem);
} else if (kind instanceof HTML.UnknownTag) {
return new HiddenTagView(elem);
} else if (kind == HTML.Tag.COMMENT) {
return new CommentView(elem);
} else if (kind == HTML.Tag.HEAD) {
// Make the head never visible, and never load its
// children. For Cursor positioning,
// getNextVisualPositionFrom is overriden to always return
// the end offset of the element.
return new BlockView(elem, View.X_AXIS) {
public float getPreferredSpan(int axis) {
return 0;
}
public float getMinimumSpan(int axis) {
return 0;
}
public float getMaximumSpan(int axis) {
return 0;
}
protected void loadChildren(ViewFactory f) {
}
public Shape modelToView(int pos, Shape a,
Position.Bias b) throws BadLocationException {
return a;
}
public int getNextVisualPositionFrom(int pos,
Position.Bias b, Shape a,
int direction, Position.Bias[] biasRet) {
return getElement().getEndOffset();
}
};
} else if ((kind == HTML.Tag.TITLE) ||
(kind == HTML.Tag.META) ||
(kind == HTML.Tag.LINK) ||
(kind == HTML.Tag.STYLE) ||
(kind == HTML.Tag.SCRIPT) ||
(kind == HTML.Tag.AREA) ||
(kind == HTML.Tag.MAP) ||
(kind == HTML.Tag.PARAM) ||
(kind == HTML.Tag.APPLET)) {
return new HiddenTagView(elem);
}
}
// If we get here, it's either an element we don't know about
// or something from StyledDocument that doesn't have a mapping to HTML.
String nm = (elementName != null) ? (String)elementName :
elem.getName();
if (nm != null) {
if (nm.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
} else if (nm.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (nm.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
} else if (nm.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (nm.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
static class BodyBlockView extends BlockView implements ComponentListener {
public BodyBlockView(Element elem) {
super(elem,View.Y_AXIS);
}
// reimplement major axis requirements to indicate that the
// block is flexible for the body element... so that it can
// be stretched to fill the background properly.
protected SizeRequirements calculateMajorAxisRequirements(int axis, SizeRequirements r) {
r = super.calculateMajorAxisRequirements(axis, r);
r.maximum = Integer.MAX_VALUE;
return r;
}
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
Container container = getContainer();
Container parentContainer;
if (container != null
&& (container instanceof javax.swing.JEditorPane)
&& (parentContainer = container.getParent()) != null
&& (parentContainer instanceof javax.swing.JViewport)) {
JViewport viewPort = (JViewport)parentContainer;
Object cachedObject;
if (cachedViewPort != null) {
if ((cachedObject = cachedViewPort.get()) != null) {
if (cachedObject != viewPort) {
((JComponent)cachedObject).removeComponentListener(this);
}
} else {
cachedViewPort = null;
}
}
if (cachedViewPort == null) {
viewPort.addComponentListener(this);
cachedViewPort = new WeakReference(viewPort);
}
componentVisibleWidth = viewPort.getExtentSize().width;
if (componentVisibleWidth > 0) {
Insets insets = container.getInsets();
viewVisibleWidth = componentVisibleWidth - insets.left - getLeftInset();
//try to use viewVisibleWidth if it is smaller than targetSpan
targetSpan = Math.min(targetSpan, viewVisibleWidth);
}
} else {
if (cachedViewPort != null) {
Object cachedObject;
if ((cachedObject = cachedViewPort.get()) != null) {
((JComponent)cachedObject).removeComponentListener(this);
}
cachedViewPort = null;
}
}
super.layoutMinorAxis(targetSpan, axis, offsets, spans);
}
public void setParent(View parent) {
//if parent == null unregister component listener
if (parent == null) {
if (cachedViewPort != null) {
Object cachedObject;
if ((cachedObject = cachedViewPort.get()) != null) {
((JComponent)cachedObject).removeComponentListener(this);
}
cachedViewPort = null;
}
}
super.setParent(parent);
}
public void componentResized(ComponentEvent e) {
if ( !(e.getSource() instanceof JViewport) ) {
return;
}
JViewport viewPort = (JViewport)e.getSource();
if (componentVisibleWidth != viewPort.getExtentSize().width) {
Document doc = getDocument();
if (doc instanceof AbstractDocument) {
AbstractDocument document = (AbstractDocument)getDocument();
document.readLock();
try {
layoutChanged(X_AXIS);
preferenceChanged(null, true, true);
} finally {
document.readUnlock();
}
}
}
}
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
/*
* we keep weak reference to viewPort if and only if BodyBoxView is listening for ComponentEvents
* only in that case cachedViewPort is not equal to null.
* we need to keep this reference in order to remove BodyBoxView from viewPort listeners.
*
*/
private Reference cachedViewPort = null;
private boolean isListening = false;
private int viewVisibleWidth = Integer.MAX_VALUE;
private int componentVisibleWidth = Integer.MAX_VALUE;
}
}
// --- Action implementations ------------------------------
/** {@collect.stats} The bold action identifier
*/
public static final String BOLD_ACTION = "html-bold-action";
/** {@collect.stats} The italic action identifier
*/
public static final String ITALIC_ACTION = "html-italic-action";
/** {@collect.stats} The paragraph left indent action identifier
*/
public static final String PARA_INDENT_LEFT = "html-para-indent-left";
/** {@collect.stats} The paragraph right indent action identifier
*/
public static final String PARA_INDENT_RIGHT = "html-para-indent-right";
/** {@collect.stats} The font size increase to next value action identifier
*/
public static final String FONT_CHANGE_BIGGER = "html-font-bigger";
/** {@collect.stats} The font size decrease to next value action identifier
*/
public static final String FONT_CHANGE_SMALLER = "html-font-smaller";
/** {@collect.stats} The Color choice action identifier
The color is passed as an argument
*/
public static final String COLOR_ACTION = "html-color-action";
/** {@collect.stats} The logical style choice action identifier
The logical style is passed in as an argument
*/
public static final String LOGICAL_STYLE_ACTION = "html-logical-style-action";
/** {@collect.stats}
* Align images at the top.
*/
public static final String IMG_ALIGN_TOP = "html-image-align-top";
/** {@collect.stats}
* Align images in the middle.
*/
public static final String IMG_ALIGN_MIDDLE = "html-image-align-middle";
/** {@collect.stats}
* Align images at the bottom.
*/
public static final String IMG_ALIGN_BOTTOM = "html-image-align-bottom";
/** {@collect.stats}
* Align images at the border.
*/
public static final String IMG_BORDER = "html-image-border";
/** {@collect.stats} HTML used when inserting tables. */
private static final String INSERT_TABLE_HTML = "<table border=1><tr><td></td></tr></table>";
/** {@collect.stats} HTML used when inserting unordered lists. */
private static final String INSERT_UL_HTML = "<ul><li></li></ul>";
/** {@collect.stats} HTML used when inserting ordered lists. */
private static final String INSERT_OL_HTML = "<ol><li></li></ol>";
/** {@collect.stats} HTML used when inserting hr. */
private static final String INSERT_HR_HTML = "<hr>";
/** {@collect.stats} HTML used when inserting pre. */
private static final String INSERT_PRE_HTML = "<pre></pre>";
private static final NavigateLinkAction nextLinkAction =
new NavigateLinkAction("next-link-action");
private static final NavigateLinkAction previousLinkAction =
new NavigateLinkAction("previous-link-action");
private static final ActivateLinkAction activateLinkAction =
new ActivateLinkAction("activate-link-action");
private static final Action[] defaultActions = {
new InsertHTMLTextAction("InsertTable", INSERT_TABLE_HTML,
HTML.Tag.BODY, HTML.Tag.TABLE),
new InsertHTMLTextAction("InsertTableRow", INSERT_TABLE_HTML,
HTML.Tag.TABLE, HTML.Tag.TR,
HTML.Tag.BODY, HTML.Tag.TABLE),
new InsertHTMLTextAction("InsertTableDataCell", INSERT_TABLE_HTML,
HTML.Tag.TR, HTML.Tag.TD,
HTML.Tag.BODY, HTML.Tag.TABLE),
new InsertHTMLTextAction("InsertUnorderedList", INSERT_UL_HTML,
HTML.Tag.BODY, HTML.Tag.UL),
new InsertHTMLTextAction("InsertUnorderedListItem", INSERT_UL_HTML,
HTML.Tag.UL, HTML.Tag.LI,
HTML.Tag.BODY, HTML.Tag.UL),
new InsertHTMLTextAction("InsertOrderedList", INSERT_OL_HTML,
HTML.Tag.BODY, HTML.Tag.OL),
new InsertHTMLTextAction("InsertOrderedListItem", INSERT_OL_HTML,
HTML.Tag.OL, HTML.Tag.LI,
HTML.Tag.BODY, HTML.Tag.OL),
new InsertHRAction(),
new InsertHTMLTextAction("InsertPre", INSERT_PRE_HTML,
HTML.Tag.BODY, HTML.Tag.PRE),
nextLinkAction, previousLinkAction, activateLinkAction,
new BeginAction(beginAction, false),
new BeginAction(selectionBeginAction, true)
};
// link navigation support
private boolean foundLink = false;
private int prevHypertextOffset = -1;
private Object linkNavigationTag;
/** {@collect.stats}
* An abstract Action providing some convenience methods that may
* be useful in inserting HTML into an existing document.
* <p>NOTE: None of the convenience methods obtain a lock on the
* document. If you have another thread modifying the text these
* methods may have inconsistent behavior, or return the wrong thing.
*/
public static abstract class HTMLTextAction extends StyledTextAction {
public HTMLTextAction(String name) {
super(name);
}
/** {@collect.stats}
* @return HTMLDocument of <code>e</code>.
*/
protected HTMLDocument getHTMLDocument(JEditorPane e) {
Document d = e.getDocument();
if (d instanceof HTMLDocument) {
return (HTMLDocument) d;
}
throw new IllegalArgumentException("document must be HTMLDocument");
}
/** {@collect.stats}
* @return HTMLEditorKit for <code>e</code>.
*/
protected HTMLEditorKit getHTMLEditorKit(JEditorPane e) {
EditorKit k = e.getEditorKit();
if (k instanceof HTMLEditorKit) {
return (HTMLEditorKit) k;
}
throw new IllegalArgumentException("EditorKit must be HTMLEditorKit");
}
/** {@collect.stats}
* Returns an array of the Elements that contain <code>offset</code>.
* The first elements corresponds to the root.
*/
protected Element[] getElementsAt(HTMLDocument doc, int offset) {
return getElementsAt(doc.getDefaultRootElement(), offset, 0);
}
/** {@collect.stats}
* Recursive method used by getElementsAt.
*/
private Element[] getElementsAt(Element parent, int offset,
int depth) {
if (parent.isLeaf()) {
Element[] retValue = new Element[depth + 1];
retValue[depth] = parent;
return retValue;
}
Element[] retValue = getElementsAt(parent.getElement
(parent.getElementIndex(offset)), offset, depth + 1);
retValue[depth] = parent;
return retValue;
}
/** {@collect.stats}
* Returns number of elements, starting at the deepest leaf, needed
* to get to an element representing <code>tag</code>. This will
* return -1 if no elements is found representing <code>tag</code>,
* or 0 if the parent of the leaf at <code>offset</code> represents
* <code>tag</code>.
*/
protected int elementCountToTag(HTMLDocument doc, int offset,
HTML.Tag tag) {
int depth = -1;
Element e = doc.getCharacterElement(offset);
while (e != null && e.getAttributes().getAttribute
(StyleConstants.NameAttribute) != tag) {
e = e.getParentElement();
depth++;
}
if (e == null) {
return -1;
}
return depth;
}
/** {@collect.stats}
* Returns the deepest element at <code>offset</code> matching
* <code>tag</code>.
*/
protected Element findElementMatchingTag(HTMLDocument doc, int offset,
HTML.Tag tag) {
Element e = doc.getDefaultRootElement();
Element lastMatch = null;
while (e != null) {
if (e.getAttributes().getAttribute
(StyleConstants.NameAttribute) == tag) {
lastMatch = e;
}
e = e.getElement(e.getElementIndex(offset));
}
return lastMatch;
}
}
/** {@collect.stats}
* InsertHTMLTextAction can be used to insert an arbitrary string of HTML
* into an existing HTML document. At least two HTML.Tags need to be
* supplied. The first Tag, parentTag, identifies the parent in
* the document to add the elements to. The second tag, addTag,
* identifies the first tag that should be added to the document as
* seen in the HTML string. One important thing to remember, is that
* the parser is going to generate all the appropriate tags, even if
* they aren't in the HTML string passed in.<p>
* For example, lets say you wanted to create an action to insert
* a table into the body. The parentTag would be HTML.Tag.BODY,
* addTag would be HTML.Tag.TABLE, and the string could be something
* like <table><tr><td></td></tr></table>.
* <p>There is also an option to supply an alternate parentTag and
* addTag. These will be checked for if there is no parentTag at
* offset.
*/
public static class InsertHTMLTextAction extends HTMLTextAction {
public InsertHTMLTextAction(String name, String html,
HTML.Tag parentTag, HTML.Tag addTag) {
this(name, html, parentTag, addTag, null, null);
}
public InsertHTMLTextAction(String name, String html,
HTML.Tag parentTag,
HTML.Tag addTag,
HTML.Tag alternateParentTag,
HTML.Tag alternateAddTag) {
this(name, html, parentTag, addTag, alternateParentTag,
alternateAddTag, true);
}
/* public */
InsertHTMLTextAction(String name, String html,
HTML.Tag parentTag,
HTML.Tag addTag,
HTML.Tag alternateParentTag,
HTML.Tag alternateAddTag,
boolean adjustSelection) {
super(name);
this.html = html;
this.parentTag = parentTag;
this.addTag = addTag;
this.alternateParentTag = alternateParentTag;
this.alternateAddTag = alternateAddTag;
this.adjustSelection = adjustSelection;
}
/** {@collect.stats}
* A cover for HTMLEditorKit.insertHTML. If an exception it
* thrown it is wrapped in a RuntimeException and thrown.
*/
protected void insertHTML(JEditorPane editor, HTMLDocument doc,
int offset, String html, int popDepth,
int pushDepth, HTML.Tag addTag) {
try {
getHTMLEditorKit(editor).insertHTML(doc, offset, html,
popDepth, pushDepth,
addTag);
} catch (IOException ioe) {
throw new RuntimeException("Unable to insert: " + ioe);
} catch (BadLocationException ble) {
throw new RuntimeException("Unable to insert: " + ble);
}
}
/** {@collect.stats}
* This is invoked when inserting at a boundary. It determines
* the number of pops, and then the number of pushes that need
* to be performed, and then invokes insertHTML.
* @since 1.3
*/
protected void insertAtBoundary(JEditorPane editor, HTMLDocument doc,
int offset, Element insertElement,
String html, HTML.Tag parentTag,
HTML.Tag addTag) {
insertAtBoundry(editor, doc, offset, insertElement, html,
parentTag, addTag);
}
/** {@collect.stats}
* This is invoked when inserting at a boundary. It determines
* the number of pops, and then the number of pushes that need
* to be performed, and then invokes insertHTML.
* @deprecated As of Java 2 platform v1.3, use insertAtBoundary
*/
@Deprecated
protected void insertAtBoundry(JEditorPane editor, HTMLDocument doc,
int offset, Element insertElement,
String html, HTML.Tag parentTag,
HTML.Tag addTag) {
// Find the common parent.
Element e;
Element commonParent;
boolean isFirst = (offset == 0);
if (offset > 0 || insertElement == null) {
e = doc.getDefaultRootElement();
while (e != null && e.getStartOffset() != offset &&
!e.isLeaf()) {
e = e.getElement(e.getElementIndex(offset));
}
commonParent = (e != null) ? e.getParentElement() : null;
}
else {
// If inserting at the origin, the common parent is the
// insertElement.
commonParent = insertElement;
}
if (commonParent != null) {
// Determine how many pops to do.
int pops = 0;
int pushes = 0;
if (isFirst && insertElement != null) {
e = commonParent;
while (e != null && !e.isLeaf()) {
e = e.getElement(e.getElementIndex(offset));
pops++;
}
}
else {
e = commonParent;
offset--;
while (e != null && !e.isLeaf()) {
e = e.getElement(e.getElementIndex(offset));
pops++;
}
// And how many pushes
e = commonParent;
offset++;
while (e != null && e != insertElement) {
e = e.getElement(e.getElementIndex(offset));
pushes++;
}
}
pops = Math.max(0, pops - 1);
// And insert!
insertHTML(editor, doc, offset, html, pops, pushes, addTag);
}
}
/** {@collect.stats}
* If there is an Element with name <code>tag</code> at
* <code>offset</code>, this will invoke either insertAtBoundary
* or <code>insertHTML</code>. This returns true if there is
* a match, and one of the inserts is invoked.
*/
/*protected*/
boolean insertIntoTag(JEditorPane editor, HTMLDocument doc,
int offset, HTML.Tag tag, HTML.Tag addTag) {
Element e = findElementMatchingTag(doc, offset, tag);
if (e != null && e.getStartOffset() == offset) {
insertAtBoundary(editor, doc, offset, e, html,
tag, addTag);
return true;
}
else if (offset > 0) {
int depth = elementCountToTag(doc, offset - 1, tag);
if (depth != -1) {
insertHTML(editor, doc, offset, html, depth, 0, addTag);
return true;
}
}
return false;
}
/** {@collect.stats}
* Called after an insertion to adjust the selection.
*/
/* protected */
void adjustSelection(JEditorPane pane, HTMLDocument doc,
int startOffset, int oldLength) {
int newLength = doc.getLength();
if (newLength != oldLength && startOffset < newLength) {
if (startOffset > 0) {
String text;
try {
text = doc.getText(startOffset - 1, 1);
} catch (BadLocationException ble) {
text = null;
}
if (text != null && text.length() > 0 &&
text.charAt(0) == '\n') {
pane.select(startOffset, startOffset);
}
else {
pane.select(startOffset + 1, startOffset + 1);
}
}
else {
pane.select(1, 1);
}
}
}
/** {@collect.stats}
* Inserts the HTML into the document.
*
* @param ae the event
*/
public void actionPerformed(ActionEvent ae) {
JEditorPane editor = getEditor(ae);
if (editor != null) {
HTMLDocument doc = getHTMLDocument(editor);
int offset = editor.getSelectionStart();
int length = doc.getLength();
boolean inserted;
// Try first choice
if (!insertIntoTag(editor, doc, offset, parentTag, addTag) &&
alternateParentTag != null) {
// Then alternate.
inserted = insertIntoTag(editor, doc, offset,
alternateParentTag,
alternateAddTag);
}
else {
inserted = true;
}
if (adjustSelection && inserted) {
adjustSelection(editor, doc, offset, length);
}
}
}
/** {@collect.stats} HTML to insert. */
protected String html;
/** {@collect.stats} Tag to check for in the document. */
protected HTML.Tag parentTag;
/** {@collect.stats} Tag in HTML to start adding tags from. */
protected HTML.Tag addTag;
/** {@collect.stats} Alternate Tag to check for in the document if parentTag is
* not found. */
protected HTML.Tag alternateParentTag;
/** {@collect.stats} Alternate tag in HTML to start adding tags from if parentTag
* is not found and alternateParentTag is found. */
protected HTML.Tag alternateAddTag;
/** {@collect.stats} True indicates the selection should be adjusted after an insert. */
boolean adjustSelection;
}
/** {@collect.stats}
* InsertHRAction is special, at actionPerformed time it will determine
* the parent HTML.Tag based on the paragraph element at the selection
* start.
*/
static class InsertHRAction extends InsertHTMLTextAction {
InsertHRAction() {
super("InsertHR", "<hr>", null, HTML.Tag.IMPLIED, null, null,
false);
}
/** {@collect.stats}
* Inserts the HTML into the document.
*
* @param ae the event
*/
public void actionPerformed(ActionEvent ae) {
JEditorPane editor = getEditor(ae);
if (editor != null) {
HTMLDocument doc = getHTMLDocument(editor);
int offset = editor.getSelectionStart();
Element paragraph = doc.getParagraphElement(offset);
if (paragraph.getParentElement() != null) {
parentTag = (HTML.Tag)paragraph.getParentElement().
getAttributes().getAttribute
(StyleConstants.NameAttribute);
super.actionPerformed(ae);
}
}
}
}
/*
* Returns the object in an AttributeSet matching a key
*/
static private Object getAttrValue(AttributeSet attr, HTML.Attribute key) {
Enumeration names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object nextKey = names.nextElement();
Object nextVal = attr.getAttribute(nextKey);
if (nextVal instanceof AttributeSet) {
Object value = getAttrValue((AttributeSet)nextVal, key);
if (value != null) {
return value;
}
} else if (nextKey == key) {
return nextVal;
}
}
return null;
}
/*
* Action to move the focus on the next or previous hypertext link
* or object. TODO: This method relies on support from the
* javax.accessibility package. The text package should support
* keyboard navigation of text elements directly.
*/
static class NavigateLinkAction extends TextAction implements CaretListener {
private static final FocusHighlightPainter focusPainter =
new FocusHighlightPainter(null);
private final boolean focusBack;
/*
* Create this action with the appropriate identifier.
*/
public NavigateLinkAction(String actionName) {
super(actionName);
focusBack = "previous-link-action".equals(actionName);
}
/** {@collect.stats}
* Called when the caret position is updated.
*
* @param e the caret event
*/
public void caretUpdate(CaretEvent e) {
Object src = e.getSource();
if (src instanceof JTextComponent) {
JTextComponent comp = (JTextComponent) src;
HTMLEditorKit kit = getHTMLEditorKit(comp);
if (kit != null && kit.foundLink) {
kit.foundLink = false;
// TODO: The AccessibleContext for the editor should register
// as a listener for CaretEvents and forward the events to
// assistive technologies listening for such events.
comp.getAccessibleContext().firePropertyChange(
AccessibleContext.ACCESSIBLE_HYPERTEXT_OFFSET,
new Integer(kit.prevHypertextOffset),
new Integer(e.getDot()));
}
}
}
/*
* The operation to perform when this action is triggered.
*/
public void actionPerformed(ActionEvent e) {
JTextComponent comp = getTextComponent(e);
if (comp == null || comp.isEditable()) {
return;
}
Document doc = comp.getDocument();
HTMLEditorKit kit = getHTMLEditorKit(comp);
if (doc == null || kit == null) {
return;
}
// TODO: Should start successive iterations from the
// current caret position.
ElementIterator ei = new ElementIterator(doc);
int currentOffset = comp.getCaretPosition();
int prevStartOffset = -1;
int prevEndOffset = -1;
// highlight the next link or object after the current caret position
Element nextElement = null;
while ((nextElement = ei.next()) != null) {
String name = nextElement.getName();
AttributeSet attr = nextElement.getAttributes();
Object href = getAttrValue(attr, HTML.Attribute.HREF);
if (!(name.equals(HTML.Tag.OBJECT.toString())) && href == null) {
continue;
}
int elementOffset = nextElement.getStartOffset();
if (focusBack) {
if (elementOffset >= currentOffset &&
prevStartOffset >= 0) {
kit.foundLink = true;
comp.setCaretPosition(prevStartOffset);
moveCaretPosition(comp, kit, prevStartOffset,
prevEndOffset);
kit.prevHypertextOffset = prevStartOffset;
return;
}
} else { // focus forward
if (elementOffset > currentOffset) {
kit.foundLink = true;
comp.setCaretPosition(elementOffset);
moveCaretPosition(comp, kit, elementOffset,
nextElement.getEndOffset());
kit.prevHypertextOffset = elementOffset;
return;
}
}
prevStartOffset = nextElement.getStartOffset();
prevEndOffset = nextElement.getEndOffset();
}
if (focusBack && prevStartOffset >= 0) {
kit.foundLink = true;
comp.setCaretPosition(prevStartOffset);
moveCaretPosition(comp, kit, prevStartOffset, prevEndOffset);
kit.prevHypertextOffset = prevStartOffset;
return;
}
}
/*
* Moves the caret from mark to dot
*/
private void moveCaretPosition(JTextComponent comp, HTMLEditorKit kit,
int mark, int dot) {
Highlighter h = comp.getHighlighter();
if (h != null) {
int p0 = Math.min(dot, mark);
int p1 = Math.max(dot, mark);
try {
if (kit.linkNavigationTag != null) {
h.changeHighlight(kit.linkNavigationTag, p0, p1);
} else {
kit.linkNavigationTag =
h.addHighlight(p0, p1, focusPainter);
}
} catch (BadLocationException e) {
}
}
}
private HTMLEditorKit getHTMLEditorKit(JTextComponent comp) {
if (comp instanceof JEditorPane) {
EditorKit kit = ((JEditorPane) comp).getEditorKit();
if (kit instanceof HTMLEditorKit) {
return (HTMLEditorKit) kit;
}
}
return null;
}
/** {@collect.stats}
* A highlight painter that draws a one-pixel border around
* the highlighted area.
*/
static class FocusHighlightPainter extends
DefaultHighlighter.DefaultHighlightPainter {
FocusHighlightPainter(Color color) {
super(color);
}
/** {@collect.stats}
* Paints a portion of a highlight.
*
* @param g the graphics context
* @param offs0 the starting model offset >= 0
* @param offs1 the ending model offset >= offs1
* @param bounds the bounding box of the view, which is not
* necessarily the region to paint.
* @param c the editor
* @param view View painting for
* @return region in which drawing occurred
*/
public Shape paintLayer(Graphics g, int offs0, int offs1,
Shape bounds, JTextComponent c, View view) {
Color color = getColor();
if (color == null) {
g.setColor(c.getSelectionColor());
}
else {
g.setColor(color);
}
if (offs0 == view.getStartOffset() &&
offs1 == view.getEndOffset()) {
// Contained in view, can just use bounds.
Rectangle alloc;
if (bounds instanceof Rectangle) {
alloc = (Rectangle)bounds;
}
else {
alloc = bounds.getBounds();
}
g.drawRect(alloc.x, alloc.y, alloc.width - 1, alloc.height);
return alloc;
}
else {
// Should only render part of View.
try {
// --- determine locations ---
Shape shape = view.modelToView(offs0, Position.Bias.Forward,
offs1,Position.Bias.Backward,
bounds);
Rectangle r = (shape instanceof Rectangle) ?
(Rectangle)shape : shape.getBounds();
g.drawRect(r.x, r.y, r.width - 1, r.height);
return r;
} catch (BadLocationException e) {
// can't render
}
}
// Only if exception
return null;
}
}
}
/*
* Action to activate the hypertext link that has focus.
* TODO: This method relies on support from the
* javax.accessibility package. The text package should support
* keyboard navigation of text elements directly.
*/
static class ActivateLinkAction extends TextAction {
/** {@collect.stats}
* Create this action with the appropriate identifier.
*/
public ActivateLinkAction(String actionName) {
super(actionName);
}
/*
* activates the hyperlink at offset
*/
private void activateLink(String href, HTMLDocument doc,
JEditorPane editor, int offset) {
try {
URL page =
(URL)doc.getProperty(Document.StreamDescriptionProperty);
URL url = new URL(page, href);
HyperlinkEvent linkEvent = new HyperlinkEvent
(editor, HyperlinkEvent.EventType.
ACTIVATED, url, url.toExternalForm(),
doc.getCharacterElement(offset));
editor.fireHyperlinkUpdate(linkEvent);
} catch (MalformedURLException m) {
}
}
/*
* Invokes default action on the object in an element
*/
private void doObjectAction(JEditorPane editor, Element elem) {
View view = getView(editor, elem);
if (view != null && view instanceof ObjectView) {
Component comp = ((ObjectView)view).getComponent();
if (comp != null && comp instanceof Accessible) {
AccessibleContext ac = ((Accessible)comp).getAccessibleContext();
if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
aa.doAccessibleAction(0);
}
}
}
}
}
/*
* Returns the root view for a document
*/
private View getRootView(JEditorPane editor) {
return editor.getUI().getRootView(editor);
}
/*
* Returns a view associated with an element
*/
private View getView(JEditorPane editor, Element elem) {
Object lock = lock(editor);
try {
View rootView = getRootView(editor);
int start = elem.getStartOffset();
if (rootView != null) {
return getView(rootView, elem, start);
}
return null;
} finally {
unlock(lock);
}
}
private View getView(View parent, Element elem, int start) {
if (parent.getElement() == elem) {
return parent;
}
int index = parent.getViewIndex(start, Position.Bias.Forward);
if (index != -1 && index < parent.getViewCount()) {
return getView(parent.getView(index), elem, start);
}
return null;
}
/*
* If possible acquires a lock on the Document. If a lock has been
* obtained a key will be retured that should be passed to
* <code>unlock</code>.
*/
private Object lock(JEditorPane editor) {
Document document = editor.getDocument();
if (document instanceof AbstractDocument) {
((AbstractDocument)document).readLock();
return document;
}
return null;
}
/*
* Releases a lock previously obtained via <code>lock</code>.
*/
private void unlock(Object key) {
if (key != null) {
((AbstractDocument)key).readUnlock();
}
}
/*
* The operation to perform when this action is triggered.
*/
public void actionPerformed(ActionEvent e) {
JTextComponent c = getTextComponent(e);
if (c.isEditable() || !(c instanceof JEditorPane)) {
return;
}
JEditorPane editor = (JEditorPane)c;
Document d = editor.getDocument();
if (d == null || !(d instanceof HTMLDocument)) {
return;
}
HTMLDocument doc = (HTMLDocument)d;
ElementIterator ei = new ElementIterator(doc);
int currentOffset = editor.getCaretPosition();
// invoke the next link or object action
String urlString = null;
String objString = null;
Element currentElement = null;
while ((currentElement = ei.next()) != null) {
String name = currentElement.getName();
AttributeSet attr = currentElement.getAttributes();
Object href = getAttrValue(attr, HTML.Attribute.HREF);
if (href != null) {
if (currentOffset >= currentElement.getStartOffset() &&
currentOffset <= currentElement.getEndOffset()) {
activateLink((String)href, doc, editor, currentOffset);
return;
}
} else if (name.equals(HTML.Tag.OBJECT.toString())) {
Object obj = getAttrValue(attr, HTML.Attribute.CLASSID);
if (obj != null) {
if (currentOffset >= currentElement.getStartOffset() &&
currentOffset <= currentElement.getEndOffset()) {
doObjectAction(editor, currentElement);
return;
}
}
}
}
}
}
private static int getBodyElementStart(JTextComponent comp) {
Element rootElement = comp.getDocument().getRootElements()[0];
for (int i = 0; i < rootElement.getElementCount(); i++) {
Element currElement = rootElement.getElement(i);
if("body".equals(currElement.getName())) {
return currElement.getStartOffset();
}
}
return 0;
}
/*
* Move the caret to the beginning of the document.
* @see DefaultEditorKit#beginAction
* @see HTMLEditorKit#getActions
*/
static class BeginAction extends TextAction {
/* Create this object with the appropriate identifier. */
BeginAction(String nm, boolean select) {
super(nm);
this.select = select;
}
/** {@collect.stats} The operation to perform when this action is triggered. */
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
int bodyStart = getBodyElementStart(target);
if (target != null) {
if (select) {
target.moveCaretPosition(bodyStart);
} else {
target.setCaretPosition(bodyStart);
}
}
}
private boolean select;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.awt.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.*;
import java.util.Enumeration;
import java.lang.Integer;
/** {@collect.stats}
* A view implementation to display an html horizontal
* rule.
*
* @author Timothy Prinzing
* @author Sara Swanson
*/
class HRuleView extends View {
/** {@collect.stats}
* Creates a new view that represents an <hr> element.
*
* @param elem the element to create a view for
*/
public HRuleView(Element elem) {
super(elem);
setPropertiesFromAttributes();
}
/** {@collect.stats}
* Update any cached values that come from attributes.
*/
protected void setPropertiesFromAttributes() {
StyleSheet sheet = ((HTMLDocument)getDocument()).getStyleSheet();
AttributeSet eAttr = getElement().getAttributes();
attr = sheet.getViewAttributes(this);
alignment = StyleConstants.ALIGN_CENTER;
size = 0;
noshade = null;
widthValue = null;
if (attr != null) {
// getAlignment() returns ALIGN_LEFT by default, and HR should
// use ALIGN_CENTER by default, so we check if the alignment
// attribute is actually defined
if (attr.getAttribute(StyleConstants.Alignment) != null) {
alignment = StyleConstants.getAlignment(attr);
}
noshade = (String)eAttr.getAttribute(HTML.Attribute.NOSHADE);
Object value = eAttr.getAttribute(HTML.Attribute.SIZE);
if (value != null && (value instanceof String))
size = Integer.parseInt((String)value);
value = attr.getAttribute(CSS.Attribute.WIDTH);
if (value != null && (value instanceof CSS.LengthValue)) {
widthValue = (CSS.LengthValue)value;
}
topMargin = getLength(CSS.Attribute.MARGIN_TOP, attr);
bottomMargin = getLength(CSS.Attribute.MARGIN_BOTTOM, attr);
leftMargin = getLength(CSS.Attribute.MARGIN_LEFT, attr);
rightMargin = getLength(CSS.Attribute.MARGIN_RIGHT, attr);
}
else {
topMargin = bottomMargin = leftMargin = rightMargin = 0;
}
size = Math.max(2, size);
}
// This will be removed and centralized at some point, need to unify this
// and avoid private classes.
private float getLength(CSS.Attribute key, AttributeSet a) {
CSS.LengthValue lv = (CSS.LengthValue) a.getAttribute(key);
float len = (lv != null) ? lv.getValue() : 0;
return len;
}
// --- View methods ---------------------------------------------
/** {@collect.stats}
* Paints the view.
*
* @param g the graphics context
* @param a the allocation region for the view
* @see View#paint
*/
public void paint(Graphics g, Shape a) {
Rectangle alloc = (a instanceof Rectangle) ? (Rectangle)a :
a.getBounds();
int x = 0;
int y = alloc.y + SPACE_ABOVE + (int)topMargin;
int width = alloc.width - (int)(leftMargin + rightMargin);
if (widthValue != null) {
width = (int)widthValue.getValue((float)width);
}
int height = alloc.height - (SPACE_ABOVE + SPACE_BELOW +
(int)topMargin + (int)bottomMargin);
if (size > 0)
height = size;
// Align the rule horizontally.
switch (alignment) {
case StyleConstants.ALIGN_CENTER:
x = alloc.x + (alloc.width / 2) - (width / 2);
break;
case StyleConstants.ALIGN_RIGHT:
x = alloc.x + alloc.width - width - (int)rightMargin;
break;
case StyleConstants.ALIGN_LEFT:
default:
x = alloc.x + (int)leftMargin;
break;
}
// Paint either a shaded rule or a solid line.
if (noshade != null) {
g.setColor(Color.black);
g.fillRect(x, y, width, height);
}
else {
Color bg = getContainer().getBackground();
Color bottom, top;
if (bg == null || bg.equals(Color.white)) {
top = Color.darkGray;
bottom = Color.lightGray;
}
else {
top = Color.darkGray;
bottom = Color.white;
}
g.setColor(bottom);
g.drawLine(x + width - 1, y, x + width - 1, y + height - 1);
g.drawLine(x, y + height - 1, x + width - 1, y + height - 1);
g.setColor(top);
g.drawLine(x, y, x + width - 1, y);
g.drawLine(x, y, x, y + height - 1);
}
}
/** {@collect.stats}
* Calculates the desired shape of the rule... this is
* basically the preferred size of the border.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the desired span
* @see View#getPreferredSpan
*/
public float getPreferredSpan(int axis) {
switch (axis) {
case View.X_AXIS:
return 1;
case View.Y_AXIS:
if (size > 0) {
return size + SPACE_ABOVE + SPACE_BELOW + topMargin +
bottomMargin;
} else {
if (noshade != null) {
return 2 + SPACE_ABOVE + SPACE_BELOW + topMargin +
bottomMargin;
} else {
return SPACE_ABOVE + SPACE_BELOW + topMargin +bottomMargin;
}
}
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
/** {@collect.stats}
* Gets the resize weight for the axis.
* The rule is: rigid vertically and flexible horizontally.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the weight
*/
public int getResizeWeight(int axis) {
if (axis == View.X_AXIS) {
return 1;
} else if (axis == View.Y_AXIS) {
return 0;
} else {
return 0;
}
}
/** {@collect.stats}
* Determines how attractive a break opportunity in
* this view is. This is implemented to request a forced break.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @param pos the potential location of the start of the
* broken view (greater than or equal to zero).
* This may be useful for calculating tab
* positions.
* @param len specifies the relative length from <em>pos</em>
* where a potential break is desired. The value must be greater
* than or equal to zero.
* @return the weight, which should be a value between
* ForcedBreakWeight and BadBreakWeight.
*/
public int getBreakWeight(int axis, float pos, float len) {
if (axis == X_AXIS) {
return ForcedBreakWeight;
}
return BadBreakWeight;
}
public View breakView(int axis, int offset, float pos, float len) {
return null;
}
/** {@collect.stats}
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @return the bounding box of the given position
* @exception BadLocationException if the given position does not
* represent a valid location in the associated document
* @see View#modelToView
*/
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
int p0 = getStartOffset();
int p1 = getEndOffset();
if ((pos >= p0) && (pos <= p1)) {
Rectangle r = a.getBounds();
if (pos == p1) {
r.x += r.width;
}
r.width = 0;
return r;
}
return null;
}
/** {@collect.stats}
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param x the X coordinate
* @param y the Y coordinate
* @param a the allocated region to render into
* @return the location within the model that best represents the
* given point of view
* @see View#viewToModel
*/
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
Rectangle alloc = (Rectangle) a;
if (x < alloc.x + (alloc.width / 2)) {
bias[0] = Position.Bias.Forward;
return getStartOffset();
}
bias[0] = Position.Bias.Backward;
return getEndOffset();
}
/** {@collect.stats}
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
return attr;
}
public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
super.changedUpdate(changes, a, f);
int pos = changes.getOffset();
if (pos <= getStartOffset() && (pos + changes.getLength()) >=
getEndOffset()) {
setPropertiesFromAttributes();
}
}
// --- variables ------------------------------------------------
private float topMargin;
private float bottomMargin;
private float leftMargin;
private float rightMargin;
private int alignment = StyleConstants.ALIGN_CENTER;
private String noshade = null;
private int size = 0;
private CSS.LengthValue widthValue;
private static final int SPACE_ABOVE = 3;
private static final int SPACE_BELOW = 3;
/** {@collect.stats} View Attributes. */
private AttributeSet attr;
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.awt.Polygon;
import java.io.Serializable;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.text.AttributeSet;
/** {@collect.stats}
* Map is used to represent a map element that is part of an HTML document.
* Once a Map has been created, and any number of areas have been added,
* you can test if a point falls inside the map via the contains method.
*
* @author Scott Violet
*/
class Map implements Serializable {
/** {@collect.stats} Name of the Map. */
private String name;
/** {@collect.stats} An array of AttributeSets. */
private Vector areaAttributes;
/** {@collect.stats} An array of RegionContainments, will slowly grow to match the
* length of areaAttributes as needed. */
private Vector areas;
public Map() {
}
public Map(String name) {
this.name = name;
}
/** {@collect.stats}
* Returns the name of the Map.
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Defines a region of the Map, based on the passed in AttributeSet.
*/
public void addArea(AttributeSet as) {
if (as == null) {
return;
}
if (areaAttributes == null) {
areaAttributes = new Vector(2);
}
areaAttributes.addElement(as.copyAttributes());
}
/** {@collect.stats}
* Removes the previously created area.
*/
public void removeArea(AttributeSet as) {
if (as != null && areaAttributes != null) {
int numAreas = (areas != null) ? areas.size() : 0;
for (int counter = areaAttributes.size() - 1; counter >= 0;
counter--) {
if (((AttributeSet)areaAttributes.elementAt(counter)).
isEqual(as)){
areaAttributes.removeElementAt(counter);
if (counter < numAreas) {
areas.removeElementAt(counter);
}
}
}
}
}
/** {@collect.stats}
* Returns the AttributeSets representing the differet areas of the Map.
*/
public AttributeSet[] getAreas() {
int numAttributes = (areaAttributes != null) ? areaAttributes.size() :
0;
if (numAttributes != 0) {
AttributeSet[] retValue = new AttributeSet[numAttributes];
areaAttributes.copyInto(retValue);
return retValue;
}
return null;
}
/** {@collect.stats}
* Returns the AttributeSet that contains the passed in location,
* <code>x</code>, <code>y</code>. <code>width</code>, <code>height</code>
* gives the size of the region the map is defined over. If a matching
* area is found, the AttribueSet for it is returned.
*/
public AttributeSet getArea(int x, int y, int width, int height) {
int numAttributes = (areaAttributes != null) ?
areaAttributes.size() : 0;
if (numAttributes > 0) {
int numAreas = (areas != null) ? areas.size() : 0;
if (areas == null) {
areas = new Vector(numAttributes);
}
for (int counter = 0; counter < numAttributes; counter++) {
if (counter >= numAreas) {
areas.addElement(createRegionContainment
((AttributeSet)areaAttributes.elementAt(counter)));
}
RegionContainment rc = (RegionContainment)areas.
elementAt(counter);
if (rc != null && rc.contains(x, y, width, height)) {
return (AttributeSet)areaAttributes.elementAt(counter);
}
}
}
return null;
}
/** {@collect.stats}
* Creates and returns an instance of RegionContainment that can be
* used to test if a particular point lies inside a region.
*/
protected RegionContainment createRegionContainment
(AttributeSet attributes) {
Object shape = attributes.getAttribute(HTML.Attribute.SHAPE);
if (shape == null) {
shape = "rect";
}
if (shape instanceof String) {
String shapeString = ((String)shape).toLowerCase();
RegionContainment rc = null;
try {
if (shapeString.equals("rect")) {
rc = new RectangleRegionContainment(attributes);
}
else if (shapeString.equals("circle")) {
rc = new CircleRegionContainment(attributes);
}
else if (shapeString.equals("poly")) {
rc = new PolygonRegionContainment(attributes);
}
else if (shapeString.equals("default")) {
rc = DefaultRegionContainment.sharedInstance();
}
} catch (RuntimeException re) {
// Something wrong with attributes.
rc = null;
}
return rc;
}
return null;
}
/** {@collect.stats}
* Creates and returns an array of integers from the String
* <code>stringCoords</code>. If one of the values represents a
* % the returned value with be negative. If a parse error results
* from trying to parse one of the numbers null is returned.
*/
static protected int[] extractCoords(Object stringCoords) {
if (stringCoords == null || !(stringCoords instanceof String)) {
return null;
}
StringTokenizer st = new StringTokenizer((String)stringCoords,
", \t\n\r");
int[] retValue = null;
int numCoords = 0;
while(st.hasMoreElements()) {
String token = st.nextToken();
int scale;
if (token.endsWith("%")) {
scale = -1;
token = token.substring(0, token.length() - 1);
}
else {
scale = 1;
}
try {
int intValue = Integer.parseInt(token);
if (retValue == null) {
retValue = new int[4];
}
else if(numCoords == retValue.length) {
int[] temp = new int[retValue.length * 2];
System.arraycopy(retValue, 0, temp, 0, retValue.length);
retValue = temp;
}
retValue[numCoords++] = intValue * scale;
} catch (NumberFormatException nfe) {
return null;
}
}
if (numCoords > 0 && numCoords != retValue.length) {
int[] temp = new int[numCoords];
System.arraycopy(retValue, 0, temp, 0, numCoords);
retValue = temp;
}
return retValue;
}
/** {@collect.stats}
* Defines the interface used for to check if a point is inside a
* region.
*/
interface RegionContainment {
/** {@collect.stats}
* Returns true if the location <code>x</code>, <code>y</code>
* falls inside the region defined in the receiver.
* <code>width</code>, <code>height</code> is the size of
* the enclosing region.
*/
public boolean contains(int x, int y, int width, int height);
}
/** {@collect.stats}
* Used to test for containment in a rectangular region.
*/
static class RectangleRegionContainment implements RegionContainment {
/** {@collect.stats} Will be non-null if one of the values is a percent, and any value
* that is non null indicates it is a percent
* (order is x, y, width, height). */
float[] percents;
/** {@collect.stats} Last value of width passed in. */
int lastWidth;
/** {@collect.stats} Last value of height passed in. */
int lastHeight;
/** {@collect.stats} Top left. */
int x0;
int y0;
/** {@collect.stats} Bottom right. */
int x1;
int y1;
public RectangleRegionContainment(AttributeSet as) {
int[] coords = Map.extractCoords(as.getAttribute(HTML.
Attribute.COORDS));
percents = null;
if (coords == null || coords.length != 4) {
throw new RuntimeException("Unable to parse rectangular area");
}
else {
x0 = coords[0];
y0 = coords[1];
x1 = coords[2];
y1 = coords[3];
if (x0 < 0 || y0 < 0 || x1 < 0 || y1 < 0) {
percents = new float[4];
lastWidth = lastHeight = -1;
for (int counter = 0; counter < 4; counter++) {
if (coords[counter] < 0) {
percents[counter] = Math.abs
(coords[counter]) / 100.0f;
}
else {
percents[counter] = -1.0f;
}
}
}
}
}
public boolean contains(int x, int y, int width, int height) {
if (percents == null) {
return contains(x, y);
}
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
if (percents[0] != -1.0f) {
x0 = (int)(percents[0] * width);
}
if (percents[1] != -1.0f) {
y0 = (int)(percents[1] * height);
}
if (percents[2] != -1.0f) {
x1 = (int)(percents[2] * width);
}
if (percents[3] != -1.0f) {
y1 = (int)(percents[3] * height);
}
}
return contains(x, y);
}
public boolean contains(int x, int y) {
return ((x >= x0 && x <= x1) &&
(y >= y0 && y <= y1));
}
}
/** {@collect.stats}
* Used to test for containment in a polygon region.
*/
static class PolygonRegionContainment extends Polygon implements
RegionContainment {
/** {@collect.stats} If any value is a percent there will be an entry here for the
* percent value. Use percentIndex to find out the index for it. */
float[] percentValues;
int[] percentIndexs;
/** {@collect.stats} Last value of width passed in. */
int lastWidth;
/** {@collect.stats} Last value of height passed in. */
int lastHeight;
public PolygonRegionContainment(AttributeSet as) {
int[] coords = Map.extractCoords(as.getAttribute(HTML.Attribute.
COORDS));
if (coords == null || coords.length == 0 ||
coords.length % 2 != 0) {
throw new RuntimeException("Unable to parse polygon area");
}
else {
int numPercents = 0;
lastWidth = lastHeight = -1;
for (int counter = coords.length - 1; counter >= 0;
counter--) {
if (coords[counter] < 0) {
numPercents++;
}
}
if (numPercents > 0) {
percentIndexs = new int[numPercents];
percentValues = new float[numPercents];
for (int counter = coords.length - 1, pCounter = 0;
counter >= 0; counter--) {
if (coords[counter] < 0) {
percentValues[pCounter] = coords[counter] /
-100.0f;
percentIndexs[pCounter] = counter;
pCounter++;
}
}
}
else {
percentIndexs = null;
percentValues = null;
}
npoints = coords.length / 2;
xpoints = new int[npoints];
ypoints = new int[npoints];
for (int counter = 0; counter < npoints; counter++) {
xpoints[counter] = coords[counter + counter];
ypoints[counter] = coords[counter + counter + 1];
}
}
}
public boolean contains(int x, int y, int width, int height) {
if (percentValues == null || (lastWidth == width &&
lastHeight == height)) {
return contains(x, y);
}
// Force the bounding box to be recalced.
bounds = null;
lastWidth = width;
lastHeight = height;
float fWidth = (float)width;
float fHeight = (float)height;
for (int counter = percentValues.length - 1; counter >= 0;
counter--) {
if (percentIndexs[counter] % 2 == 0) {
// x
xpoints[percentIndexs[counter] / 2] =
(int)(percentValues[counter] * fWidth);
}
else {
// y
ypoints[percentIndexs[counter] / 2] =
(int)(percentValues[counter] * fHeight);
}
}
return contains(x, y);
}
}
/** {@collect.stats}
* Used to test for containment in a circular region.
*/
static class CircleRegionContainment implements RegionContainment {
/** {@collect.stats} X origin of the circle. */
int x;
/** {@collect.stats} Y origin of the circle. */
int y;
/** {@collect.stats} Radius of the circle. */
int radiusSquared;
/** {@collect.stats} Non-null indicates one of the values represents a percent. */
float[] percentValues;
/** {@collect.stats} Last value of width passed in. */
int lastWidth;
/** {@collect.stats} Last value of height passed in. */
int lastHeight;
public CircleRegionContainment(AttributeSet as) {
int[] coords = Map.extractCoords(as.getAttribute(HTML.Attribute.
COORDS));
if (coords == null || coords.length != 3) {
throw new RuntimeException("Unable to parse circular area");
}
x = coords[0];
y = coords[1];
radiusSquared = coords[2] * coords[2];
if (coords[0] < 0 || coords[1] < 0 || coords[2] < 0) {
lastWidth = lastHeight = -1;
percentValues = new float[3];
for (int counter = 0; counter < 3; counter++) {
if (coords[counter] < 0) {
percentValues[counter] = coords[counter] /
-100.0f;
}
else {
percentValues[counter] = -1.0f;
}
}
}
else {
percentValues = null;
}
}
public boolean contains(int x, int y, int width, int height) {
if (percentValues != null && (lastWidth != width ||
lastHeight != height)) {
int newRad = Math.min(width, height) / 2;
lastWidth = width;
lastHeight = height;
if (percentValues[0] != -1.0f) {
this.x = (int)(percentValues[0] * width);
}
if (percentValues[1] != -1.0f) {
this.y = (int)(percentValues[1] * height);
}
if (percentValues[2] != -1.0f) {
radiusSquared = (int)(percentValues[2] *
Math.min(width, height));
radiusSquared *= radiusSquared;
}
}
return (((x - this.x) * (x - this.x) +
(y - this.y) * (y - this.y)) <= radiusSquared);
}
}
/** {@collect.stats}
* An implementation that will return true if the x, y location is
* inside a rectangle defined by origin 0, 0, and width equal to
* width passed in, and height equal to height passed in.
*/
static class DefaultRegionContainment implements RegionContainment {
/** {@collect.stats} A global shared instance. */
static DefaultRegionContainment si = null;
public static DefaultRegionContainment sharedInstance() {
if (si == null) {
si = new DefaultRegionContainment();
}
return si;
}
public boolean contains(int x, int y, int width, int height) {
return (x <= width && x >= 0 && y >= 0 && y <= width);
}
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.io.InputStream;
/** {@collect.stats}
* Simple class to load resources using the 1.2
* security model. Since the html support is loaded
* lazily, it's resources are potentially fetched with
* applet code in the call stack. By providing this
* functionality in a class that is only built on 1.2,
* reflection can be used from the code that is also
* built on 1.1 to call this functionality (and avoid
* the evils of preprocessing). This functionality
* is called from HTMLEditorKit.getResourceAsStream.
*
* @author Timothy Prinzing
*/
class ResourceLoader implements java.security.PrivilegedAction {
ResourceLoader(String name) {
this.name = name;
}
public Object run() {
Object o = HTMLEditorKit.class.getResourceAsStream(name);
return o;
}
public static InputStream getResourceAsStream(String name) {
java.security.PrivilegedAction a = new ResourceLoader(name);
return (InputStream) java.security.AccessController.doPrivileged(a);
}
private String name;
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.io.Serializable;
import javax.swing.text.*;
/** {@collect.stats}
* Value for the ListModel used to represent
* <option> elements. This is the object
* installed as items of the DefaultComboBoxModel
* used to represent the <select> element.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public class Option implements Serializable {
/** {@collect.stats}
* Creates a new Option object.
*
* @param attr the attributes associated with the
* option element. The attributes are copied to
* ensure they won't change.
*/
public Option(AttributeSet attr) {
this.attr = attr.copyAttributes();
selected = (attr.getAttribute(HTML.Attribute.SELECTED) != null);
}
/** {@collect.stats}
* Sets the label to be used for the option.
*/
public void setLabel(String label) {
this.label = label;
}
/** {@collect.stats}
* Fetch the label associated with the option.
*/
public String getLabel() {
return label;
}
/** {@collect.stats}
* Fetch the attributes associated with this option.
*/
public AttributeSet getAttributes() {
return attr;
}
/** {@collect.stats}
* String representation is the label.
*/
public String toString() {
return label;
}
/** {@collect.stats}
* Sets the selected state.
*/
protected void setSelection(boolean state) {
selected = state;
}
/** {@collect.stats}
* Fetches the selection state associated with this option.
*/
public boolean isSelected() {
return selected;
}
/** {@collect.stats}
* Convenience method to return the string associated
* with the <code>value</code> attribute. If the
* value has not been specified, the label will be
* returned.
*/
public String getValue() {
String value = (String) attr.getAttribute(HTML.Attribute.VALUE);
if (value == null) {
value = label;
}
return value;
}
private boolean selected;
private String label;
private AttributeSet attr;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.io.*;
/** {@collect.stats}
* A CSS parser. This works by way of a delegate that implements the
* CSSParserCallback interface. The delegate is notified of the following
* events:
* <ul>
* <li>Import statement: <code>handleImport</code>
* <li>Selectors <code>handleSelector</code>. This is invoked for each
* string. For example if the Reader contained p, bar , a {}, the delegate
* would be notified 4 times, for 'p,' 'bar' ',' and 'a'.
* <li>When a rule starts, <code>startRule</code>
* <li>Properties in the rule via the <code>handleProperty</code>. This
* is invoked one per property/value key, eg font size: foo;, would
* cause the delegate to be notified once with a value of 'font size'.
* <li>Values in the rule via the <code>handleValue</code>, this is notified
* for the total value.
* <li>When a rule ends, <code>endRule</code>
* </ul>
* This will parse much more than CSS 1, and loosely implements the
* recommendation for <i>Forward-compatible parsing</i> in section
* 7.1 of the CSS spec found at:
* <a href=http://www.w3.org/TR/REC-CSS1>http://www.w3.org/TR/REC-CSS1</a>.
* If an error results in parsing, a RuntimeException will be thrown.
* <p>
* This will preserve case. If the callback wishes to treat certain poritions
* case insensitively (such as selectors), it should use toLowerCase, or
* something similar.
*
* @author Scott Violet
*/
class CSSParser {
// Parsing something like the following:
// (@rule | ruleset | block)*
//
// @rule (block | identifier)*; (block with {} ends @rule)
// block matching [] () {} (that is, [()] is a block, [(){}{[]}]
// is a block, ()[] is two blocks)
// identifier "*" | '*' | anything but a [](){} and whitespace
//
// ruleset selector decblock
// selector (identifier | (block, except block '{}') )*
// declblock declaration* block*
// declaration (identifier* stopping when identifier ends with :)
// (identifier* stopping when identifier ends with ;)
//
// comments /* */ can appear any where, and are stripped.
// identifier - letters, digits, dashes and escaped characters
// block starts with { ends with matching }, () [] and {} always occur
// in matching pairs, '' and "" also occur in pairs, except " may be
// Indicates the type of token being parsed.
private static final int IDENTIFIER = 1;
private static final int BRACKET_OPEN = 2;
private static final int BRACKET_CLOSE = 3;
private static final int BRACE_OPEN = 4;
private static final int BRACE_CLOSE = 5;
private static final int PAREN_OPEN = 6;
private static final int PAREN_CLOSE = 7;
private static final int END = -1;
private static final char[] charMapping = { 0, 0, '[', ']', '{', '}', '(',
')', 0};
/** {@collect.stats} Set to true if one character has been read ahead. */
private boolean didPushChar;
/** {@collect.stats} The read ahead character. */
private int pushedChar;
/** {@collect.stats} Temporary place to hold identifiers. */
private StringBuffer unitBuffer;
/** {@collect.stats} Used to indicate blocks. */
private int[] unitStack;
/** {@collect.stats} Number of valid blocks. */
private int stackCount;
/** {@collect.stats} Holds the incoming CSS rules. */
private Reader reader;
/** {@collect.stats} Set to true when the first non @ rule is encountered. */
private boolean encounteredRuleSet;
/** {@collect.stats} Notified of state. */
private CSSParserCallback callback;
/** {@collect.stats} nextToken() inserts the string here. */
private char[] tokenBuffer;
/** {@collect.stats} Current number of chars in tokenBufferLength. */
private int tokenBufferLength;
/** {@collect.stats} Set to true if any whitespace is read. */
private boolean readWS;
// The delegate interface.
static interface CSSParserCallback {
/** {@collect.stats} Called when an @import is encountered. */
void handleImport(String importString);
// There is currently no way to distinguish between '"foo,"' and
// 'foo,'. But this generally isn't valid CSS. If it becomes
// a problem, handleSelector will have to be told if the string is
// quoted.
void handleSelector(String selector);
void startRule();
// Property names are mapped to lower case before being passed to
// the delegate.
void handleProperty(String property);
void handleValue(String value);
void endRule();
}
CSSParser() {
unitStack = new int[2];
tokenBuffer = new char[80];
unitBuffer = new StringBuffer();
}
void parse(Reader reader, CSSParserCallback callback,
boolean inRule) throws IOException {
this.callback = callback;
stackCount = tokenBufferLength = 0;
this.reader = reader;
encounteredRuleSet = false;
try {
if (inRule) {
parseDeclarationBlock();
}
else {
while (getNextStatement());
}
} finally {
callback = null;
reader = null;
}
}
/** {@collect.stats}
* Gets the next statement, returning false if the end is reached. A
* statement is either an @rule, or a ruleset.
*/
private boolean getNextStatement() throws IOException {
unitBuffer.setLength(0);
int token = nextToken((char)0);
switch (token) {
case IDENTIFIER:
if (tokenBufferLength > 0) {
if (tokenBuffer[0] == '@') {
parseAtRule();
}
else {
encounteredRuleSet = true;
parseRuleSet();
}
}
return true;
case BRACKET_OPEN:
case BRACE_OPEN:
case PAREN_OPEN:
parseTillClosed(token);
return true;
case BRACKET_CLOSE:
case BRACE_CLOSE:
case PAREN_CLOSE:
// Shouldn't happen...
throw new RuntimeException("Unexpected top level block close");
case END:
return false;
}
return true;
}
/** {@collect.stats}
* Parses an @ rule, stopping at a matching brace pair, or ;.
*/
private void parseAtRule() throws IOException {
// PENDING: make this more effecient.
boolean done = false;
boolean isImport = (tokenBufferLength == 7 &&
tokenBuffer[0] == '@' && tokenBuffer[1] == 'i' &&
tokenBuffer[2] == 'm' && tokenBuffer[3] == 'p' &&
tokenBuffer[4] == 'o' && tokenBuffer[5] == 'r' &&
tokenBuffer[6] == 't');
unitBuffer.setLength(0);
while (!done) {
int nextToken = nextToken(';');
switch (nextToken) {
case IDENTIFIER:
if (tokenBufferLength > 0 &&
tokenBuffer[tokenBufferLength - 1] == ';') {
--tokenBufferLength;
done = true;
}
if (tokenBufferLength > 0) {
if (unitBuffer.length() > 0 && readWS) {
unitBuffer.append(' ');
}
unitBuffer.append(tokenBuffer, 0, tokenBufferLength);
}
break;
case BRACE_OPEN:
if (unitBuffer.length() > 0 && readWS) {
unitBuffer.append(' ');
}
unitBuffer.append(charMapping[nextToken]);
parseTillClosed(nextToken);
done = true;
// Skip a tailing ';', not really to spec.
{
int nextChar = readWS();
if (nextChar != -1 && nextChar != ';') {
pushChar(nextChar);
}
}
break;
case BRACKET_OPEN: case PAREN_OPEN:
unitBuffer.append(charMapping[nextToken]);
parseTillClosed(nextToken);
break;
case BRACKET_CLOSE: case BRACE_CLOSE: case PAREN_CLOSE:
throw new RuntimeException("Unexpected close in @ rule");
case END:
done = true;
break;
}
}
if (isImport && !encounteredRuleSet) {
callback.handleImport(unitBuffer.toString());
}
}
/** {@collect.stats}
* Parses the next rule set, which is a selector followed by a
* declaration block.
*/
private void parseRuleSet() throws IOException {
if (parseSelectors()) {
callback.startRule();
parseDeclarationBlock();
callback.endRule();
}
}
/** {@collect.stats}
* Parses a set of selectors, returning false if the end of the stream
* is reached.
*/
private boolean parseSelectors() throws IOException {
// Parse the selectors
int nextToken;
if (tokenBufferLength > 0) {
callback.handleSelector(new String(tokenBuffer, 0,
tokenBufferLength));
}
unitBuffer.setLength(0);
for (;;) {
while ((nextToken = nextToken((char)0)) == IDENTIFIER) {
if (tokenBufferLength > 0) {
callback.handleSelector(new String(tokenBuffer, 0,
tokenBufferLength));
}
}
switch (nextToken) {
case BRACE_OPEN:
return true;
case BRACKET_OPEN: case PAREN_OPEN:
parseTillClosed(nextToken);
// Not too sure about this, how we handle this isn't very
// well spec'd.
unitBuffer.setLength(0);
break;
case BRACKET_CLOSE: case BRACE_CLOSE: case PAREN_CLOSE:
throw new RuntimeException("Unexpected block close in selector");
case END:
// Prematurely hit end.
return false;
}
}
}
/** {@collect.stats}
* Parses a declaration block. Which a number of declarations followed
* by a })].
*/
private void parseDeclarationBlock() throws IOException {
for (;;) {
int token = parseDeclaration();
switch (token) {
case END: case BRACE_CLOSE:
return;
case BRACKET_CLOSE: case PAREN_CLOSE:
// Bail
throw new RuntimeException("Unexpected close in declaration block");
case IDENTIFIER:
break;
}
}
}
/** {@collect.stats}
* Parses a single declaration, which is an identifier a : and another
* identifier. This returns the last token seen.
*/
// identifier+: identifier* ;|}
private int parseDeclaration() throws IOException {
int token;
if ((token = parseIdentifiers(':', false)) != IDENTIFIER) {
return token;
}
// Make the property name to lowercase
for (int counter = unitBuffer.length() - 1; counter >= 0; counter--) {
unitBuffer.setCharAt(counter, Character.toLowerCase
(unitBuffer.charAt(counter)));
}
callback.handleProperty(unitBuffer.toString());
token = parseIdentifiers(';', true);
callback.handleValue(unitBuffer.toString());
return token;
}
/** {@collect.stats}
* Parses identifiers until <code>extraChar</code> is encountered,
* returning the ending token, which will be IDENTIFIER if extraChar
* is found.
*/
private int parseIdentifiers(char extraChar,
boolean wantsBlocks) throws IOException {
int nextToken;
int ubl;
unitBuffer.setLength(0);
for (;;) {
nextToken = nextToken(extraChar);
switch (nextToken) {
case IDENTIFIER:
if (tokenBufferLength > 0) {
if (tokenBuffer[tokenBufferLength - 1] == extraChar) {
if (--tokenBufferLength > 0) {
if (readWS && unitBuffer.length() > 0) {
unitBuffer.append(' ');
}
unitBuffer.append(tokenBuffer, 0,
tokenBufferLength);
}
return IDENTIFIER;
}
if (readWS && unitBuffer.length() > 0) {
unitBuffer.append(' ');
}
unitBuffer.append(tokenBuffer, 0, tokenBufferLength);
}
break;
case BRACKET_OPEN:
case BRACE_OPEN:
case PAREN_OPEN:
ubl = unitBuffer.length();
if (wantsBlocks) {
unitBuffer.append(charMapping[nextToken]);
}
parseTillClosed(nextToken);
if (!wantsBlocks) {
unitBuffer.setLength(ubl);
}
break;
case BRACE_CLOSE:
// No need to throw for these two, we return token and
// caller can do whatever.
case BRACKET_CLOSE:
case PAREN_CLOSE:
case END:
// Hit the end
return nextToken;
}
}
}
/** {@collect.stats}
* Parses till a matching block close is encountered. This is only
* appropriate to be called at the top level (no nesting).
*/
private void parseTillClosed(int openToken) throws IOException {
int nextToken;
boolean done = false;
startBlock(openToken);
while (!done) {
nextToken = nextToken((char)0);
switch (nextToken) {
case IDENTIFIER:
if (unitBuffer.length() > 0 && readWS) {
unitBuffer.append(' ');
}
if (tokenBufferLength > 0) {
unitBuffer.append(tokenBuffer, 0, tokenBufferLength);
}
break;
case BRACKET_OPEN: case BRACE_OPEN: case PAREN_OPEN:
if (unitBuffer.length() > 0 && readWS) {
unitBuffer.append(' ');
}
unitBuffer.append(charMapping[nextToken]);
startBlock(nextToken);
break;
case BRACKET_CLOSE: case BRACE_CLOSE: case PAREN_CLOSE:
if (unitBuffer.length() > 0 && readWS) {
unitBuffer.append(' ');
}
unitBuffer.append(charMapping[nextToken]);
endBlock(nextToken);
if (!inBlock()) {
done = true;
}
break;
case END:
// Prematurely hit end.
throw new RuntimeException("Unclosed block");
}
}
}
/** {@collect.stats}
* Fetches the next token.
*/
private int nextToken(char idChar) throws IOException {
readWS = false;
int nextChar = readWS();
switch (nextChar) {
case '\'':
readTill('\'');
if (tokenBufferLength > 0) {
tokenBufferLength--;
}
return IDENTIFIER;
case '"':
readTill('"');
if (tokenBufferLength > 0) {
tokenBufferLength--;
}
return IDENTIFIER;
case '[':
return BRACKET_OPEN;
case ']':
return BRACKET_CLOSE;
case '{':
return BRACE_OPEN;
case '}':
return BRACE_CLOSE;
case '(':
return PAREN_OPEN;
case ')':
return PAREN_CLOSE;
case -1:
return END;
default:
pushChar(nextChar);
getIdentifier(idChar);
return IDENTIFIER;
}
}
/** {@collect.stats}
* Gets an identifier, returning true if the length of the string is greater than 0,
* stopping when <code>stopChar</code>, whitespace, or one of {}()[] is
* hit.
*/
// NOTE: this could be combined with readTill, as they contain somewhat
// similiar functionality.
private boolean getIdentifier(char stopChar) throws IOException {
boolean lastWasEscape = false;
boolean done = false;
int escapeCount = 0;
int escapeChar = 0;
int nextChar;
int intStopChar = (int)stopChar;
// 1 for '\', 2 for valid escape char [0-9a-fA-F], 3 for
// stop character (white space, ()[]{}) 0 otherwise
short type;
int escapeOffset = 0;
tokenBufferLength = 0;
while (!done) {
nextChar = readChar();
switch (nextChar) {
case '\\':
type = 1;
break;
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
type = 2;
escapeOffset = nextChar - '0';
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
type = 2;
escapeOffset = nextChar - 'a' + 10;
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
type = 2;
escapeOffset = nextChar - 'A' + 10;
break;
case '\'': case '"': case '[': case ']': case '{': case '}':
case '(': case ')':
case ' ': case '\n': case '\t': case '\r':
type = 3;
break;
case '/':
type = 4;
break;
case -1:
// Reached the end
done = true;
type = 0;
break;
default:
type = 0;
break;
}
if (lastWasEscape) {
if (type == 2) {
// Continue with escape.
escapeChar = escapeChar * 16 + escapeOffset;
if (++escapeCount == 4) {
lastWasEscape = false;
append((char)escapeChar);
}
}
else {
// no longer escaped
lastWasEscape = false;
if (escapeCount > 0) {
append((char)escapeChar);
// Make this simpler, reprocess the character.
pushChar(nextChar);
}
else if (!done) {
append((char)nextChar);
}
}
}
else if (!done) {
if (type == 1) {
lastWasEscape = true;
escapeChar = escapeCount = 0;
}
else if (type == 3) {
done = true;
pushChar(nextChar);
}
else if (type == 4) {
// Potential comment
nextChar = readChar();
if (nextChar == '*') {
done = true;
readComment();
readWS = true;
}
else {
append('/');
if (nextChar == -1) {
done = true;
}
else {
pushChar(nextChar);
}
}
}
else {
append((char)nextChar);
if (nextChar == intStopChar) {
done = true;
}
}
}
}
return (tokenBufferLength > 0);
}
/** {@collect.stats}
* Reads till a <code>stopChar</code> is encountered, escaping characters
* as necessary.
*/
private void readTill(char stopChar) throws IOException {
boolean lastWasEscape = false;
int escapeCount = 0;
int escapeChar = 0;
int nextChar;
boolean done = false;
int intStopChar = (int)stopChar;
// 1 for '\', 2 for valid escape char [0-9a-fA-F], 0 otherwise
short type;
int escapeOffset = 0;
tokenBufferLength = 0;
while (!done) {
nextChar = readChar();
switch (nextChar) {
case '\\':
type = 1;
break;
case '0': case '1': case '2': case '3': case '4':case '5':
case '6': case '7': case '8': case '9':
type = 2;
escapeOffset = nextChar - '0';
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
type = 2;
escapeOffset = nextChar - 'a' + 10;
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
type = 2;
escapeOffset = nextChar - 'A' + 10;
break;
case -1:
// Prematurely reached the end!
throw new RuntimeException("Unclosed " + stopChar);
default:
type = 0;
break;
}
if (lastWasEscape) {
if (type == 2) {
// Continue with escape.
escapeChar = escapeChar * 16 + escapeOffset;
if (++escapeCount == 4) {
lastWasEscape = false;
append((char)escapeChar);
}
}
else {
// no longer escaped
if (escapeCount > 0) {
append((char)escapeChar);
if (type == 1) {
lastWasEscape = true;
escapeChar = escapeCount = 0;
}
else {
if (nextChar == intStopChar) {
done = true;
}
append((char)nextChar);
lastWasEscape = false;
}
}
else {
append((char)nextChar);
lastWasEscape = false;
}
}
}
else if (type == 1) {
lastWasEscape = true;
escapeChar = escapeCount = 0;
}
else {
if (nextChar == intStopChar) {
done = true;
}
append((char)nextChar);
}
}
}
private void append(char character) {
if (tokenBufferLength == tokenBuffer.length) {
char[] newBuffer = new char[tokenBuffer.length * 2];
System.arraycopy(tokenBuffer, 0, newBuffer, 0, tokenBuffer.length);
tokenBuffer = newBuffer;
}
tokenBuffer[tokenBufferLength++] = character;
}
/** {@collect.stats}
* Parses a comment block.
*/
private void readComment() throws IOException {
int nextChar;
for(;;) {
nextChar = readChar();
switch (nextChar) {
case -1:
throw new RuntimeException("Unclosed comment");
case '*':
nextChar = readChar();
if (nextChar == '/') {
return;
}
else if (nextChar == -1) {
throw new RuntimeException("Unclosed comment");
}
else {
pushChar(nextChar);
}
break;
default:
break;
}
}
}
/** {@collect.stats}
* Called when a block start is encountered ({[.
*/
private void startBlock(int startToken) {
if (stackCount == unitStack.length) {
int[] newUS = new int[stackCount * 2];
System.arraycopy(unitStack, 0, newUS, 0, stackCount);
unitStack = newUS;
}
unitStack[stackCount++] = startToken;
}
/** {@collect.stats}
* Called when an end block is encountered )]}
*/
private void endBlock(int endToken) {
int startToken;
switch (endToken) {
case BRACKET_CLOSE:
startToken = BRACKET_OPEN;
break;
case BRACE_CLOSE:
startToken = BRACE_OPEN;
break;
case PAREN_CLOSE:
startToken = PAREN_OPEN;
break;
default:
// Will never happen.
startToken = -1;
break;
}
if (stackCount > 0 && unitStack[stackCount - 1] == startToken) {
stackCount--;
}
else {
// Invalid state, should do something.
throw new RuntimeException("Unmatched block");
}
}
/** {@collect.stats}
* @return true if currently in a block.
*/
private boolean inBlock() {
return (stackCount > 0);
}
/** {@collect.stats}
* Skips any white space, returning the character after the white space.
*/
private int readWS() throws IOException {
int nextChar;
while ((nextChar = readChar()) != -1 &&
Character.isWhitespace((char)nextChar)) {
readWS = true;
}
return nextChar;
}
/** {@collect.stats}
* Reads a character from the stream.
*/
private int readChar() throws IOException {
if (didPushChar) {
didPushChar = false;
return pushedChar;
}
return reader.read();
// Uncomment the following to do case insensitive parsing.
/*
if (retValue != -1) {
return (int)Character.toLowerCase((char)retValue);
}
return retValue;
*/
}
/** {@collect.stats}
* Supports one character look ahead, this will throw if called twice
* in a row.
*/
private void pushChar(int tempChar) {
if (didPushChar) {
// Should never happen.
throw new RuntimeException("Can not handle look ahead of more than one character");
}
didPushChar = true;
pushedChar = tempChar;
}
}
|
Java
|
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import javax.swing.text.*;
import java.net.URL;
/** {@collect.stats}
* FormSubmitEvent is used to notify interested
* parties that a form was submited.
*
* @since 1.5
* @author Denis Sharypov
*/
public class FormSubmitEvent extends HTMLFrameHyperlinkEvent {
/** {@collect.stats}
* Represents an HTML form method type.
* <UL>
* <LI><code>GET</code> corresponds to the GET form method</LI>
* <LI><code>POST</code> corresponds to the POST from method</LI>
* </UL>
* @since 1.5
*/
public enum MethodType { GET, POST };
/** {@collect.stats}
* Creates a new object representing an html form submit event.
*
* @param source the object responsible for the event
* @param type the event type
* @param actionURL the form action URL
* @param sourceElement the element that corresponds to the source
* of the event
* @param targetFrame the Frame to display the document in
* @param method the form method type
* @param data the form submission data
*/
FormSubmitEvent(Object source, EventType type, URL targetURL,
Element sourceElement, String targetFrame,
MethodType method, String data) {
super(source, type, targetURL, sourceElement, targetFrame);
this.method = method;
this.data = data;
}
/** {@collect.stats}
* Gets the form method type.
*
* @return the form method type, either
* <code>Method.GET</code> or <code>Method.POST</code>.
*/
public MethodType getMethod() {
return method;
}
/** {@collect.stats}
* Gets the form submission data.
*
* @return the string representing the form submission data.
*/
public String getData() {
return data;
}
private MethodType method;
private String data;
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import javax.swing.text.*;
/** {@collect.stats}
* TextAreaDocument extends the capabilities of the PlainDocument
* to store the data that is initially set in the Document.
* This is stored in order to enable an accurate reset of the
* state when a reset is requested.
*
* @author Sunita Mani
*/
class TextAreaDocument extends PlainDocument {
String initialText;
/** {@collect.stats}
* Resets the model by removing all the data,
* and restoring it to its initial state.
*/
void reset() {
try {
remove(0, getLength());
if (initialText != null) {
insertString(0, initialText, null);
}
} catch (BadLocationException e) {
}
}
/** {@collect.stats}
* Stores the data that the model is initially
* loaded with.
*/
void storeInitialText() {
try {
initialText = getText(0, getLength());
} catch (BadLocationException e) {
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import javax.swing.text.*;
/** {@collect.stats}
* Processes the <BR> tag. In other words, forces a line break.
*
* @author Sunita Mani
*/
class BRView extends InlineView {
/** {@collect.stats}
* Creates a new view that represents a <BR> element.
*
* @param elem the element to create a view for
*/
public BRView(Element elem) {
super(elem);
}
/** {@collect.stats}
* Forces a line break.
*
* @return View.ForcedBreakWeight
*/
public int getBreakWeight(int axis, float pos, float len) {
if (axis == X_AXIS) {
return ForcedBreakWeight;
} else {
return super.getBreakWeight(axis, pos, len);
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.HeadlessException;
import java.awt.Image;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Locale;
import javax.swing.ImageIcon;
import javax.swing.SizeRequirements;
import javax.swing.text.*;
/** {@collect.stats}
* Defines a set of
* <a href="http://www.w3.org/TR/REC-CSS1">CSS attributes</a>
* as a typesafe enumeration. The HTML View implementations use
* CSS attributes to determine how they will render. This also defines
* methods to map between CSS/HTML/StyleConstants. Any shorthand
* properties, such as font, are mapped to the intrinsic properties.
* <p>The following describes the CSS properties that are suppored by the
* rendering engine:
* <ul><li>font-family
* <li>font-style
* <li>font-size (supports relative units)
* <li>font-weight
* <li>font
* <li>color
* <li>background-color (with the exception of transparent)
* <li>background-image
* <li>background-repeat
* <li>background-position
* <li>background
* <li>background-repeat
* <li>text-decoration (with the exception of blink and overline)
* <li>vertical-align (only sup and super)
* <li>text-align (justify is treated as center)
* <li>margin-top
* <li>margin-right
* <li>margin-bottom
* <li>margin-left
* <li>margin
* <li>padding-top
* <li>padding-right
* <li>padding-bottom
* <li>padding-left
* <li>border-style (only supports inset, outset and none)
* <li>list-style-type
* <li>list-style-position
* </ul>
* The following are modeled, but currently not rendered.
* <ul><li>font-variant
* <li>background-attachment (background always treated as scroll)
* <li>word-spacing
* <li>letter-spacing
* <li>text-indent
* <li>text-transform
* <li>line-height
* <li>border-top-width (this is used to indicate if a border should be used)
* <li>border-right-width
* <li>border-bottom-width
* <li>border-left-width
* <li>border-width
* <li>border-top
* <li>border-right
* <li>border-bottom
* <li>border-left
* <li>border
* <li>width
* <li>height
* <li>float
* <li>clear
* <li>display
* <li>white-space
* <li>list-style
* </ul>
* <p><b>Note: for the time being we do not fully support relative units,
* unless noted, so that
* p { margin-top: 10% } will be treated as if no margin-top was specified.
*
* @author Timothy Prinzing
* @author Scott Violet
* @see StyleSheet
*/
public class CSS implements Serializable {
/** {@collect.stats}
* Definitions to be used as a key on AttributeSet's
* that might hold CSS attributes. Since this is a
* closed set (i.e. defined exactly by the specification),
* it is final and cannot be extended.
*/
public static final class Attribute {
private Attribute(String name, String defaultValue, boolean inherited) {
this.name = name;
this.defaultValue = defaultValue;
this.inherited = inherited;
}
/** {@collect.stats}
* The string representation of the attribute. This
* should exactly match the string specified in the
* CSS specification.
*/
public String toString() {
return name;
}
/** {@collect.stats}
* Fetch the default value for the attribute.
* If there is no default value (such as for
* composite attributes), null will be returned.
*/
public String getDefaultValue() {
return defaultValue;
}
/** {@collect.stats}
* Indicates if the attribute should be inherited
* from the parent or not.
*/
public boolean isInherited() {
return inherited;
}
private String name;
private String defaultValue;
private boolean inherited;
public static final Attribute BACKGROUND =
new Attribute("background", null, false);
public static final Attribute BACKGROUND_ATTACHMENT =
new Attribute("background-attachment", "scroll", false);
public static final Attribute BACKGROUND_COLOR =
new Attribute("background-color", "transparent", false);
public static final Attribute BACKGROUND_IMAGE =
new Attribute("background-image", "none", false);
public static final Attribute BACKGROUND_POSITION =
new Attribute("background-position", null, false);
public static final Attribute BACKGROUND_REPEAT =
new Attribute("background-repeat", "repeat", false);
public static final Attribute BORDER =
new Attribute("border", null, false);
public static final Attribute BORDER_BOTTOM =
new Attribute("border-bottom", null, false);
public static final Attribute BORDER_BOTTOM_WIDTH =
new Attribute("border-bottom-width", "medium", false);
public static final Attribute BORDER_COLOR =
new Attribute("border-color", "black", false);
public static final Attribute BORDER_LEFT =
new Attribute("border-left", null, false);
public static final Attribute BORDER_LEFT_WIDTH =
new Attribute("border-left-width", "medium", false);
public static final Attribute BORDER_RIGHT =
new Attribute("border-right", null, false);
public static final Attribute BORDER_RIGHT_WIDTH =
new Attribute("border-right-width", "medium", false);
public static final Attribute BORDER_STYLE =
new Attribute("border-style", "none", false);
public static final Attribute BORDER_TOP =
new Attribute("border-top", null, false);
public static final Attribute BORDER_TOP_WIDTH =
new Attribute("border-top-width", "medium", false);
public static final Attribute BORDER_WIDTH =
new Attribute("border-width", "medium", false);
public static final Attribute CLEAR =
new Attribute("clear", "none", false);
public static final Attribute COLOR =
new Attribute("color", "black", true);
public static final Attribute DISPLAY =
new Attribute("display", "block", false);
public static final Attribute FLOAT =
new Attribute("float", "none", false);
public static final Attribute FONT =
new Attribute("font", null, true);
public static final Attribute FONT_FAMILY =
new Attribute("font-family", null, true);
public static final Attribute FONT_SIZE =
new Attribute("font-size", "medium", true);
public static final Attribute FONT_STYLE =
new Attribute("font-style", "normal", true);
public static final Attribute FONT_VARIANT =
new Attribute("font-variant", "normal", true);
public static final Attribute FONT_WEIGHT =
new Attribute("font-weight", "normal", true);
public static final Attribute HEIGHT =
new Attribute("height", "auto", false);
public static final Attribute LETTER_SPACING =
new Attribute("letter-spacing", "normal", true);
public static final Attribute LINE_HEIGHT =
new Attribute("line-height", "normal", true);
public static final Attribute LIST_STYLE =
new Attribute("list-style", null, true);
public static final Attribute LIST_STYLE_IMAGE =
new Attribute("list-style-image", "none", true);
public static final Attribute LIST_STYLE_POSITION =
new Attribute("list-style-position", "outside", true);
public static final Attribute LIST_STYLE_TYPE =
new Attribute("list-style-type", "disc", true);
public static final Attribute MARGIN =
new Attribute("margin", null, false);
public static final Attribute MARGIN_BOTTOM =
new Attribute("margin-bottom", "0", false);
public static final Attribute MARGIN_LEFT =
new Attribute("margin-left", "0", false);
public static final Attribute MARGIN_RIGHT =
new Attribute("margin-right", "0", false);
/*
* made up css attributes to describe orientation depended
* margins. used for <dir>, <menu>, <ul> etc. see
* 5088268 for more details
*/
static final Attribute MARGIN_LEFT_LTR =
new Attribute("margin-left-ltr",
Integer.toString(Integer.MIN_VALUE), false);
static final Attribute MARGIN_LEFT_RTL =
new Attribute("margin-left-rtl",
Integer.toString(Integer.MIN_VALUE), false);
static final Attribute MARGIN_RIGHT_LTR =
new Attribute("margin-right-ltr",
Integer.toString(Integer.MIN_VALUE), false);
static final Attribute MARGIN_RIGHT_RTL =
new Attribute("margin-right-rtl",
Integer.toString(Integer.MIN_VALUE), false);
public static final Attribute MARGIN_TOP =
new Attribute("margin-top", "0", false);
public static final Attribute PADDING =
new Attribute("padding", null, false);
public static final Attribute PADDING_BOTTOM =
new Attribute("padding-bottom", "0", false);
public static final Attribute PADDING_LEFT =
new Attribute("padding-left", "0", false);
public static final Attribute PADDING_RIGHT =
new Attribute("padding-right", "0", false);
public static final Attribute PADDING_TOP =
new Attribute("padding-top", "0", false);
public static final Attribute TEXT_ALIGN =
new Attribute("text-align", null, true);
public static final Attribute TEXT_DECORATION =
new Attribute("text-decoration", "none", true);
public static final Attribute TEXT_INDENT =
new Attribute("text-indent", "0", true);
public static final Attribute TEXT_TRANSFORM =
new Attribute("text-transform", "none", true);
public static final Attribute VERTICAL_ALIGN =
new Attribute("vertical-align", "baseline", false);
public static final Attribute WORD_SPACING =
new Attribute("word-spacing", "normal", true);
public static final Attribute WHITE_SPACE =
new Attribute("white-space", "normal", true);
public static final Attribute WIDTH =
new Attribute("width", "auto", false);
/*public*/ static final Attribute BORDER_SPACING =
new Attribute("border-spacing", "0", true);
/*public*/ static final Attribute CAPTION_SIDE =
new Attribute("caption-side", "left", true);
// All possible CSS attribute keys.
static final Attribute[] allAttributes = {
BACKGROUND, BACKGROUND_ATTACHMENT, BACKGROUND_COLOR,
BACKGROUND_IMAGE, BACKGROUND_POSITION, BACKGROUND_REPEAT,
BORDER, BORDER_BOTTOM, BORDER_BOTTOM_WIDTH, BORDER_COLOR,
BORDER_LEFT, BORDER_LEFT_WIDTH, BORDER_RIGHT, BORDER_RIGHT_WIDTH,
BORDER_STYLE, BORDER_TOP, BORDER_TOP_WIDTH, BORDER_WIDTH,
CLEAR, COLOR, DISPLAY, FLOAT, FONT, FONT_FAMILY, FONT_SIZE,
FONT_STYLE, FONT_VARIANT, FONT_WEIGHT, HEIGHT, LETTER_SPACING,
LINE_HEIGHT, LIST_STYLE, LIST_STYLE_IMAGE, LIST_STYLE_POSITION,
LIST_STYLE_TYPE, MARGIN, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT,
MARGIN_TOP, PADDING, PADDING_BOTTOM, PADDING_LEFT, PADDING_RIGHT,
PADDING_TOP, TEXT_ALIGN, TEXT_DECORATION, TEXT_INDENT, TEXT_TRANSFORM,
VERTICAL_ALIGN, WORD_SPACING, WHITE_SPACE, WIDTH,
BORDER_SPACING, CAPTION_SIDE,
MARGIN_LEFT_LTR, MARGIN_LEFT_RTL, MARGIN_RIGHT_LTR, MARGIN_RIGHT_RTL
};
private static final Attribute[] ALL_MARGINS =
{ MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM, MARGIN_LEFT };
private static final Attribute[] ALL_PADDING =
{ PADDING_TOP, PADDING_RIGHT, PADDING_BOTTOM, PADDING_LEFT };
private static final Attribute[] ALL_BORDER_WIDTHS =
{ BORDER_TOP_WIDTH, BORDER_RIGHT_WIDTH, BORDER_BOTTOM_WIDTH,
BORDER_LEFT_WIDTH };
}
static final class Value {
private Value(String name) {
this.name = name;
}
/** {@collect.stats}
* The string representation of the attribute. This
* should exactly match the string specified in the
* CSS specification.
*/
public String toString() {
return name;
}
static final Value INHERITED = new Value("inherited");
static final Value NONE = new Value("none");
static final Value DOTTED = new Value("dotted");
static final Value DASHED = new Value("dashed");
static final Value SOLID = new Value("solid");
static final Value DOUBLE = new Value("double");
static final Value GROOVE = new Value("groove");
static final Value RIDGE = new Value("ridge");
static final Value INSET = new Value("inset");
static final Value OUTSET = new Value("outset");
// Lists.
static final Value BLANK_LIST_ITEM = new Value("none");
static final Value DISC = new Value("disc");
static final Value CIRCLE = new Value("circle");
static final Value SQUARE = new Value("square");
static final Value DECIMAL = new Value("decimal");
static final Value LOWER_ROMAN = new Value("lower-roman");
static final Value UPPER_ROMAN = new Value("upper-roman");
static final Value LOWER_ALPHA = new Value("lower-alpha");
static final Value UPPER_ALPHA = new Value("upper-alpha");
// background-repeat
static final Value BACKGROUND_NO_REPEAT = new Value("no-repeat");
static final Value BACKGROUND_REPEAT = new Value("repeat");
static final Value BACKGROUND_REPEAT_X = new Value("repeat-x");
static final Value BACKGROUND_REPEAT_Y = new Value("repeat-y");
// background-attachment
static final Value BACKGROUND_SCROLL = new Value("scroll");
static final Value BACKGROUND_FIXED = new Value("fixed");
private String name;
static final Value[] allValues = {
INHERITED, NONE, DOTTED, DASHED, SOLID, DOUBLE, GROOVE,
RIDGE, INSET, OUTSET, DISC, CIRCLE, SQUARE, DECIMAL,
LOWER_ROMAN, UPPER_ROMAN, LOWER_ALPHA, UPPER_ALPHA,
BLANK_LIST_ITEM, BACKGROUND_NO_REPEAT, BACKGROUND_REPEAT,
BACKGROUND_REPEAT_X, BACKGROUND_REPEAT_Y,
BACKGROUND_FIXED, BACKGROUND_FIXED
};
}
public CSS() {
baseFontSize = baseFontSizeIndex + 1;
// setup the css conversion table
valueConvertor = new Hashtable();
valueConvertor.put(CSS.Attribute.FONT_SIZE, new FontSize());
valueConvertor.put(CSS.Attribute.FONT_FAMILY, new FontFamily());
valueConvertor.put(CSS.Attribute.FONT_WEIGHT, new FontWeight());
valueConvertor.put(CSS.Attribute.BORDER_STYLE, new BorderStyle());
Object cv = new ColorValue();
valueConvertor.put(CSS.Attribute.COLOR, cv);
valueConvertor.put(CSS.Attribute.BACKGROUND_COLOR, cv);
valueConvertor.put(CSS.Attribute.BORDER_COLOR, cv);
Object lv = new LengthValue();
valueConvertor.put(CSS.Attribute.MARGIN_TOP, lv);
valueConvertor.put(CSS.Attribute.MARGIN_BOTTOM, lv);
valueConvertor.put(CSS.Attribute.MARGIN_LEFT, lv);
valueConvertor.put(CSS.Attribute.MARGIN_LEFT_LTR, lv);
valueConvertor.put(CSS.Attribute.MARGIN_LEFT_RTL, lv);
valueConvertor.put(CSS.Attribute.MARGIN_RIGHT, lv);
valueConvertor.put(CSS.Attribute.MARGIN_RIGHT_LTR, lv);
valueConvertor.put(CSS.Attribute.MARGIN_RIGHT_RTL, lv);
valueConvertor.put(CSS.Attribute.PADDING_TOP, lv);
valueConvertor.put(CSS.Attribute.PADDING_BOTTOM, lv);
valueConvertor.put(CSS.Attribute.PADDING_LEFT, lv);
valueConvertor.put(CSS.Attribute.PADDING_RIGHT, lv);
Object bv = new BorderWidthValue(null, 0);
valueConvertor.put(CSS.Attribute.BORDER_WIDTH, lv);
valueConvertor.put(CSS.Attribute.BORDER_TOP_WIDTH, bv);
valueConvertor.put(CSS.Attribute.BORDER_BOTTOM_WIDTH, bv);
valueConvertor.put(CSS.Attribute.BORDER_LEFT_WIDTH, bv);
valueConvertor.put(CSS.Attribute.BORDER_RIGHT_WIDTH, bv);
Object nlv = new LengthValue(true);
valueConvertor.put(CSS.Attribute.TEXT_INDENT, nlv);
valueConvertor.put(CSS.Attribute.WIDTH, lv);
valueConvertor.put(CSS.Attribute.HEIGHT, lv);
valueConvertor.put(CSS.Attribute.BORDER_SPACING, lv);
Object sv = new StringValue();
valueConvertor.put(CSS.Attribute.FONT_STYLE, sv);
valueConvertor.put(CSS.Attribute.TEXT_DECORATION, sv);
valueConvertor.put(CSS.Attribute.TEXT_ALIGN, sv);
valueConvertor.put(CSS.Attribute.VERTICAL_ALIGN, sv);
Object valueMapper = new CssValueMapper();
valueConvertor.put(CSS.Attribute.LIST_STYLE_TYPE,
valueMapper);
valueConvertor.put(CSS.Attribute.BACKGROUND_IMAGE,
new BackgroundImage());
valueConvertor.put(CSS.Attribute.BACKGROUND_POSITION,
new BackgroundPosition());
valueConvertor.put(CSS.Attribute.BACKGROUND_REPEAT,
valueMapper);
valueConvertor.put(CSS.Attribute.BACKGROUND_ATTACHMENT,
valueMapper);
Object generic = new CssValue();
int n = CSS.Attribute.allAttributes.length;
for (int i = 0; i < n; i++) {
CSS.Attribute key = CSS.Attribute.allAttributes[i];
if (valueConvertor.get(key) == null) {
valueConvertor.put(key, generic);
}
}
}
/** {@collect.stats}
* Sets the base font size. <code>sz</code> is a CSS value, and is
* not necessarily the point size. Use getPointSize to determine the
* point size corresponding to <code>sz</code>.
*/
void setBaseFontSize(int sz) {
if (sz < 1)
baseFontSize = 0;
else if (sz > 7)
baseFontSize = 7;
else
baseFontSize = sz;
}
/** {@collect.stats}
* Sets the base font size from the passed in string.
*/
void setBaseFontSize(String size) {
int relSize, absSize, diff;
if (size != null) {
if (size.startsWith("+")) {
relSize = Integer.valueOf(size.substring(1)).intValue();
setBaseFontSize(baseFontSize + relSize);
} else if (size.startsWith("-")) {
relSize = -Integer.valueOf(size.substring(1)).intValue();
setBaseFontSize(baseFontSize + relSize);
} else {
setBaseFontSize(Integer.valueOf(size).intValue());
}
}
}
/** {@collect.stats}
* Returns the base font size.
*/
int getBaseFontSize() {
return baseFontSize;
}
/** {@collect.stats}
* Parses the CSS property <code>key</code> with value
* <code>value</code> placing the result in <code>att</code>.
*/
void addInternalCSSValue(MutableAttributeSet attr,
CSS.Attribute key, String value) {
if (key == CSS.Attribute.FONT) {
ShorthandFontParser.parseShorthandFont(this, value, attr);
}
else if (key == CSS.Attribute.BACKGROUND) {
ShorthandBackgroundParser.parseShorthandBackground
(this, value, attr);
}
else if (key == CSS.Attribute.MARGIN) {
ShorthandMarginParser.parseShorthandMargin(this, value, attr,
CSS.Attribute.ALL_MARGINS);
}
else if (key == CSS.Attribute.PADDING) {
ShorthandMarginParser.parseShorthandMargin(this, value, attr,
CSS.Attribute.ALL_PADDING);
}
else if (key == CSS.Attribute.BORDER_WIDTH) {
ShorthandMarginParser.parseShorthandMargin(this, value, attr,
CSS.Attribute.ALL_BORDER_WIDTHS);
}
else {
Object iValue = getInternalCSSValue(key, value);
if (iValue != null) {
attr.addAttribute(key, iValue);
}
}
}
/** {@collect.stats}
* Gets the internal CSS representation of <code>value</code> which is
* a CSS value of the CSS attribute named <code>key</code>. The receiver
* should not modify <code>value</code>, and the first <code>count</code>
* strings are valid.
*/
Object getInternalCSSValue(CSS.Attribute key, String value) {
CssValue conv = (CssValue) valueConvertor.get(key);
Object r = conv.parseCssValue(value);
return r != null ? r : conv.parseCssValue(key.getDefaultValue());
}
/** {@collect.stats}
* Maps from a StyleConstants to a CSS Attribute.
*/
Attribute styleConstantsKeyToCSSKey(StyleConstants sc) {
return (Attribute)styleConstantToCssMap.get(sc);
}
/** {@collect.stats}
* Maps from a StyleConstants value to a CSS value.
*/
Object styleConstantsValueToCSSValue(StyleConstants sc,
Object styleValue) {
Object cssKey = styleConstantsKeyToCSSKey(sc);
if (cssKey != null) {
CssValue conv = (CssValue)valueConvertor.get(cssKey);
return conv.fromStyleConstants(sc, styleValue);
}
return null;
}
/** {@collect.stats}
* Converts the passed in CSS value to a StyleConstants value.
* <code>key</code> identifies the CSS attribute being mapped.
*/
Object cssValueToStyleConstantsValue(StyleConstants key, Object value) {
if (value instanceof CssValue) {
return ((CssValue)value).toStyleConstants((StyleConstants)key,
null);
}
return null;
}
/** {@collect.stats}
* Returns the font for the values in the passed in AttributeSet.
* It is assumed the keys will be CSS.Attribute keys.
* <code>sc</code> is the StyleContext that will be messaged to get
* the font once the size, name and style have been determined.
*/
Font getFont(StyleContext sc, AttributeSet a, int defaultSize, StyleSheet ss) {
ss = getStyleSheet(ss);
int size = getFontSize(a, defaultSize, ss);
/*
* If the vertical alignment is set to either superscirpt or
* subscript we reduce the font size by 2 points.
*/
StringValue vAlignV = (StringValue)a.getAttribute
(CSS.Attribute.VERTICAL_ALIGN);
if ((vAlignV != null)) {
String vAlign = vAlignV.toString();
if ((vAlign.indexOf("sup") >= 0) ||
(vAlign.indexOf("sub") >= 0)) {
size -= 2;
}
}
FontFamily familyValue = (FontFamily)a.getAttribute
(CSS.Attribute.FONT_FAMILY);
String family = (familyValue != null) ? familyValue.getValue() :
Font.SANS_SERIF;
int style = Font.PLAIN;
FontWeight weightValue = (FontWeight) a.getAttribute
(CSS.Attribute.FONT_WEIGHT);
if ((weightValue != null) && (weightValue.getValue() > 400)) {
style |= Font.BOLD;
}
Object fs = a.getAttribute(CSS.Attribute.FONT_STYLE);
if ((fs != null) && (fs.toString().indexOf("italic") >= 0)) {
style |= Font.ITALIC;
}
if (family.equalsIgnoreCase("monospace")) {
family = Font.MONOSPACED;
}
Font f = sc.getFont(family, style, size);
if (f == null
|| (f.getFamily().equals(Font.DIALOG)
&& ! family.equalsIgnoreCase(Font.DIALOG))) {
family = Font.SANS_SERIF;
f = sc.getFont(family, style, size);
}
return f;
}
static int getFontSize(AttributeSet attr, int defaultSize, StyleSheet ss) {
// PENDING(prinz) this is a 1.1 based implementation, need to also
// have a 1.2 version.
FontSize sizeValue = (FontSize)attr.getAttribute(CSS.Attribute.
FONT_SIZE);
return (sizeValue != null) ? sizeValue.getValue(attr, ss)
: defaultSize;
}
/** {@collect.stats}
* Takes a set of attributes and turn it into a color
* specification. This might be used to specify things
* like brighter, more hue, etc.
* This will return null if there is no value for <code>key</code>.
*
* @param key CSS.Attribute identifying where color is stored.
* @param a the set of attributes
* @return the color
*/
Color getColor(AttributeSet a, CSS.Attribute key) {
ColorValue cv = (ColorValue) a.getAttribute(key);
if (cv != null) {
return cv.getValue();
}
return null;
}
/** {@collect.stats}
* Returns the size of a font from the passed in string.
*
* @param size CSS string describing font size
* @param baseFontSize size to use for relative units.
*/
float getPointSize(String size, StyleSheet ss) {
int relSize, absSize, diff, index;
ss = getStyleSheet(ss);
if (size != null) {
if (size.startsWith("+")) {
relSize = Integer.valueOf(size.substring(1)).intValue();
return getPointSize(baseFontSize + relSize, ss);
} else if (size.startsWith("-")) {
relSize = -Integer.valueOf(size.substring(1)).intValue();
return getPointSize(baseFontSize + relSize, ss);
} else {
absSize = Integer.valueOf(size).intValue();
return getPointSize(absSize, ss);
}
}
return 0;
}
/** {@collect.stats}
* Returns the length of the attribute in <code>a</code> with
* key <code>key</code>.
*/
float getLength(AttributeSet a, CSS.Attribute key, StyleSheet ss) {
ss = getStyleSheet(ss);
LengthValue lv = (LengthValue) a.getAttribute(key);
boolean isW3CLengthUnits = (ss == null) ? false : ss.isW3CLengthUnits();
float len = (lv != null) ? lv.getValue(isW3CLengthUnits) : 0;
return len;
}
/** {@collect.stats}
* Convert a set of HTML attributes to an equivalent
* set of CSS attributes.
*
* @param AttributeSet containing the HTML attributes.
* @return AttributeSet containing the corresponding CSS attributes.
* The AttributeSet will be empty if there are no mapping
* CSS attributes.
*/
AttributeSet translateHTMLToCSS(AttributeSet htmlAttrSet) {
MutableAttributeSet cssAttrSet = new SimpleAttributeSet();
Element elem = (Element)htmlAttrSet;
HTML.Tag tag = getHTMLTag(htmlAttrSet);
if ((tag == HTML.Tag.TD) || (tag == HTML.Tag.TH)) {
// translate border width into the cells
AttributeSet tableAttr = elem.getParentElement().
getParentElement().getAttributes();
translateAttribute(HTML.Attribute.BORDER, tableAttr, cssAttrSet);
String pad = (String)tableAttr.getAttribute(HTML.Attribute.CELLPADDING);
if (pad != null) {
LengthValue v =
(LengthValue)getInternalCSSValue(CSS.Attribute.PADDING_TOP, pad);
v.span = (v.span < 0) ? 0 : v.span;
cssAttrSet.addAttribute(CSS.Attribute.PADDING_TOP, v);
cssAttrSet.addAttribute(CSS.Attribute.PADDING_BOTTOM, v);
cssAttrSet.addAttribute(CSS.Attribute.PADDING_LEFT, v);
cssAttrSet.addAttribute(CSS.Attribute.PADDING_RIGHT, v);
}
}
if (elem.isLeaf()) {
translateEmbeddedAttributes(htmlAttrSet, cssAttrSet);
} else {
translateAttributes(tag, htmlAttrSet, cssAttrSet);
}
if (tag == HTML.Tag.CAPTION) {
/*
* Navigator uses ALIGN for caption placement and IE uses VALIGN.
*/
Object v = htmlAttrSet.getAttribute(HTML.Attribute.ALIGN);
if ((v != null) && (v.equals("top") || v.equals("bottom"))) {
cssAttrSet.addAttribute(CSS.Attribute.CAPTION_SIDE, v);
cssAttrSet.removeAttribute(CSS.Attribute.TEXT_ALIGN);
} else {
v = htmlAttrSet.getAttribute(HTML.Attribute.VALIGN);
if (v != null) {
cssAttrSet.addAttribute(CSS.Attribute.CAPTION_SIDE, v);
}
}
}
return cssAttrSet;
}
private static final Hashtable attributeMap = new Hashtable();
private static final Hashtable valueMap = new Hashtable();
/** {@collect.stats}
* The hashtable and the static initalization block below,
* set up a mapping from well-known HTML attributes to
* CSS attributes. For the most part, there is a 1-1 mapping
* between the two. However in the case of certain HTML
* attributes for example HTML.Attribute.VSPACE or
* HTML.Attribute.HSPACE, end up mapping to two CSS.Attribute's.
* Therefore, the value associated with each HTML.Attribute.
* key ends up being an array of CSS.Attribute.* objects.
*/
private static final Hashtable htmlAttrToCssAttrMap = new Hashtable(20);
/** {@collect.stats}
* The hashtable and static initialization that follows sets
* up a translation from StyleConstants (i.e. the <em>well known</em>
* attributes) to the associated CSS attributes.
*/
private static final Hashtable styleConstantToCssMap = new Hashtable(17);
/** {@collect.stats} Maps from HTML value to a CSS value. Used in internal mapping. */
private static final Hashtable htmlValueToCssValueMap = new Hashtable(8);
/** {@collect.stats} Maps from CSS value (string) to internal value. */
private static final Hashtable cssValueToInternalValueMap = new Hashtable(13);
static {
// load the attribute map
for (int i = 0; i < Attribute.allAttributes.length; i++ ) {
attributeMap.put(Attribute.allAttributes[i].toString(),
Attribute.allAttributes[i]);
}
// load the value map
for (int i = 0; i < Value.allValues.length; i++ ) {
valueMap.put(Value.allValues[i].toString(),
Value.allValues[i]);
}
htmlAttrToCssAttrMap.put(HTML.Attribute.COLOR,
new CSS.Attribute[]{CSS.Attribute.COLOR});
htmlAttrToCssAttrMap.put(HTML.Attribute.TEXT,
new CSS.Attribute[]{CSS.Attribute.COLOR});
htmlAttrToCssAttrMap.put(HTML.Attribute.CLEAR,
new CSS.Attribute[]{CSS.Attribute.CLEAR});
htmlAttrToCssAttrMap.put(HTML.Attribute.BACKGROUND,
new CSS.Attribute[]{CSS.Attribute.BACKGROUND_IMAGE});
htmlAttrToCssAttrMap.put(HTML.Attribute.BGCOLOR,
new CSS.Attribute[]{CSS.Attribute.BACKGROUND_COLOR});
htmlAttrToCssAttrMap.put(HTML.Attribute.WIDTH,
new CSS.Attribute[]{CSS.Attribute.WIDTH});
htmlAttrToCssAttrMap.put(HTML.Attribute.HEIGHT,
new CSS.Attribute[]{CSS.Attribute.HEIGHT});
htmlAttrToCssAttrMap.put(HTML.Attribute.BORDER,
new CSS.Attribute[]{CSS.Attribute.BORDER_TOP_WIDTH, CSS.Attribute.BORDER_RIGHT_WIDTH, CSS.Attribute.BORDER_BOTTOM_WIDTH, CSS.Attribute.BORDER_LEFT_WIDTH});
htmlAttrToCssAttrMap.put(HTML.Attribute.CELLPADDING,
new CSS.Attribute[]{CSS.Attribute.PADDING});
htmlAttrToCssAttrMap.put(HTML.Attribute.CELLSPACING,
new CSS.Attribute[]{CSS.Attribute.BORDER_SPACING});
htmlAttrToCssAttrMap.put(HTML.Attribute.MARGINWIDTH,
new CSS.Attribute[]{CSS.Attribute.MARGIN_LEFT,
CSS.Attribute.MARGIN_RIGHT});
htmlAttrToCssAttrMap.put(HTML.Attribute.MARGINHEIGHT,
new CSS.Attribute[]{CSS.Attribute.MARGIN_TOP,
CSS.Attribute.MARGIN_BOTTOM});
htmlAttrToCssAttrMap.put(HTML.Attribute.HSPACE,
new CSS.Attribute[]{CSS.Attribute.PADDING_LEFT,
CSS.Attribute.PADDING_RIGHT});
htmlAttrToCssAttrMap.put(HTML.Attribute.VSPACE,
new CSS.Attribute[]{CSS.Attribute.PADDING_BOTTOM,
CSS.Attribute.PADDING_TOP});
htmlAttrToCssAttrMap.put(HTML.Attribute.FACE,
new CSS.Attribute[]{CSS.Attribute.FONT_FAMILY});
htmlAttrToCssAttrMap.put(HTML.Attribute.SIZE,
new CSS.Attribute[]{CSS.Attribute.FONT_SIZE});
htmlAttrToCssAttrMap.put(HTML.Attribute.VALIGN,
new CSS.Attribute[]{CSS.Attribute.VERTICAL_ALIGN});
htmlAttrToCssAttrMap.put(HTML.Attribute.ALIGN,
new CSS.Attribute[]{CSS.Attribute.VERTICAL_ALIGN,
CSS.Attribute.TEXT_ALIGN,
CSS.Attribute.FLOAT});
htmlAttrToCssAttrMap.put(HTML.Attribute.TYPE,
new CSS.Attribute[]{CSS.Attribute.LIST_STYLE_TYPE});
htmlAttrToCssAttrMap.put(HTML.Attribute.NOWRAP,
new CSS.Attribute[]{CSS.Attribute.WHITE_SPACE});
// initialize StyleConstants mapping
styleConstantToCssMap.put(StyleConstants.FontFamily,
CSS.Attribute.FONT_FAMILY);
styleConstantToCssMap.put(StyleConstants.FontSize,
CSS.Attribute.FONT_SIZE);
styleConstantToCssMap.put(StyleConstants.Bold,
CSS.Attribute.FONT_WEIGHT);
styleConstantToCssMap.put(StyleConstants.Italic,
CSS.Attribute.FONT_STYLE);
styleConstantToCssMap.put(StyleConstants.Underline,
CSS.Attribute.TEXT_DECORATION);
styleConstantToCssMap.put(StyleConstants.StrikeThrough,
CSS.Attribute.TEXT_DECORATION);
styleConstantToCssMap.put(StyleConstants.Superscript,
CSS.Attribute.VERTICAL_ALIGN);
styleConstantToCssMap.put(StyleConstants.Subscript,
CSS.Attribute.VERTICAL_ALIGN);
styleConstantToCssMap.put(StyleConstants.Foreground,
CSS.Attribute.COLOR);
styleConstantToCssMap.put(StyleConstants.Background,
CSS.Attribute.BACKGROUND_COLOR);
styleConstantToCssMap.put(StyleConstants.FirstLineIndent,
CSS.Attribute.TEXT_INDENT);
styleConstantToCssMap.put(StyleConstants.LeftIndent,
CSS.Attribute.MARGIN_LEFT);
styleConstantToCssMap.put(StyleConstants.RightIndent,
CSS.Attribute.MARGIN_RIGHT);
styleConstantToCssMap.put(StyleConstants.SpaceAbove,
CSS.Attribute.MARGIN_TOP);
styleConstantToCssMap.put(StyleConstants.SpaceBelow,
CSS.Attribute.MARGIN_BOTTOM);
styleConstantToCssMap.put(StyleConstants.Alignment,
CSS.Attribute.TEXT_ALIGN);
// HTML->CSS
htmlValueToCssValueMap.put("disc", CSS.Value.DISC);
htmlValueToCssValueMap.put("square", CSS.Value.SQUARE);
htmlValueToCssValueMap.put("circle", CSS.Value.CIRCLE);
htmlValueToCssValueMap.put("1", CSS.Value.DECIMAL);
htmlValueToCssValueMap.put("a", CSS.Value.LOWER_ALPHA);
htmlValueToCssValueMap.put("A", CSS.Value.UPPER_ALPHA);
htmlValueToCssValueMap.put("i", CSS.Value.LOWER_ROMAN);
htmlValueToCssValueMap.put("I", CSS.Value.UPPER_ROMAN);
// CSS-> internal CSS
cssValueToInternalValueMap.put("none", CSS.Value.NONE);
cssValueToInternalValueMap.put("disc", CSS.Value.DISC);
cssValueToInternalValueMap.put("square", CSS.Value.SQUARE);
cssValueToInternalValueMap.put("circle", CSS.Value.CIRCLE);
cssValueToInternalValueMap.put("decimal", CSS.Value.DECIMAL);
cssValueToInternalValueMap.put("lower-roman", CSS.Value.LOWER_ROMAN);
cssValueToInternalValueMap.put("upper-roman", CSS.Value.UPPER_ROMAN);
cssValueToInternalValueMap.put("lower-alpha", CSS.Value.LOWER_ALPHA);
cssValueToInternalValueMap.put("upper-alpha", CSS.Value.UPPER_ALPHA);
cssValueToInternalValueMap.put("repeat", CSS.Value.BACKGROUND_REPEAT);
cssValueToInternalValueMap.put("no-repeat",
CSS.Value.BACKGROUND_NO_REPEAT);
cssValueToInternalValueMap.put("repeat-x",
CSS.Value.BACKGROUND_REPEAT_X);
cssValueToInternalValueMap.put("repeat-y",
CSS.Value.BACKGROUND_REPEAT_Y);
cssValueToInternalValueMap.put("scroll",
CSS.Value.BACKGROUND_SCROLL);
cssValueToInternalValueMap.put("fixed",
CSS.Value.BACKGROUND_FIXED);
// Register all the CSS attribute keys for archival/unarchival
Object[] keys = CSS.Attribute.allAttributes;
try {
for (int i = 0; i < keys.length; i++) {
StyleContext.registerStaticAttributeKey(keys[i]);
}
} catch (Throwable e) {
e.printStackTrace();
}
// Register all the CSS Values for archival/unarchival
keys = CSS.Value.allValues;
try {
for (int i = 0; i < keys.length; i++) {
StyleContext.registerStaticAttributeKey(keys[i]);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
/** {@collect.stats}
* Return the set of all possible CSS attribute keys.
*/
public static Attribute[] getAllAttributeKeys() {
Attribute[] keys = new Attribute[Attribute.allAttributes.length];
System.arraycopy(Attribute.allAttributes, 0, keys, 0, Attribute.allAttributes.length);
return keys;
}
/** {@collect.stats}
* Translates a string to a <code>CSS.Attribute</code> object.
* This will return <code>null</code> if there is no attribute
* by the given name.
*
* @param name the name of the CSS attribute to fetch the
* typesafe enumeration for
* @return the <code>CSS.Attribute</code> object,
* or <code>null</code> if the string
* doesn't represent a valid attribute key
*/
public static final Attribute getAttribute(String name) {
return (Attribute) attributeMap.get(name);
}
/** {@collect.stats}
* Translates a string to a <code>CSS.Value</code> object.
* This will return <code>null</code> if there is no value
* by the given name.
*
* @param name the name of the CSS value to fetch the
* typesafe enumeration for
* @return the <code>CSS.Value</code> object,
* or <code>null</code> if the string
* doesn't represent a valid CSS value name; this does
* not mean that it doesn't represent a valid CSS value
*/
static final Value getValue(String name) {
return (Value) valueMap.get(name);
}
//
// Conversion related methods/classes
//
/** {@collect.stats}
* Returns a URL for the given CSS url string. If relative,
* <code>base</code> is used as the parent. If a valid URL can not
* be found, this will not throw a MalformedURLException, instead
* null will be returned.
*/
static URL getURL(URL base, String cssString) {
if (cssString == null) {
return null;
}
if (cssString.startsWith("url(") &&
cssString.endsWith(")")) {
cssString = cssString.substring(4, cssString.length() - 1);
}
// Absolute first
try {
URL url = new URL(cssString);
if (url != null) {
return url;
}
} catch (MalformedURLException mue) {
}
// Then relative
if (base != null) {
// Relative URL, try from base
try {
URL url = new URL(base, cssString);
return url;
}
catch (MalformedURLException muee) {
}
}
return null;
}
/** {@collect.stats}
* Converts a type Color to a hex string
* in the format "#RRGGBB"
*/
static String colorToHex(Color color) {
String colorstr = new String("#");
// Red
String str = Integer.toHexString(color.getRed());
if (str.length() > 2)
str = str.substring(0, 2);
else if (str.length() < 2)
colorstr += "0" + str;
else
colorstr += str;
// Green
str = Integer.toHexString(color.getGreen());
if (str.length() > 2)
str = str.substring(0, 2);
else if (str.length() < 2)
colorstr += "0" + str;
else
colorstr += str;
// Blue
str = Integer.toHexString(color.getBlue());
if (str.length() > 2)
str = str.substring(0, 2);
else if (str.length() < 2)
colorstr += "0" + str;
else
colorstr += str;
return colorstr;
}
/** {@collect.stats}
* Convert a "#FFFFFF" hex string to a Color.
* If the color specification is bad, an attempt
* will be made to fix it up.
*/
static final Color hexToColor(String value) {
String digits;
int n = value.length();
if (value.startsWith("#")) {
digits = value.substring(1, Math.min(value.length(), 7));
} else {
digits = value;
}
String hstr = "0x" + digits;
Color c;
try {
c = Color.decode(hstr);
} catch (NumberFormatException nfe) {
c = null;
}
return c;
}
/** {@collect.stats}
* Convert a color string such as "RED" or "#NNNNNN" or "rgb(r, g, b)"
* to a Color.
*/
static Color stringToColor(String str) {
Color color = null;
if (str.length() == 0)
color = Color.black;
else if (str.startsWith("rgb(")) {
color = parseRGB(str);
}
else if (str.charAt(0) == '#')
color = hexToColor(str);
else if (str.equalsIgnoreCase("Black"))
color = hexToColor("#000000");
else if(str.equalsIgnoreCase("Silver"))
color = hexToColor("#C0C0C0");
else if(str.equalsIgnoreCase("Gray"))
color = hexToColor("#808080");
else if(str.equalsIgnoreCase("White"))
color = hexToColor("#FFFFFF");
else if(str.equalsIgnoreCase("Maroon"))
color = hexToColor("#800000");
else if(str.equalsIgnoreCase("Red"))
color = hexToColor("#FF0000");
else if(str.equalsIgnoreCase("Purple"))
color = hexToColor("#800080");
else if(str.equalsIgnoreCase("Fuchsia"))
color = hexToColor("#FF00FF");
else if(str.equalsIgnoreCase("Green"))
color = hexToColor("#008000");
else if(str.equalsIgnoreCase("Lime"))
color = hexToColor("#00FF00");
else if(str.equalsIgnoreCase("Olive"))
color = hexToColor("#808000");
else if(str.equalsIgnoreCase("Yellow"))
color = hexToColor("#FFFF00");
else if(str.equalsIgnoreCase("Navy"))
color = hexToColor("#000080");
else if(str.equalsIgnoreCase("Blue"))
color = hexToColor("#0000FF");
else if(str.equalsIgnoreCase("Teal"))
color = hexToColor("#008080");
else if(str.equalsIgnoreCase("Aqua"))
color = hexToColor("#00FFFF");
else
color = hexToColor(str); // sometimes get specified without leading #
return color;
}
/** {@collect.stats}
* Parses a String in the format <code>rgb(r, g, b)</code> where
* each of the Color components is either an integer, or a floating number
* with a % after indicating a percentage value of 255. Values are
* constrained to fit with 0-255. The resulting Color is returned.
*/
private static Color parseRGB(String string) {
// Find the next numeric char
int[] index = new int[1];
index[0] = 4;
int red = getColorComponent(string, index);
int green = getColorComponent(string, index);
int blue = getColorComponent(string, index);
return new Color(red, green, blue);
}
/** {@collect.stats}
* Returns the next integer value from <code>string</code> starting
* at <code>index[0]</code>. The value can either can an integer, or
* a percentage (floating number ending with %), in which case it is
* multiplied by 255.
*/
private static int getColorComponent(String string, int[] index) {
int length = string.length();
char aChar;
// Skip non-decimal chars
while(index[0] < length && (aChar = string.charAt(index[0])) != '-' &&
!Character.isDigit(aChar) && aChar != '.') {
index[0]++;
}
int start = index[0];
if (start < length && string.charAt(index[0]) == '-') {
index[0]++;
}
while(index[0] < length &&
Character.isDigit(string.charAt(index[0]))) {
index[0]++;
}
if (index[0] < length && string.charAt(index[0]) == '.') {
// Decimal value
index[0]++;
while(index[0] < length &&
Character.isDigit(string.charAt(index[0]))) {
index[0]++;
}
}
if (start != index[0]) {
try {
float value = Float.parseFloat(string.substring
(start, index[0]));
if (index[0] < length && string.charAt(index[0]) == '%') {
index[0]++;
value = value * 255f / 100f;
}
return Math.min(255, Math.max(0, (int)value));
} catch (NumberFormatException nfe) {
// Treat as 0
}
}
return 0;
}
static int getIndexOfSize(float pt, int[] sizeMap) {
for (int i = 0; i < sizeMap.length; i ++ )
if (pt <= sizeMap[i])
return i + 1;
return sizeMap.length;
}
static int getIndexOfSize(float pt, StyleSheet ss) {
int[] sizeMap = (ss != null) ? ss.getSizeMap() :
StyleSheet.sizeMapDefault;
return getIndexOfSize(pt, sizeMap);
}
/** {@collect.stats}
* @return an array of all the strings in <code>value</code>
* that are separated by whitespace.
*/
static String[] parseStrings(String value) {
int current, last;
int length = (value == null) ? 0 : value.length();
Vector temp = new Vector(4);
current = 0;
while (current < length) {
// Skip ws
while (current < length && Character.isWhitespace
(value.charAt(current))) {
current++;
}
last = current;
while (current < length && !Character.isWhitespace
(value.charAt(current))) {
current++;
}
if (last != current) {
temp.addElement(value.substring(last, current));
}
current++;
}
String[] retValue = new String[temp.size()];
temp.copyInto(retValue);
return retValue;
}
/** {@collect.stats}
* Return the point size, given a size index. Legal HTML index sizes
* are 1-7.
*/
float getPointSize(int index, StyleSheet ss) {
ss = getStyleSheet(ss);
int[] sizeMap = (ss != null) ? ss.getSizeMap() :
StyleSheet.sizeMapDefault;
--index;
if (index < 0)
return sizeMap[0];
else if (index > sizeMap.length - 1)
return sizeMap[sizeMap.length - 1];
else
return sizeMap[index];
}
private void translateEmbeddedAttributes(AttributeSet htmlAttrSet,
MutableAttributeSet cssAttrSet) {
Enumeration keys = htmlAttrSet.getAttributeNames();
if (htmlAttrSet.getAttribute(StyleConstants.NameAttribute) ==
HTML.Tag.HR) {
// HR needs special handling due to us treating it as a leaf.
translateAttributes(HTML.Tag.HR, htmlAttrSet, cssAttrSet);
}
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof HTML.Tag) {
HTML.Tag tag = (HTML.Tag)key;
Object o = htmlAttrSet.getAttribute(tag);
if (o != null && o instanceof AttributeSet) {
translateAttributes(tag, (AttributeSet)o, cssAttrSet);
}
} else if (key instanceof CSS.Attribute) {
cssAttrSet.addAttribute(key, htmlAttrSet.getAttribute(key));
}
}
}
private void translateAttributes(HTML.Tag tag,
AttributeSet htmlAttrSet,
MutableAttributeSet cssAttrSet) {
Enumeration names = htmlAttrSet.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
if (name instanceof HTML.Attribute) {
HTML.Attribute key = (HTML.Attribute)name;
/*
* HTML.Attribute.ALIGN needs special processing.
* It can map to to 1 of many(3) possible CSS attributes
* depending on the nature of the tag the attribute is
* part off and depending on the value of the attribute.
*/
if (key == HTML.Attribute.ALIGN) {
String htmlAttrValue = (String)htmlAttrSet.getAttribute(HTML.Attribute.ALIGN);
if (htmlAttrValue != null) {
CSS.Attribute cssAttr = getCssAlignAttribute(tag, htmlAttrSet);
if (cssAttr != null) {
Object o = getCssValue(cssAttr, htmlAttrValue);
if (o != null) {
cssAttrSet.addAttribute(cssAttr, o);
}
}
}
} else {
/*
* The html size attribute has a mapping in the CSS world only
* if it is par of a font or base font tag.
*/
if (key == HTML.Attribute.SIZE && !isHTMLFontTag(tag)) {
continue;
}
translateAttribute(key, htmlAttrSet, cssAttrSet);
}
} else if (name instanceof CSS.Attribute) {
cssAttrSet.addAttribute(name, htmlAttrSet.getAttribute(name));
}
}
}
private void translateAttribute(HTML.Attribute key,
AttributeSet htmlAttrSet,
MutableAttributeSet cssAttrSet) {
/*
* In the case of all remaining HTML.Attribute's they
* map to 1 or more CCS.Attribute.
*/
CSS.Attribute[] cssAttrList = getCssAttribute(key);
String htmlAttrValue = (String)htmlAttrSet.getAttribute(key);
if (cssAttrList == null || htmlAttrValue == null) {
return;
}
for (int i = 0; i < cssAttrList.length; i++) {
Object o = getCssValue(cssAttrList[i], htmlAttrValue);
if (o != null) {
cssAttrSet.addAttribute(cssAttrList[i], o);
}
}
}
/** {@collect.stats}
* Given a CSS.Attribute object and its corresponding HTML.Attribute's
* value, this method returns a CssValue object to associate with the
* CSS attribute.
*
* @param the CSS.Attribute
* @param a String containing the value associated HTML.Attribtue.
*/
Object getCssValue(CSS.Attribute cssAttr, String htmlAttrValue) {
CssValue value = (CssValue)valueConvertor.get(cssAttr);
Object o = value.parseHtmlValue(htmlAttrValue);
return o;
}
/** {@collect.stats}
* Maps an HTML.Attribute object to its appropriate CSS.Attributes.
*
* @param HTML.Attribute
* @return CSS.Attribute[]
*/
private CSS.Attribute[] getCssAttribute(HTML.Attribute hAttr) {
return (CSS.Attribute[])htmlAttrToCssAttrMap.get(hAttr);
}
/** {@collect.stats}
* Maps HTML.Attribute.ALIGN to either:
* CSS.Attribute.TEXT_ALIGN
* CSS.Attribute.FLOAT
* CSS.Attribute.VERTICAL_ALIGN
* based on the tag associated with the attribute and the
* value of the attribute.
*
* @param AttributeSet containing HTML attributes.
* @return CSS.Attribute mapping for HTML.Attribute.ALIGN.
*/
private CSS.Attribute getCssAlignAttribute(HTML.Tag tag,
AttributeSet htmlAttrSet) {
return CSS.Attribute.TEXT_ALIGN;
/*
String htmlAttrValue = (String)htmlAttrSet.getAttribute(HTML.Attribute.ALIGN);
CSS.Attribute cssAttr = CSS.Attribute.TEXT_ALIGN;
if (htmlAttrValue != null && htmlAttrSet instanceof Element) {
Element elem = (Element)htmlAttrSet;
if (!elem.isLeaf() && tag.isBlock() && validTextAlignValue(htmlAttrValue)) {
return CSS.Attribute.TEXT_ALIGN;
} else if (isFloater(htmlAttrValue)) {
return CSS.Attribute.FLOAT;
} else if (elem.isLeaf()) {
return CSS.Attribute.VERTICAL_ALIGN;
}
}
return null;
*/
}
/** {@collect.stats}
* Fetches the tag associated with the HTML AttributeSet.
*
* @param AttributeSet containing the HTML attributes.
* @return HTML.Tag
*/
private HTML.Tag getHTMLTag(AttributeSet htmlAttrSet) {
Object o = htmlAttrSet.getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag tag = (HTML.Tag) o;
return tag;
}
return null;
}
private boolean isHTMLFontTag(HTML.Tag tag) {
return (tag != null && ((tag == HTML.Tag.FONT) || (tag == HTML.Tag.BASEFONT)));
}
private boolean isFloater(String alignValue) {
return (alignValue.equals("left") || alignValue.equals("right"));
}
private boolean validTextAlignValue(String alignValue) {
return (isFloater(alignValue) || alignValue.equals("center"));
}
/** {@collect.stats}
* Base class to CSS values in the attribute sets. This
* is intended to act as a convertor to/from other attribute
* formats.
* <p>
* The CSS parser uses the parseCssValue method to convert
* a string to whatever format is appropriate a given key
* (i.e. these convertors are stored in a map using the
* CSS.Attribute as a key and the CssValue as the value).
* <p>
* The HTML to CSS conversion process first converts the
* HTML.Attribute to a CSS.Attribute, and then calls
* the parseHtmlValue method on the value of the HTML
* attribute to produce the corresponding CSS value.
* <p>
* The StyleConstants to CSS conversion process first
* converts the StyleConstants attribute to a
* CSS.Attribute, and then calls the fromStyleConstants
* method to convert the StyleConstants value to a
* CSS value.
* <p>
* The CSS to StyleConstants conversion process first
* converts the StyleConstants attribute to a
* CSS.Attribute, and then calls the toStyleConstants
* method to convert the CSS value to a StyleConstants
* value.
*/
static class CssValue implements Serializable {
/** {@collect.stats}
* Convert a CSS value string to the internal format
* (for fast processing) used in the attribute sets.
* The fallback storage for any value that we don't
* have a special binary format for is a String.
*/
Object parseCssValue(String value) {
return value;
}
/** {@collect.stats}
* Convert an HTML attribute value to a CSS attribute
* value. If there is no conversion, return null.
* This is implemented to simply forward to the CSS
* parsing by default (since some of the attribute
* values are the same). If the attribute value
* isn't recognized as a CSS value it is generally
* returned as null.
*/
Object parseHtmlValue(String value) {
return parseCssValue(value);
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion,
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
return null;
}
/** {@collect.stats}
* Converts a CSS attribute value to a
* <code>StyleConstants</code>
* value. If there is no conversion, returns
* <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param v the view containing <code>AttributeSet</code>
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
return null;
}
/** {@collect.stats}
* Return the CSS format of the value
*/
public String toString() {
return svalue;
}
/** {@collect.stats}
* The value as a string... before conversion to a
* binary format.
*/
String svalue;
}
/** {@collect.stats}
* By default CSS attributes are represented as simple
* strings. They also have no conversion to/from
* StyleConstants by default. This class represents the
* value as a string (via the superclass), but
* provides StyleConstants conversion support for the
* CSS attributes that are held as strings.
*/
static class StringValue extends CssValue {
/** {@collect.stats}
* Convert a CSS value string to the internal format
* (for fast processing) used in the attribute sets.
* This produces a StringValue, so that it can be
* used to convert from CSS to StyleConstants values.
*/
Object parseCssValue(String value) {
StringValue sv = new StringValue();
sv.svalue = value;
return sv;
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion
* returns <code>null</code>.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
if (key == StyleConstants.Italic) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("italic");
}
return parseCssValue("");
} else if (key == StyleConstants.Underline) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("underline");
}
return parseCssValue("");
} else if (key == StyleConstants.Alignment) {
int align = ((Integer)value).intValue();
String ta;
switch(align) {
case StyleConstants.ALIGN_LEFT:
ta = "left";
break;
case StyleConstants.ALIGN_RIGHT:
ta = "right";
break;
case StyleConstants.ALIGN_CENTER:
ta = "center";
break;
case StyleConstants.ALIGN_JUSTIFIED:
ta = "justify";
break;
default:
ta = "left";
}
return parseCssValue(ta);
} else if (key == StyleConstants.StrikeThrough) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("line-through");
}
return parseCssValue("");
} else if (key == StyleConstants.Superscript) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("super");
}
return parseCssValue("");
} else if (key == StyleConstants.Subscript) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("sub");
}
return parseCssValue("");
}
return null;
}
/** {@collect.stats}
* Converts a CSS attribute value to a
* <code>StyleConstants</code> value.
* If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
if (key == StyleConstants.Italic) {
if (svalue.indexOf("italic") >= 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} else if (key == StyleConstants.Underline) {
if (svalue.indexOf("underline") >= 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} else if (key == StyleConstants.Alignment) {
if (svalue.equals("right")) {
return new Integer(StyleConstants.ALIGN_RIGHT);
} else if (svalue.equals("center")) {
return new Integer(StyleConstants.ALIGN_CENTER);
} else if (svalue.equals("justify")) {
return new Integer(StyleConstants.ALIGN_JUSTIFIED);
}
return new Integer(StyleConstants.ALIGN_LEFT);
} else if (key == StyleConstants.StrikeThrough) {
if (svalue.indexOf("line-through") >= 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} else if (key == StyleConstants.Superscript) {
if (svalue.indexOf("super") >= 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} else if (key == StyleConstants.Subscript) {
if (svalue.indexOf("sub") >= 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
return null;
}
// Used by ViewAttributeSet
boolean isItalic() {
return (svalue.indexOf("italic") != -1);
}
boolean isStrike() {
return (svalue.indexOf("line-through") != -1);
}
boolean isUnderline() {
return (svalue.indexOf("underline") != -1);
}
boolean isSub() {
return (svalue.indexOf("sub") != -1);
}
boolean isSup() {
return (svalue.indexOf("sup") != -1);
}
}
/** {@collect.stats}
* Represents a value for the CSS.FONT_SIZE attribute.
* The binary format of the value can be one of several
* types. If the type is Float,
* the value is specified in terms of point or
* percentage, depending upon the ending of the
* associated string.
* If the type is Integer, the value is specified
* in terms of a size index.
*/
class FontSize extends CssValue {
/** {@collect.stats}
* Returns the size in points. This is ultimately
* what we need for the purpose of creating/fetching
* a Font object.
*
* @param a the attribute set the value is being
* requested from. We may need to walk up the
* resolve hierarchy if it's relative.
*/
int getValue(AttributeSet a, StyleSheet ss) {
ss = getStyleSheet(ss);
if (index) {
// it's an index, translate from size table
return Math.round(getPointSize((int) value, ss));
}
else if (lu == null) {
return Math.round(value);
}
else {
if (lu.type == 0) {
boolean isW3CLengthUnits = (ss == null) ? false : ss.isW3CLengthUnits();
return Math.round(lu.getValue(isW3CLengthUnits));
}
if (a != null) {
AttributeSet resolveParent = a.getResolveParent();
if (resolveParent != null) {
int pValue = StyleConstants.getFontSize(resolveParent);
float retValue;
if (lu.type == 1 || lu.type == 3) {
retValue = lu.value * (float)pValue;
}
else {
retValue = lu.value + (float)pValue;
}
return Math.round(retValue);
}
}
// a is null, or no resolve parent.
return 12;
}
}
Object parseCssValue(String value) {
FontSize fs = new FontSize();
fs.svalue = value;
try {
if (value.equals("xx-small")) {
fs.value = 1;
fs.index = true;
} else if (value.equals("x-small")) {
fs.value = 2;
fs.index = true;
} else if (value.equals("small")) {
fs.value = 3;
fs.index = true;
} else if (value.equals("medium")) {
fs.value = 4;
fs.index = true;
} else if (value.equals("large")) {
fs.value = 5;
fs.index = true;
} else if (value.equals("x-large")) {
fs.value = 6;
fs.index = true;
} else if (value.equals("xx-large")) {
fs.value = 7;
fs.index = true;
} else {
fs.lu = new LengthUnit(value, (short)1, 1f);
}
// relative sizes, larger | smaller (adjust from parent by
// 1.5 pixels)
// em, ex refer to parent sizes
// lengths: pt, mm, cm, pc, in, px
// em (font height 3em would be 3 times font height)
// ex (height of X)
// lengths are (+/-) followed by a number and two letter
// unit identifier
} catch (NumberFormatException nfe) {
fs = null;
}
return fs;
}
Object parseHtmlValue(String value) {
if ((value == null) || (value.length() == 0)) {
return null;
}
FontSize fs = new FontSize();
fs.svalue = value;
try {
/*
* relative sizes in the size attribute are relative
* to the <basefont>'s size.
*/
int baseFontSize = getBaseFontSize();
if (value.charAt(0) == '+') {
int relSize = Integer.valueOf(value.substring(1)).intValue();
fs.value = baseFontSize + relSize;
fs.index = true;
} else if (value.charAt(0) == '-') {
int relSize = -Integer.valueOf(value.substring(1)).intValue();
fs.value = baseFontSize + relSize;
fs.index = true;
} else {
fs.value = Integer.parseInt(value);
if (fs.value > 7) {
fs.value = 7;
} else if (fs.value < 0) {
fs.value = 0;
}
fs.index = true;
}
} catch (NumberFormatException nfe) {
fs = null;
}
return fs;
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
if (value instanceof Number) {
FontSize fs = new FontSize();
fs.value = getIndexOfSize(((Number)value).floatValue(), StyleSheet.sizeMapDefault);
fs.svalue = Integer.toString((int)fs.value);
fs.index = true;
return fs;
}
return parseCssValue(value.toString());
}
/** {@collect.stats}
* Converts a CSS attribute value to a <code>StyleConstants</code>
* value. If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
if (v != null) {
return Integer.valueOf(getValue(v.getAttributes(), null));
}
return Integer.valueOf(getValue(null, null));
}
float value;
boolean index;
LengthUnit lu;
}
static class FontFamily extends CssValue {
/** {@collect.stats}
* Returns the font family to use.
*/
String getValue() {
return family;
}
Object parseCssValue(String value) {
int cIndex = value.indexOf(',');
FontFamily ff = new FontFamily();
ff.svalue = value;
ff.family = null;
if (cIndex == -1) {
setFontName(ff, value);
}
else {
boolean done = false;
int lastIndex;
int length = value.length();
cIndex = 0;
while (!done) {
// skip ws.
while (cIndex < length &&
Character.isWhitespace(value.charAt(cIndex)))
cIndex++;
// Find next ','
lastIndex = cIndex;
cIndex = value.indexOf(',', cIndex);
if (cIndex == -1) {
cIndex = length;
}
if (lastIndex < length) {
if (lastIndex != cIndex) {
int lastCharIndex = cIndex;
if (cIndex > 0 && value.charAt(cIndex - 1) == ' '){
lastCharIndex--;
}
setFontName(ff, value.substring
(lastIndex, lastCharIndex));
done = (ff.family != null);
}
cIndex++;
}
else {
done = true;
}
}
}
if (ff.family == null) {
ff.family = Font.SANS_SERIF;
}
return ff;
}
private void setFontName(FontFamily ff, String fontName) {
ff.family = fontName;
}
Object parseHtmlValue(String value) {
// TBD
return parseCssValue(value);
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
return parseCssValue(value.toString());
}
/** {@collect.stats}
* Converts a CSS attribute value to a <code>StyleConstants</code>
* value. If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
return family;
}
String family;
}
static class FontWeight extends CssValue {
int getValue() {
return weight;
}
Object parseCssValue(String value) {
FontWeight fw = new FontWeight();
fw.svalue = value;
if (value.equals("bold")) {
fw.weight = 700;
} else if (value.equals("normal")) {
fw.weight = 400;
} else {
// PENDING(prinz) add support for relative values
try {
fw.weight = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
fw = null;
}
}
return fw;
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
if (value.equals(Boolean.TRUE)) {
return parseCssValue("bold");
}
return parseCssValue("normal");
}
/** {@collect.stats}
* Converts a CSS attribute value to a <code>StyleConstants</code>
* value. If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
return (weight > 500) ? Boolean.TRUE : Boolean.FALSE;
}
boolean isBold() {
return (weight > 500);
}
int weight;
}
static class ColorValue extends CssValue {
/** {@collect.stats}
* Returns the color to use.
*/
Color getValue() {
return c;
}
Object parseCssValue(String value) {
Color c = stringToColor(value);
if (c != null) {
ColorValue cv = new ColorValue();
cv.svalue = value;
cv.c = c;
return cv;
}
return null;
}
Object parseHtmlValue(String value) {
return parseCssValue(value);
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
ColorValue colorValue = new ColorValue();
colorValue.c = (Color)value;
colorValue.svalue = colorToHex(colorValue.c);
return colorValue;
}
/** {@collect.stats}
* Converts a CSS attribute value to a <code>StyleConstants</code>
* value. If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
return c;
}
Color c;
}
static class BorderStyle extends CssValue {
CSS.Value getValue() {
return style;
}
Object parseCssValue(String value) {
CSS.Value cssv = CSS.getValue(value);
if (cssv != null) {
if ((cssv == CSS.Value.INSET) ||
(cssv == CSS.Value.OUTSET) ||
(cssv == CSS.Value.NONE) ||
(cssv == CSS.Value.DOTTED) ||
(cssv == CSS.Value.DASHED) ||
(cssv == CSS.Value.SOLID) ||
(cssv == CSS.Value.DOUBLE) ||
(cssv == CSS.Value.GROOVE) ||
(cssv == CSS.Value.RIDGE)) {
BorderStyle bs = new BorderStyle();
bs.svalue = value;
bs.style = cssv;
return bs;
}
}
return null;
}
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
s.defaultWriteObject();
if (style == null) {
s.writeObject(null);
}
else {
s.writeObject(style.toString());
}
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
Object value = s.readObject();
if (value != null) {
style = CSS.getValue((String)value);
}
}
// CSS.Values are static, don't archive it.
transient private CSS.Value style;
}
static class LengthValue extends CssValue {
/** {@collect.stats}
* if this length value may be negative.
*/
boolean mayBeNegative;
LengthValue() {
this(false);
}
LengthValue(boolean mayBeNegative) {
this.mayBeNegative = mayBeNegative;
}
/** {@collect.stats}
* Returns the length (span) to use.
*/
float getValue() {
return getValue(false);
}
float getValue(boolean isW3CLengthUnits) {
return getValue(0, isW3CLengthUnits);
}
/** {@collect.stats}
* Returns the length (span) to use. If the value represents
* a percentage, it is scaled based on <code>currentValue</code>.
*/
float getValue(float currentValue) {
return getValue(currentValue, false);
}
float getValue(float currentValue, boolean isW3CLengthUnits) {
if (percentage) {
return span * currentValue;
}
return LengthUnit.getValue(span, units, isW3CLengthUnits);
}
/** {@collect.stats}
* Returns true if the length represents a percentage of the
* containing box.
*/
boolean isPercentage() {
return percentage;
}
Object parseCssValue(String value) {
LengthValue lv;
try {
// Assume pixels
float absolute = Float.valueOf(value).floatValue();
lv = new LengthValue();
lv.span = absolute;
} catch (NumberFormatException nfe) {
// Not pixels, use LengthUnit
LengthUnit lu = new LengthUnit(value,
LengthUnit.UNINITALIZED_LENGTH,
0);
// PENDING: currently, we only support absolute values and
// percentages.
switch (lu.type) {
case 0:
// Absolute
lv = new LengthValue();
lv.span =
(mayBeNegative) ? lu.value : Math.max(0, lu.value);
lv.units = lu.units;
break;
case 1:
// %
lv = new LengthValue();
lv.span = Math.max(0, Math.min(1, lu.value));
lv.percentage = true;
break;
default:
return null;
}
}
lv.svalue = value;
return lv;
}
Object parseHtmlValue(String value) {
if (value.equals(HTML.NULL_ATTRIBUTE_VALUE)) {
value = "1";
}
return parseCssValue(value);
}
/** {@collect.stats}
* Converts a <code>StyleConstants</code> attribute value to
* a CSS attribute value. If there is no conversion,
* returns <code>null</code>. By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @param value the value of a <code>StyleConstants</code>
* attribute to be converted
* @return the CSS value that represents the
* <code>StyleConstants</code> value
*/
Object fromStyleConstants(StyleConstants key, Object value) {
LengthValue v = new LengthValue();
v.svalue = value.toString();
v.span = ((Float)value).floatValue();
return v;
}
/** {@collect.stats}
* Converts a CSS attribute value to a <code>StyleConstants</code>
* value. If there is no conversion, returns <code>null</code>.
* By default, there is no conversion.
*
* @param key the <code>StyleConstants</code> attribute
* @return the <code>StyleConstants</code> attribute value that
* represents the CSS attribute value
*/
Object toStyleConstants(StyleConstants key, View v) {
return new Float(getValue(false));
}
/** {@collect.stats} If true, span is a percentage value, and that to determine
* the length another value needs to be passed in. */
boolean percentage;
/** {@collect.stats} Either the absolute value (percentage == false) or
* a percentage value. */
float span;
String units = null;
}
/** {@collect.stats}
* BorderWidthValue is used to model BORDER_XXX_WIDTH and adds support
* for the thin/medium/thick values.
*/
static class BorderWidthValue extends LengthValue {
BorderWidthValue(String svalue, int index) {
this.svalue = svalue;
span = values[index];
percentage = false;
}
Object parseCssValue(String value) {
if (value != null) {
if (value.equals("thick")) {
return new BorderWidthValue(value, 2);
}
else if (value.equals("medium")) {
return new BorderWidthValue(value, 1);
}
else if (value.equals("thin")) {
return new BorderWidthValue(value, 0);
}
}
// Assume its a length.
return super.parseCssValue(value);
}
Object parseHtmlValue(String value) {
if (value == HTML.NULL_ATTRIBUTE_VALUE) {
return parseCssValue("medium");
}
return parseCssValue(value);
}
/** {@collect.stats} Values used to represent border width. */
private static final float[] values = { 1, 2, 4 };
}
/** {@collect.stats}
* Handles uniquing of CSS values, like lists, and background image
* repeating.
*/
static class CssValueMapper extends CssValue {
Object parseCssValue(String value) {
Object retValue = cssValueToInternalValueMap.get(value);
if (retValue == null) {
retValue = cssValueToInternalValueMap.get(value.toLowerCase());
}
return retValue;
}
Object parseHtmlValue(String value) {
Object retValue = htmlValueToCssValueMap.get(value);
if (retValue == null) {
retValue = htmlValueToCssValueMap.get(value.toLowerCase());
}
return retValue;
}
}
/** {@collect.stats}
* Used for background images, to represent the position.
*/
static class BackgroundPosition extends CssValue {
float horizontalPosition;
float verticalPosition;
// bitmask: bit 0, horizontal relative, bit 1 horizontal relative to
// font size, 2 vertical relative to size, 3 vertical relative to
// font size.
//
short relative;
Object parseCssValue(String value) {
// 'top left' and 'left top' both mean the same as '0% 0%'.
// 'top', 'top center' and 'center top' mean the same as '50% 0%'.
// 'right top' and 'top right' mean the same as '100% 0%'.
// 'left', 'left center' and 'center left' mean the same as
// '0% 50%'.
// 'center' and 'center center' mean the same as '50% 50%'.
// 'right', 'right center' and 'center right' mean the same as
// '100% 50%'.
// 'bottom left' and 'left bottom' mean the same as '0% 100%'.
// 'bottom', 'bottom center' and 'center bottom' mean the same as
// '50% 100%'.
// 'bottom right' and 'right bottom' mean the same as '100% 100%'.
String[] strings = CSS.parseStrings(value);
int count = strings.length;
BackgroundPosition bp = new BackgroundPosition();
bp.relative = 5;
bp.svalue = value;
if (count > 0) {
// bit 0 for vert, 1 hor, 2 for center
short found = 0;
int index = 0;
while (index < count) {
// First, check for keywords
String string = strings[index++];
if (string.equals("center")) {
found |= 4;
continue;
}
else {
if ((found & 1) == 0) {
if (string.equals("top")) {
found |= 1;
}
else if (string.equals("bottom")) {
found |= 1;
bp.verticalPosition = 1;
continue;
}
}
if ((found & 2) == 0) {
if (string.equals("left")) {
found |= 2;
bp.horizontalPosition = 0;
}
else if (string.equals("right")) {
found |= 2;
bp.horizontalPosition = 1;
}
}
}
}
if (found != 0) {
if ((found & 1) == 1) {
if ((found & 2) == 0) {
// vert and no horiz.
bp.horizontalPosition = .5f;
}
}
else if ((found & 2) == 2) {
// horiz and no vert.
bp.verticalPosition = .5f;
}
else {
// no horiz, no vert, but center
bp.horizontalPosition = bp.verticalPosition = .5f;
}
}
else {
// Assume lengths
LengthUnit lu = new LengthUnit(strings[0], (short)0, 0f);
if (lu.type == 0) {
bp.horizontalPosition = lu.value;
bp.relative = (short)(1 ^ bp.relative);
}
else if (lu.type == 1) {
bp.horizontalPosition = lu.value;
}
else if (lu.type == 3) {
bp.horizontalPosition = lu.value;
bp.relative = (short)((1 ^ bp.relative) | 2);
}
if (count > 1) {
lu = new LengthUnit(strings[1], (short)0, 0f);
if (lu.type == 0) {
bp.verticalPosition = lu.value;
bp.relative = (short)(4 ^ bp.relative);
}
else if (lu.type == 1) {
bp.verticalPosition = lu.value;
}
else if (lu.type == 3) {
bp.verticalPosition = lu.value;
bp.relative = (short)((4 ^ bp.relative) | 8);
}
}
else {
bp.verticalPosition = .5f;
}
}
}
return bp;
}
boolean isHorizontalPositionRelativeToSize() {
return ((relative & 1) == 1);
}
boolean isHorizontalPositionRelativeToFontSize() {
return ((relative & 2) == 2);
}
float getHorizontalPosition() {
return horizontalPosition;
}
boolean isVerticalPositionRelativeToSize() {
return ((relative & 4) == 4);
}
boolean isVerticalPositionRelativeToFontSize() {
return ((relative & 8) == 8);
}
float getVerticalPosition() {
return verticalPosition;
}
}
/** {@collect.stats}
* Used for BackgroundImages.
*/
static class BackgroundImage extends CssValue {
private boolean loadedImage;
private ImageIcon image;
Object parseCssValue(String value) {
BackgroundImage retValue = new BackgroundImage();
retValue.svalue = value;
return retValue;
}
Object parseHtmlValue(String value) {
return parseCssValue(value);
}
// PENDING: this base is wrong for linked style sheets.
ImageIcon getImage(URL base) {
if (!loadedImage) {
synchronized(this) {
if (!loadedImage) {
URL url = CSS.getURL(base, svalue);
loadedImage = true;
if (url != null) {
image = new ImageIcon();
Image tmpImg = Toolkit.getDefaultToolkit().createImage(url);
if (tmpImg != null) {
image.setImage(tmpImg);
}
}
}
}
}
return image;
}
}
/** {@collect.stats}
* Parses a length value, this is used internally, and never added
* to an AttributeSet or returned to the developer.
*/
static class LengthUnit implements Serializable {
static Hashtable lengthMapping = new Hashtable(6);
static Hashtable w3cLengthMapping = new Hashtable(6);
static {
lengthMapping.put("pt", new Float(1f));
// Not sure about 1.3, determined by experiementation.
lengthMapping.put("px", new Float(1.3f));
lengthMapping.put("mm", new Float(2.83464f));
lengthMapping.put("cm", new Float(28.3464f));
lengthMapping.put("pc", new Float(12f));
lengthMapping.put("in", new Float(72f));
int res = 72;
try {
res = Toolkit.getDefaultToolkit().getScreenResolution();
} catch (HeadlessException e) {
}
// mapping according to the CSS2 spec
w3cLengthMapping.put("pt", new Float(res/72f));
w3cLengthMapping.put("px", new Float(1f));
w3cLengthMapping.put("mm", new Float(res/25.4f));
w3cLengthMapping.put("cm", new Float(res/2.54f));
w3cLengthMapping.put("pc", new Float(res/6f));
w3cLengthMapping.put("in", new Float(res));
}
LengthUnit(String value, short defaultType, float defaultValue) {
parse(value, defaultType, defaultValue);
}
void parse(String value, short defaultType, float defaultValue) {
type = defaultType;
this.value = defaultValue;
int length = value.length();
if (length > 0 && value.charAt(length - 1) == '%') {
try {
this.value = Float.valueOf(value.substring(0, length - 1)).
floatValue() / 100.0f;
type = 1;
}
catch (NumberFormatException nfe) { }
}
if (length >= 2) {
units = value.substring(length - 2, length);
Float scale = (Float)lengthMapping.get(units);
if (scale != null) {
try {
this.value = Float.valueOf(value.substring(0,
length - 2)).floatValue();
type = 0;
}
catch (NumberFormatException nfe) { }
}
else if (units.equals("em") ||
units.equals("ex")) {
try {
this.value = Float.valueOf(value.substring(0,
length - 2)).floatValue();
type = 3;
}
catch (NumberFormatException nfe) { }
}
else if (value.equals("larger")) {
this.value = 2f;
type = 2;
}
else if (value.equals("smaller")) {
this.value = -2;
type = 2;
}
else {
// treat like points.
try {
this.value = Float.valueOf(value).floatValue();
type = 0;
} catch (NumberFormatException nfe) {}
}
}
else if (length > 0) {
// treat like points.
try {
this.value = Float.valueOf(value).floatValue();
type = 0;
} catch (NumberFormatException nfe) {}
}
}
float getValue(boolean w3cLengthUnits) {
Hashtable mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
float scale = 1;
if (units != null) {
Float scaleFloat = (Float)mapping.get(units);
if (scaleFloat != null) {
scale = scaleFloat.floatValue();
}
}
return this.value * scale;
}
static float getValue(float value, String units, Boolean w3cLengthUnits) {
Hashtable mapping = (w3cLengthUnits) ? w3cLengthMapping : lengthMapping;
float scale = 1;
if (units != null) {
Float scaleFloat = (Float)mapping.get(units);
if (scaleFloat != null) {
scale = scaleFloat.floatValue();
}
}
return value * scale;
}
public String toString() {
return type + " " + value;
}
// 0 - value indicates real value
// 1 - % value, value relative to depends upon key.
// 50% will have a value = .5
// 2 - add value to parent value.
// 3 - em/ex relative to font size of element (except for
// font-size, which is relative to parent).
short type;
float value;
String units = null;
static final short UNINITALIZED_LENGTH = (short)10;
}
/** {@collect.stats}
* Class used to parse font property. The font property is shorthand
* for the other font properties. This expands the properties, placing
* them in the attributeset.
*/
static class ShorthandFontParser {
/** {@collect.stats}
* Parses the shorthand font string <code>value</code>, placing the
* result in <code>attr</code>.
*/
static void parseShorthandFont(CSS css, String value,
MutableAttributeSet attr) {
// font is of the form:
// [ <font-style> || <font-variant> || <font-weight> ]? <font-size>
// [ / <line-height> ]? <font-family>
String[] strings = CSS.parseStrings(value);
int count = strings.length;
int index = 0;
// bitmask, 1 for style, 2 for variant, 3 for weight
short found = 0;
int maxC = Math.min(3, count);
// Check for font-style font-variant font-weight
while (index < maxC) {
if ((found & 1) == 0 && isFontStyle(strings[index])) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_STYLE,
strings[index++]);
found |= 1;
}
else if ((found & 2) == 0 && isFontVariant(strings[index])) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_VARIANT,
strings[index++]);
found |= 2;
}
else if ((found & 4) == 0 && isFontWeight(strings[index])) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_WEIGHT,
strings[index++]);
found |= 4;
}
else if (strings[index].equals("normal")) {
index++;
}
else {
break;
}
}
if ((found & 1) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_STYLE,
"normal");
}
if ((found & 2) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_VARIANT,
"normal");
}
if ((found & 4) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_WEIGHT,
"normal");
}
// string at index should be the font-size
if (index < count) {
String fontSize = strings[index];
int slashIndex = fontSize.indexOf('/');
if (slashIndex != -1) {
fontSize = fontSize.substring(0, slashIndex);
strings[index] = strings[index].substring(slashIndex);
}
else {
index++;
}
css.addInternalCSSValue(attr, CSS.Attribute.FONT_SIZE,
fontSize);
}
else {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_SIZE,
"medium");
}
// Check for line height
if (index < count && strings[index].startsWith("/")) {
String lineHeight = null;
if (strings[index].equals("/")) {
if (++index < count) {
lineHeight = strings[index++];
}
}
else {
lineHeight = strings[index++].substring(1);
}
// line height
if (lineHeight != null) {
css.addInternalCSSValue(attr, CSS.Attribute.LINE_HEIGHT,
lineHeight);
}
else {
css.addInternalCSSValue(attr, CSS.Attribute.LINE_HEIGHT,
"normal");
}
}
else {
css.addInternalCSSValue(attr, CSS.Attribute.LINE_HEIGHT,
"normal");
}
// remainder of strings are font-family
if (index < count) {
String family = strings[index++];
while (index < count) {
family += " " + strings[index++];
}
css.addInternalCSSValue(attr, CSS.Attribute.FONT_FAMILY,
family);
}
else {
css.addInternalCSSValue(attr, CSS.Attribute.FONT_FAMILY,
Font.SANS_SERIF);
}
}
private static boolean isFontStyle(String string) {
return (string.equals("italic") ||
string.equals("oblique"));
}
private static boolean isFontVariant(String string) {
return (string.equals("small-caps"));
}
private static boolean isFontWeight(String string) {
if (string.equals("bold") || string.equals("bolder") ||
string.equals("italic") || string.equals("lighter")) {
return true;
}
// test for 100-900
return (string.length() == 3 &&
string.charAt(0) >= '1' && string.charAt(0) <= '9' &&
string.charAt(1) == '0' && string.charAt(2) == '0');
}
}
/** {@collect.stats}
* Parses the background property into its intrinsic values.
*/
static class ShorthandBackgroundParser {
/** {@collect.stats}
* Parses the shorthand font string <code>value</code>, placing the
* result in <code>attr</code>.
*/
static void parseShorthandBackground(CSS css, String value,
MutableAttributeSet attr) {
String[] strings = parseStrings(value);
int count = strings.length;
int index = 0;
// bitmask: 0 for image, 1 repeat, 2 attachment, 3 position,
// 4 color
short found = 0;
while (index < count) {
String string = strings[index++];
if ((found & 1) == 0 && isImage(string)) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_IMAGE, string);
found |= 1;
}
else if ((found & 2) == 0 && isRepeat(string)) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_REPEAT, string);
found |= 2;
}
else if ((found & 4) == 0 && isAttachment(string)) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_ATTACHMENT, string);
found |= 4;
}
else if ((found & 8) == 0 && isPosition(string)) {
if (index < count && isPosition(strings[index])) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_POSITION,
string + " " +
strings[index++]);
}
else {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_POSITION, string);
}
found |= 8;
}
else if ((found & 16) == 0 && isColor(string)) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_COLOR, string);
found |= 16;
}
}
if ((found & 1) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.BACKGROUND_IMAGE,
null);
}
if ((found & 2) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.BACKGROUND_REPEAT,
"repeat");
}
if ((found & 4) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_ATTACHMENT, "scroll");
}
if ((found & 8) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.
BACKGROUND_POSITION, null);
}
// Currently, there is no good way to express this.
/*
if ((found & 16) == 0) {
css.addInternalCSSValue(attr, CSS.Attribute.BACKGROUND_COLOR,
null);
}
*/
}
static boolean isImage(String string) {
return (string.startsWith("url(") && string.endsWith(")"));
}
static boolean isRepeat(String string) {
return (string.equals("repeat-x") || string.equals("repeat-y") ||
string.equals("repeat") || string.equals("no-repeat"));
}
static boolean isAttachment(String string) {
return (string.equals("fixed") || string.equals("scroll"));
}
static boolean isPosition(String string) {
return (string.equals("top") || string.equals("bottom") ||
string.equals("left") || string.equals("right") ||
string.equals("center") ||
(string.length() > 0 &&
Character.isDigit(string.charAt(0))));
}
static boolean isColor(String string) {
return (CSS.stringToColor(string) != null);
}
}
/** {@collect.stats}
* Used to parser margin and padding.
*/
static class ShorthandMarginParser {
/** {@collect.stats}
* Parses the shorthand margin/padding/border string
* <code>value</code>, placing the result in <code>attr</code>.
* <code>names</code> give the 4 instrinsic property names.
*/
static void parseShorthandMargin(CSS css, String value,
MutableAttributeSet attr,
CSS.Attribute[] names) {
String[] strings = parseStrings(value);
int count = strings.length;
int index = 0;
switch (count) {
case 0:
// empty string
return;
case 1:
// Identifies all values.
for (int counter = 0; counter < 4; counter++) {
css.addInternalCSSValue(attr, names[counter], strings[0]);
}
break;
case 2:
// 0 & 2 = strings[0], 1 & 3 = strings[1]
css.addInternalCSSValue(attr, names[0], strings[0]);
css.addInternalCSSValue(attr, names[2], strings[0]);
css.addInternalCSSValue(attr, names[1], strings[1]);
css.addInternalCSSValue(attr, names[3], strings[1]);
break;
case 3:
css.addInternalCSSValue(attr, names[0], strings[0]);
css.addInternalCSSValue(attr, names[1], strings[1]);
css.addInternalCSSValue(attr, names[2], strings[2]);
css.addInternalCSSValue(attr, names[3], strings[1]);
break;
default:
for (int counter = 0; counter < 4; counter++) {
css.addInternalCSSValue(attr, names[counter],
strings[counter]);
}
break;
}
}
}
/** {@collect.stats}
* Calculate the requirements needed to tile the requirements
* given by the iterator that would be tiled. The calculation
* takes into consideration margin and border spacing.
*/
static SizeRequirements calculateTiledRequirements(LayoutIterator iter, SizeRequirements r) {
long minimum = 0;
long maximum = 0;
long preferred = 0;
int lastMargin = 0;
int totalSpacing = 0;
int n = iter.getCount();
for (int i = 0; i < n; i++) {
iter.setIndex(i);
int margin0 = lastMargin;
int margin1 = (int) iter.getLeadingCollapseSpan();
totalSpacing += Math.max(margin0, margin1);;
preferred += (int) iter.getPreferredSpan(0);
minimum += iter.getMinimumSpan(0);
maximum += iter.getMaximumSpan(0);
lastMargin = (int) iter.getTrailingCollapseSpan();
}
totalSpacing += lastMargin;
totalSpacing += 2 * iter.getBorderWidth();
// adjust for the spacing area
minimum += totalSpacing;
preferred += totalSpacing;
maximum += totalSpacing;
// set return value
if (r == null) {
r = new SizeRequirements();
}
r.minimum = (minimum > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)minimum;
r.preferred = (preferred > Integer.MAX_VALUE) ? Integer.MAX_VALUE :(int) preferred;
r.maximum = (maximum > Integer.MAX_VALUE) ? Integer.MAX_VALUE :(int) maximum;
return r;
}
/** {@collect.stats}
* Calculate a tiled layout for the given iterator.
* This should be done collapsing the neighboring
* margins to be a total of the maximum of the two
* neighboring margin areas as described in the CSS spec.
*/
static void calculateTiledLayout(LayoutIterator iter, int targetSpan) {
/*
* first pass, calculate the preferred sizes, adjustments needed because
* of margin collapsing, and the flexibility to adjust the sizes.
*/
long preferred = 0;
long currentPreferred = 0;
int lastMargin = 0;
int totalSpacing = 0;
int n = iter.getCount();
int adjustmentWeightsCount = LayoutIterator.WorstAdjustmentWeight + 1;
//max gain we can get adjusting elements with adjustmentWeight <= i
long gain[] = new long[adjustmentWeightsCount];
//max loss we can get adjusting elements with adjustmentWeight <= i
long loss[] = new long[adjustmentWeightsCount];
for (int i = 0; i < adjustmentWeightsCount; i++) {
gain[i] = loss[i] = 0;
}
for (int i = 0; i < n; i++) {
iter.setIndex(i);
int margin0 = lastMargin;
int margin1 = (int) iter.getLeadingCollapseSpan();
iter.setOffset(Math.max(margin0, margin1));
totalSpacing += iter.getOffset();
currentPreferred = (long)iter.getPreferredSpan(targetSpan);
iter.setSpan((int) currentPreferred);
preferred += currentPreferred;
gain[iter.getAdjustmentWeight()] +=
(long)iter.getMaximumSpan(targetSpan) - currentPreferred;
loss[iter.getAdjustmentWeight()] +=
currentPreferred - (long)iter.getMinimumSpan(targetSpan);
lastMargin = (int) iter.getTrailingCollapseSpan();
}
totalSpacing += lastMargin;
totalSpacing += 2 * iter.getBorderWidth();
for (int i = 1; i < adjustmentWeightsCount; i++) {
gain[i] += gain[i - 1];
loss[i] += loss[i - 1];
}
/*
* Second pass, expand or contract by as much as possible to reach
* the target span. This takes the margin collapsing into account
* prior to adjusting the span.
*/
// determine the adjustment to be made
int allocated = targetSpan - totalSpacing;
long desiredAdjustment = allocated - preferred;
long adjustmentsArray[] = (desiredAdjustment > 0) ? gain : loss;
desiredAdjustment = Math.abs(desiredAdjustment);
int adjustmentLevel = 0;
for (;adjustmentLevel <= LayoutIterator.WorstAdjustmentWeight;
adjustmentLevel++) {
// adjustmentsArray[] is sorted. I do not bother about
// binary search though
if (adjustmentsArray[adjustmentLevel] >= desiredAdjustment) {
break;
}
}
float adjustmentFactor = 0.0f;
if (adjustmentLevel <= LayoutIterator.WorstAdjustmentWeight) {
desiredAdjustment -= (adjustmentLevel > 0) ?
adjustmentsArray[adjustmentLevel - 1] : 0;
if (desiredAdjustment != 0) {
float maximumAdjustment =
adjustmentsArray[adjustmentLevel] -
((adjustmentLevel > 0) ?
adjustmentsArray[adjustmentLevel - 1] : 0
);
adjustmentFactor = desiredAdjustment / maximumAdjustment;
}
}
// make the adjustments
int totalOffset = (int)iter.getBorderWidth();;
for (int i = 0; i < n; i++) {
iter.setIndex(i);
iter.setOffset( iter.getOffset() + totalOffset);
if (iter.getAdjustmentWeight() < adjustmentLevel) {
iter.setSpan((int)
((allocated > preferred) ?
Math.floor(iter.getMaximumSpan(targetSpan)) :
Math.ceil(iter.getMinimumSpan(targetSpan))
)
);
} else if (iter.getAdjustmentWeight() == adjustmentLevel) {
int availableSpan = (allocated > preferred) ?
(int) iter.getMaximumSpan(targetSpan) - iter.getSpan() :
iter.getSpan() - (int) iter.getMinimumSpan(targetSpan);
int adj = (int)Math.floor(adjustmentFactor * availableSpan);
iter.setSpan(iter.getSpan() +
((allocated > preferred) ? adj : -adj));
}
totalOffset = (int) Math.min((long) iter.getOffset() +
(long) iter.getSpan(),
Integer.MAX_VALUE);
}
// while rounding we could lose several pixels.
int roundError = targetSpan - totalOffset -
(int)iter.getTrailingCollapseSpan() -
(int)iter.getBorderWidth();
int adj = (roundError > 0) ? 1 : -1;
roundError *= adj;
boolean canAdjust = true;
while (roundError > 0 && canAdjust) {
// check for infinite loop
canAdjust = false;
int offsetAdjust = 0;
// try to distribute roundError. one pixel per cell
for (int i = 0; i < n; i++) {
iter.setIndex(i);
iter.setOffset(iter.getOffset() + offsetAdjust);
int curSpan = iter.getSpan();
if (roundError > 0) {
int boundGap = (adj > 0) ?
(int)Math.floor(iter.getMaximumSpan(targetSpan)) - curSpan :
curSpan - (int)Math.ceil(iter.getMinimumSpan(targetSpan));
if (boundGap >= 1) {
canAdjust = true;
iter.setSpan(curSpan + adj);
offsetAdjust += adj;
roundError--;
}
}
}
}
}
/** {@collect.stats}
* An iterator to express the requirements to use when computing
* layout.
*/
interface LayoutIterator {
void setOffset(int offs);
int getOffset();
void setSpan(int span);
int getSpan();
int getCount();
void setIndex(int i);
float getMinimumSpan(float parentSpan);
float getPreferredSpan(float parentSpan);
float getMaximumSpan(float parentSpan);
int getAdjustmentWeight(); //0 is the best weight WorstAdjustmentWeight is a worst one
//float getAlignment();
float getBorderWidth();
float getLeadingCollapseSpan();
float getTrailingCollapseSpan();
public static final int WorstAdjustmentWeight = 2;
}
//
// Serialization support
//
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
// Determine what values in valueConvertor need to be written out.
Enumeration keys = valueConvertor.keys();
s.writeInt(valueConvertor.size());
if (keys != null) {
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = valueConvertor.get(key);
if (!(key instanceof Serializable) &&
(key = StyleContext.getStaticAttributeKey(key)) == null) {
// Should we throw an exception here?
key = null;
value = null;
}
else if (!(value instanceof Serializable) &&
(value = StyleContext.getStaticAttributeKey(value)) == null){
// Should we throw an exception here?
key = null;
value = null;
}
s.writeObject(key);
s.writeObject(value);
}
}
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
// Reconstruct the hashtable.
int numValues = s.readInt();
valueConvertor = new Hashtable(Math.max(1, numValues));
while (numValues-- > 0) {
Object key = s.readObject();
Object value = s.readObject();
Object staticKey = StyleContext.getStaticAttribute(key);
if (staticKey != null) {
key = staticKey;
}
Object staticValue = StyleContext.getStaticAttribute(value);
if (staticValue != null) {
value = staticValue;
}
if (key != null && value != null) {
valueConvertor.put(key, value);
}
}
}
/*
* we need StyleSheet for resolving lenght units. (see
* isW3CLengthUnits)
* we can not pass stylesheet for handling relative sizes. (do not
* think changing public API is necessary)
* CSS is not likely to be accessed from more then one thread.
* Having local storage for StyleSheet for resolving relative
* sizes is safe
*
* idk 08/30/2004
*/
private StyleSheet getStyleSheet(StyleSheet ss) {
if (ss != null) {
styleSheet = ss;
}
return styleSheet;
}
//
// Instance variables
//
/** {@collect.stats} Maps from CSS key to CssValue. */
private transient Hashtable valueConvertor;
/** {@collect.stats} Size used for relative units. */
private int baseFontSize;
private transient StyleSheet styleSheet = null;
static int baseFontSizeIndex = 3;
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import javax.swing.*;
import javax.swing.event.*;
import java.io.Serializable;
/** {@collect.stats}
* OptionComboBoxModel extends the capabilities of the DefaultComboBoxModel,
* to store the Option that is initially marked as selected.
* This is stored, in order to enable an accurate reset of the
* ComboBox that represents the SELECT form element when the
* user requests a clear/reset. Given that a combobox only allow
* for one item to be selected, the last OPTION that has the
* attribute set wins.
*
@author Sunita Mani
*/
class OptionComboBoxModel extends DefaultComboBoxModel implements Serializable {
private Option selectedOption = null;
/** {@collect.stats}
* Stores the Option that has been marked its
* selected attribute set.
*/
public void setInitialSelection(Option option) {
selectedOption = option;
}
/** {@collect.stats}
* Fetches the Option item that represents that was
* initially set to a selected state.
*/
public Option getInitialSelection() {
return selectedOption;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.util.Enumeration;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
/** {@collect.stats}
* A view implementation to display an unwrapped
* preformatted line.<p>
* This subclasses ParagraphView, but this really only contains one
* Row of text.
*
* @author Timothy Prinzing
*/
class LineView extends ParagraphView {
/** {@collect.stats} Last place painted at. */
int tabBase;
/** {@collect.stats}
* Creates a LineView object.
*
* @param elem the element to wrap in a view
*/
public LineView(Element elem) {
super(elem);
}
/** {@collect.stats}
* Preformatted lines are not suppressed if they
* have only whitespace, so they are always visible.
*/
public boolean isVisible() {
return true;
}
/** {@collect.stats}
* Determines the minimum span for this view along an
* axis. The preformatted line should refuse to be
* sized less than the preferred size.
*
* @param axis may be either <code>View.X_AXIS</code> or
* <code>View.Y_AXIS</code>
* @return the minimum span the view can be rendered into
* @see View#getPreferredSpan
*/
public float getMinimumSpan(int axis) {
return getPreferredSpan(axis);
}
/** {@collect.stats}
* Gets the resize weight for the specified axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the weight
*/
public int getResizeWeight(int axis) {
switch (axis) {
case View.X_AXIS:
return 1;
case View.Y_AXIS:
return 0;
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
/** {@collect.stats}
* Gets the alignment for an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the alignment
*/
public float getAlignment(int axis) {
if (axis == View.X_AXIS) {
return 0;
}
return super.getAlignment(axis);
}
/** {@collect.stats}
* Lays out the children. If the layout span has changed,
* the rows are rebuilt. The superclass functionality
* is called after checking and possibly rebuilding the
* rows. If the height has changed, the
* <code>preferenceChanged</code> method is called
* on the parent since the vertical preference is
* rigid.
*
* @param width the width to lay out against >= 0. This is
* the width inside of the inset area.
* @param height the height to lay out against >= 0 (not used
* by paragraph, but used by the superclass). This
* is the height inside of the inset area.
*/
protected void layout(int width, int height) {
super.layout(Integer.MAX_VALUE - 1, height);
}
/** {@collect.stats}
* Returns the next tab stop position given a reference position.
* This view implements the tab coordinate system, and calls
* <code>getTabbedSpan</code> on the logical children in the process
* of layout to determine the desired span of the children. The
* logical children can delegate their tab expansion upward to
* the paragraph which knows how to expand tabs.
* <code>LabelView</code> is an example of a view that delegates
* its tab expansion needs upward to the paragraph.
* <p>
* This is implemented to try and locate a <code>TabSet</code>
* in the paragraph element's attribute set. If one can be
* found, its settings will be used, otherwise a default expansion
* will be provided. The base location for for tab expansion
* is the left inset from the paragraphs most recent allocation
* (which is what the layout of the children is based upon).
*
* @param x the X reference position
* @param tabOffset the position within the text stream
* that the tab occurred at >= 0.
* @return the trailing end of the tab expansion >= 0
* @see TabSet
* @see TabStop
* @see LabelView
*/
public float nextTabStop(float x, int tabOffset) {
// If the text isn't left justified, offset by 10 pixels!
if (getTabSet() == null &&
StyleConstants.getAlignment(getAttributes()) ==
StyleConstants.ALIGN_LEFT) {
return getPreTab(x, tabOffset);
}
return super.nextTabStop(x, tabOffset);
}
/** {@collect.stats}
* Returns the location for the tab.
*/
protected float getPreTab(float x, int tabOffset) {
Document d = getDocument();
View v = getViewAtPosition(tabOffset, null);
if ((d instanceof StyledDocument) && v != null) {
// Assume f is fixed point.
Font f = ((StyledDocument)d).getFont(v.getAttributes());
Container c = getContainer();
FontMetrics fm = (c != null) ? c.getFontMetrics(f) :
Toolkit.getDefaultToolkit().getFontMetrics(f);
int width = getCharactersPerTab() * fm.charWidth('W');
int tb = (int)getTabBase();
return (float)((((int)x - tb) / width + 1) * width + tb);
}
return 10.0f + x;
}
/** {@collect.stats}
* @return number of characters per tab, 8.
*/
protected int getCharactersPerTab() {
return 8;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text;
import java.util.*;
import java.io.*;
import java.awt.font.TextAttribute;
import java.text.Bidi;
import javax.swing.UIManager;
import javax.swing.undo.*;
import javax.swing.event.ChangeListener;
import javax.swing.event.*;
import javax.swing.tree.TreeNode;
import sun.font.BidiUtils;
import sun.swing.SwingUtilities2;
/** {@collect.stats}
* An implementation of the document interface to serve as a
* basis for implementing various kinds of documents. At this
* level there is very little policy, so there is a corresponding
* increase in difficulty of use.
* <p>
* This class implements a locking mechanism for the document. It
* allows multiple readers or one writer, and writers must wait until
* all observers of the document have been notified of a previous
* change before beginning another mutation to the document. The
* read lock is acquired and released using the <code>render</code>
* method. A write lock is aquired by the methods that mutate the
* document, and are held for the duration of the method call.
* Notification is done on the thread that produced the mutation,
* and the thread has full read access to the document for the
* duration of the notification, but other readers are kept out
* until the notification has finished. The notification is a
* beans event notification which does not allow any further
* mutations until all listeners have been notified.
* <p>
* Any models subclassed from this class and used in conjunction
* with a text component that has a look and feel implementation
* that is derived from BasicTextUI may be safely updated
* asynchronously, because all access to the View hierarchy
* is serialized by BasicTextUI if the document is of type
* <code>AbstractDocument</code>. The locking assumes that an
* independent thread will access the View hierarchy only from
* the DocumentListener methods, and that there will be only
* one event thread active at a time.
* <p>
* If concurrency support is desired, there are the following
* additional implications. The code path for any DocumentListener
* implementation and any UndoListener implementation must be threadsafe,
* and not access the component lock if trying to be safe from deadlocks.
* The <code>repaint</code> and <code>revalidate</code> methods
* on JComponent are safe.
* <p>
* AbstractDocument models an implied break at the end of the document.
* Among other things this allows you to position the caret after the last
* character. As a result of this, <code>getLength</code> returns one less
* than the length of the Content. If you create your own Content, be
* sure and initialize it to have an additional character. Refer to
* StringContent and GapContent for examples of this. Another implication
* of this is that Elements that model the implied end character will have
* an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
* <code>getParagraphElement(getLength()).getEndOffset() == getLength() + 1
* </code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public abstract class AbstractDocument implements Document, Serializable {
/** {@collect.stats}
* Constructs a new <code>AbstractDocument</code>, wrapped around some
* specified content storage mechanism.
*
* @param data the content
*/
protected AbstractDocument(Content data) {
this(data, StyleContext.getDefaultStyleContext());
}
/** {@collect.stats}
* Constructs a new <code>AbstractDocument</code>, wrapped around some
* specified content storage mechanism.
*
* @param data the content
* @param context the attribute context
*/
protected AbstractDocument(Content data, AttributeContext context) {
this.data = data;
this.context = context;
bidiRoot = new BidiRootElement();
if (defaultI18NProperty == null) {
// determine default setting for i18n support
Object o = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return System.getProperty(I18NProperty);
}
}
);
if (o != null) {
defaultI18NProperty = Boolean.valueOf((String)o);
} else {
defaultI18NProperty = Boolean.FALSE;
}
}
putProperty( I18NProperty, defaultI18NProperty);
//REMIND(bcb) This creates an initial bidi element to account for
//the \n that exists by default in the content. Doing it this way
//seems to expose a little too much knowledge of the content given
//to us by the sub-class. Consider having the sub-class' constructor
//make an initial call to insertUpdate.
writeLock();
try {
Element[] p = new Element[1];
p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
bidiRoot.replace(0,0,p);
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* Supports managing a set of properties. Callers
* can use the <code>documentProperties</code> dictionary
* to annotate the document with document-wide properties.
*
* @return a non-<code>null</code> <code>Dictionary</code>
* @see #setDocumentProperties
*/
public Dictionary<Object,Object> getDocumentProperties() {
if (documentProperties == null) {
documentProperties = new Hashtable(2);
}
return documentProperties;
}
/** {@collect.stats}
* Replaces the document properties dictionary for this document.
*
* @param x the new dictionary
* @see #getDocumentProperties
*/
public void setDocumentProperties(Dictionary<Object,Object> x) {
documentProperties = x;
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireInsertUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).insertUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireChangedUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).changedUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireRemoveUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).removeUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireUndoableEditUpdate(UndoableEditEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==UndoableEditListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this document.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* document <code>d</code>
* for its document listeners with the following code:
*
* <pre>DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this component,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getDocumentListeners
* @see #getUndoableEditListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/** {@collect.stats}
* Gets the asynchronous loading priority. If less than zero,
* the document should not be loaded asynchronously.
*
* @return the asynchronous loading priority, or <code>-1</code>
* if the document should not be loaded asynchronously
*/
public int getAsynchronousLoadPriority() {
Integer loadPriority = (Integer)
getProperty(AbstractDocument.AsyncLoadPriority);
if (loadPriority != null) {
return loadPriority.intValue();
}
return -1;
}
/** {@collect.stats}
* Sets the asynchronous loading priority.
* @param p the new asynchronous loading priority; a value
* less than zero indicates that the document should not be
* loaded asynchronously
*/
public void setAsynchronousLoadPriority(int p) {
Integer loadPriority = (p >= 0) ? new Integer(p) : null;
putProperty(AbstractDocument.AsyncLoadPriority, loadPriority);
}
/** {@collect.stats}
* Sets the <code>DocumentFilter</code>. The <code>DocumentFilter</code>
* is passed <code>insert</code> and <code>remove</code> to conditionally
* allow inserting/deleting of the text. A <code>null</code> value
* indicates that no filtering will occur.
*
* @param filter the <code>DocumentFilter</code> used to constrain text
* @see #getDocumentFilter
* @since 1.4
*/
public void setDocumentFilter(DocumentFilter filter) {
documentFilter = filter;
}
/** {@collect.stats}
* Returns the <code>DocumentFilter</code> that is responsible for
* filtering of insertion/removal. A <code>null</code> return value
* implies no filtering is to occur.
*
* @since 1.4
* @see #setDocumentFilter
* @return the DocumentFilter
*/
public DocumentFilter getDocumentFilter() {
return documentFilter;
}
// --- Document methods -----------------------------------------
/** {@collect.stats}
* This allows the model to be safely rendered in the presence
* of currency, if the model supports being updated asynchronously.
* The given runnable will be executed in a way that allows it
* to safely read the model with no changes while the runnable
* is being executed. The runnable itself may <em>not</em>
* make any mutations.
* <p>
* This is implemented to aquire a read lock for the duration
* of the runnables execution. There may be multiple runnables
* executing at the same time, and all writers will be blocked
* while there are active rendering runnables. If the runnable
* throws an exception, its lock will be safely released.
* There is no protection against a runnable that never exits,
* which will effectively leave the document locked for it's
* lifetime.
* <p>
* If the given runnable attempts to make any mutations in
* this implementation, a deadlock will occur. There is
* no tracking of individual rendering threads to enable
* detecting this situation, but a subclass could incur
* the overhead of tracking them and throwing an error.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param r the renderer to execute
*/
public void render(Runnable r) {
readLock();
try {
r.run();
} finally {
readUnlock();
}
}
/** {@collect.stats}
* Returns the length of the data. This is the number of
* characters of content that represents the users data.
*
* @return the length >= 0
* @see Document#getLength
*/
public int getLength() {
return data.length() - 1;
}
/** {@collect.stats}
* Adds a document listener for notification of any changes.
*
* @param listener the <code>DocumentListener</code> to add
* @see Document#addDocumentListener
*/
public void addDocumentListener(DocumentListener listener) {
listenerList.add(DocumentListener.class, listener);
}
/** {@collect.stats}
* Removes a document listener.
*
* @param listener the <code>DocumentListener</code> to remove
* @see Document#removeDocumentListener
*/
public void removeDocumentListener(DocumentListener listener) {
listenerList.remove(DocumentListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the document listeners
* registered on this document.
*
* @return all of this document's <code>DocumentListener</code>s
* or an empty array if no document listeners are
* currently registered
*
* @see #addDocumentListener
* @see #removeDocumentListener
* @since 1.4
*/
public DocumentListener[] getDocumentListeners() {
return (DocumentListener[])listenerList.getListeners(
DocumentListener.class);
}
/** {@collect.stats}
* Adds an undo listener for notification of any changes.
* Undo/Redo operations performed on the <code>UndoableEdit</code>
* will cause the appropriate DocumentEvent to be fired to keep
* the view(s) in sync with the model.
*
* @param listener the <code>UndoableEditListener</code> to add
* @see Document#addUndoableEditListener
*/
public void addUndoableEditListener(UndoableEditListener listener) {
listenerList.add(UndoableEditListener.class, listener);
}
/** {@collect.stats}
* Removes an undo listener.
*
* @param listener the <code>UndoableEditListener</code> to remove
* @see Document#removeDocumentListener
*/
public void removeUndoableEditListener(UndoableEditListener listener) {
listenerList.remove(UndoableEditListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the undoable edit listeners
* registered on this document.
*
* @return all of this document's <code>UndoableEditListener</code>s
* or an empty array if no undoable edit listeners are
* currently registered
*
* @see #addUndoableEditListener
* @see #removeUndoableEditListener
*
* @since 1.4
*/
public UndoableEditListener[] getUndoableEditListeners() {
return (UndoableEditListener[])listenerList.getListeners(
UndoableEditListener.class);
}
/** {@collect.stats}
* A convenience method for looking up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().get(key);
* </pre>
*
* @param key the non-<code>null</code> property key
* @return the value of this property or <code>null</code>
* @see #getDocumentProperties
*/
public final Object getProperty(Object key) {
return getDocumentProperties().get(key);
}
/** {@collect.stats}
* A convenience method for storing up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().put(key, value);
* </pre>
* If <code>value</code> is <code>null</code> this method will
* remove the property.
*
* @param key the non-<code>null</code> key
* @param value the property value
* @see #getDocumentProperties
*/
public final void putProperty(Object key, Object value) {
if (value != null) {
getDocumentProperties().put(key, value);
} else {
getDocumentProperties().remove(key);
}
if( key == TextAttribute.RUN_DIRECTION
&& Boolean.TRUE.equals(getProperty(I18NProperty)) )
{
//REMIND - this needs to flip on the i18n property if run dir
//is rtl and the i18n property is not already on.
writeLock();
try {
DefaultDocumentEvent e
= new DefaultDocumentEvent(0, getLength(),
DocumentEvent.EventType.INSERT);
updateBidi( e );
} finally {
writeUnlock();
}
}
}
/** {@collect.stats}
* Removes some content from the document.
* Removing content causes a write lock to be held while the
* actual changes are taking place. Observers are notified
* of the change on the thread that called this method.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param offs the starting offset >= 0
* @param len the number of characters to remove >= 0
* @exception BadLocationException the given remove position is not a valid
* position within the document
* @see Document#remove
*/
public void remove(int offs, int len) throws BadLocationException {
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.remove(getFilterBypass(), offs, len);
}
else {
handleRemove(offs, len);
}
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* Performs the actual work of the remove. It is assumed the caller
* will have obtained a <code>writeLock</code> before invoking this.
*/
void handleRemove(int offs, int len) throws BadLocationException {
if (len > 0) {
if (offs < 0 || (offs + len) > getLength()) {
throw new BadLocationException("Invalid remove",
getLength() + 1);
}
DefaultDocumentEvent chng =
new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
boolean isComposedTextElement = false;
// Check whether the position of interest is the composed text
isComposedTextElement = Utilities.isComposedTextElement(this, offs);
removeUpdate(chng);
UndoableEdit u = data.remove(offs, len);
if (u != null) {
chng.addEdit(u);
}
postRemoveUpdate(chng);
// Mark the edit as done.
chng.end();
fireRemoveUpdate(chng);
// only fire undo if Content implementation supports it
// undo for the composed text is not supported for now
if ((u != null) && !isComposedTextElement) {
fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
}
}
}
/** {@collect.stats}
* Deletes the region of text from <code>offset</code> to
* <code>offset + length</code>, and replaces it with <code>text</code>.
* It is up to the implementation as to how this is implemented, some
* implementations may treat this as two distinct operations: a remove
* followed by an insert, others may treat the replace as one atomic
* operation.
*
* @param offset index of child element
* @param length length of text to delete, may be 0 indicating don't
* delete anything
* @param text text to insert, <code>null</code> indicates no text to insert
* @param attrs AttributeSet indicating attributes of inserted text,
* <code>null</code>
* is legal, and typically treated as an empty attributeset,
* but exact interpretation is left to the subclass
* @exception BadLocationException the given position is not a valid
* position within the document
* @since 1.4
*/
public void replace(int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
if (length == 0 && (text == null || text.length() == 0)) {
return;
}
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.replace(getFilterBypass(), offset, length, text,
attrs);
}
else {
if (length > 0) {
remove(offset, length);
}
if (text != null && text.length() > 0) {
insertString(offset, text, attrs);
}
}
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* Inserts some content into the document.
* Inserting content causes a write lock to be held while the
* actual changes are taking place, followed by notification
* to the observers on the thread that grabbed the write lock.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param offs the starting offset >= 0
* @param str the string to insert; does nothing with null/empty strings
* @param a the attributes for the inserted content
* @exception BadLocationException the given insert position is not a valid
* position within the document
* @see Document#insertString
*/
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if ((str == null) || (str.length() == 0)) {
return;
}
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.insertString(getFilterBypass(), offs, str, a);
}
else {
handleInsertString(offs, str, a);
}
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* Performs the actual work of inserting the text; it is assumed the
* caller has obtained a write lock before invoking this.
*/
void handleInsertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if ((str == null) || (str.length() == 0)) {
return;
}
UndoableEdit u = data.insertString(offs, str);
DefaultDocumentEvent e =
new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
if (u != null) {
e.addEdit(u);
}
// see if complex glyph layout support is needed
if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
// if a default direction of right-to-left has been specified,
// we want complex layout even if the text is all left to right.
Object d = getProperty(TextAttribute.RUN_DIRECTION);
if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
putProperty( I18NProperty, Boolean.TRUE);
} else {
char[] chars = str.toCharArray();
if (SwingUtilities2.isComplexLayout(chars, 0, chars.length)) {
putProperty( I18NProperty, Boolean.TRUE);
}
}
}
insertUpdate(e, a);
// Mark the edit as done.
e.end();
fireInsertUpdate(e);
// only fire undo if Content implementation supports it
// undo for the composed text is not supported for now
if (u != null &&
(a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
fireUndoableEditUpdate(new UndoableEditEvent(this, e));
}
}
/** {@collect.stats}
* Gets a sequence of text from the document.
*
* @param offset the starting offset >= 0
* @param length the number of characters to retrieve >= 0
* @return the text
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
* @see Document#getText
*/
public String getText(int offset, int length) throws BadLocationException {
if (length < 0) {
throw new BadLocationException("Length must be positive", length);
}
String str = data.getString(offset, length);
return str;
}
/** {@collect.stats}
* Fetches the text contained within the given portion
* of the document.
* <p>
* If the partialReturn property on the txt parameter is false, the
* data returned in the Segment will be the entire length requested and
* may or may not be a copy depending upon how the data was stored.
* If the partialReturn property is true, only the amount of text that
* can be returned without creating a copy is returned. Using partial
* returns will give better performance for situations where large
* parts of the document are being scanned. The following is an example
* of using the partial return to access the entire document:
* <p>
* <pre>
* int nleft = doc.getDocumentLength();
* Segment text = new Segment();
* int offs = 0;
* text.setPartialReturn(true);
* while (nleft > 0) {
* doc.getText(offs, nleft, text);
* // do something with text
* nleft -= text.count;
* offs += text.count;
* }
* </pre>
*
* @param offset the starting offset >= 0
* @param length the number of characters to retrieve >= 0
* @param txt the Segment object to retrieve the text into
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
*/
public void getText(int offset, int length, Segment txt) throws BadLocationException {
if (length < 0) {
throw new BadLocationException("Length must be positive", length);
}
data.getChars(offset, length, txt);
}
/** {@collect.stats}
* Returns a position that will track change as the document
* is altered.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param offs the position in the model >= 0
* @return the position
* @exception BadLocationException if the given position does not
* represent a valid location in the associated document
* @see Document#createPosition
*/
public synchronized Position createPosition(int offs) throws BadLocationException {
return data.createPosition(offs);
}
/** {@collect.stats}
* Returns a position that represents the start of the document. The
* position returned can be counted on to track change and stay
* located at the beginning of the document.
*
* @return the position
*/
public final Position getStartPosition() {
Position p;
try {
p = createPosition(0);
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/** {@collect.stats}
* Returns a position that represents the end of the document. The
* position returned can be counted on to track change and stay
* located at the end of the document.
*
* @return the position
*/
public final Position getEndPosition() {
Position p;
try {
p = createPosition(data.length());
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/** {@collect.stats}
* Gets all root elements defined. Typically, there
* will only be one so the default implementation
* is to return the default root element.
*
* @return the root element
*/
public Element[] getRootElements() {
Element[] elems = new Element[2];
elems[0] = getDefaultRootElement();
elems[1] = getBidiRootElement();
return elems;
}
/** {@collect.stats}
* Returns the root element that views should be based upon
* unless some other mechanism for assigning views to element
* structures is provided.
*
* @return the root element
* @see Document#getDefaultRootElement
*/
public abstract Element getDefaultRootElement();
// ---- local methods -----------------------------------------
/** {@collect.stats}
* Returns the <code>FilterBypass</code>. This will create one if one
* does not yet exist.
*/
private DocumentFilter.FilterBypass getFilterBypass() {
if (filterBypass == null) {
filterBypass = new DefaultFilterBypass();
}
return filterBypass;
}
/** {@collect.stats}
* Returns the root element of the bidirectional structure for this
* document. Its children represent character runs with a given
* Unicode bidi level.
*/
public Element getBidiRootElement() {
return bidiRoot;
}
/** {@collect.stats}
* Returns true if the text in the range <code>p0</code> to
* <code>p1</code> is left to right.
*/
boolean isLeftToRight(int p0, int p1) {
if(!getProperty(I18NProperty).equals(Boolean.TRUE)) {
return true;
}
Element bidiRoot = getBidiRootElement();
int index = bidiRoot.getElementIndex(p0);
Element bidiElem = bidiRoot.getElement(index);
if(bidiElem.getEndOffset() >= p1) {
AttributeSet bidiAttrs = bidiElem.getAttributes();
return ((StyleConstants.getBidiLevel(bidiAttrs) % 2) == 0);
}
return true;
}
/** {@collect.stats}
* Get the paragraph element containing the given position. Sub-classes
* must define for themselves what exactly constitutes a paragraph. They
* should keep in mind however that a paragraph should at least be the
* unit of text over which to run the Unicode bidirectional algorithm.
*
* @param pos the starting offset >= 0
* @return the element */
public abstract Element getParagraphElement(int pos);
/** {@collect.stats}
* Fetches the context for managing attributes. This
* method effectively establishes the strategy used
* for compressing AttributeSet information.
*
* @return the context
*/
protected final AttributeContext getAttributeContext() {
return context;
}
/** {@collect.stats}
* Updates document structure as a result of text insertion. This
* will happen within a write lock. If a subclass of
* this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
* @param attr the attributes for the change
*/
protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
updateBidi( chng );
// Check if a multi byte is encountered in the inserted text.
if (chng.type == DocumentEvent.EventType.INSERT &&
chng.getLength() > 0 &&
!Boolean.TRUE.equals(getProperty(MultiByteProperty))) {
Segment segment = SegmentCache.getSharedSegment();
try {
getText(chng.getOffset(), chng.getLength(), segment);
segment.first();
do {
if ((int)segment.current() > 255) {
putProperty(MultiByteProperty, Boolean.TRUE);
break;
}
} while (segment.next() != Segment.DONE);
} catch (BadLocationException ble) {
// Should never happen
}
SegmentCache.releaseSharedSegment(segment);
}
}
/** {@collect.stats}
* Updates any document structure as a result of text removal. This
* method is called before the text is actually removed from the Content.
* This will happen within a write lock. If a subclass
* of this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
*/
protected void removeUpdate(DefaultDocumentEvent chng) {
}
/** {@collect.stats}
* Updates any document structure as a result of text removal. This
* method is called after the text has been removed from the Content.
* This will happen within a write lock. If a subclass
* of this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
*/
protected void postRemoveUpdate(DefaultDocumentEvent chng) {
if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
updateBidi( chng );
}
/** {@collect.stats}
* Update the bidi element structure as a result of the given change
* to the document. The given change will be updated to reflect the
* changes made to the bidi structure.
*
* This method assumes that every offset in the model is contained in
* exactly one paragraph. This method also assumes that it is called
* after the change is made to the default element structure.
*/
void updateBidi( DefaultDocumentEvent chng ) {
// Calculate the range of paragraphs affected by the change.
int firstPStart;
int lastPEnd;
if( chng.type == DocumentEvent.EventType.INSERT
|| chng.type == DocumentEvent.EventType.CHANGE )
{
int chngStart = chng.getOffset();
int chngEnd = chngStart + chng.getLength();
firstPStart = getParagraphElement(chngStart).getStartOffset();
lastPEnd = getParagraphElement(chngEnd).getEndOffset();
} else if( chng.type == DocumentEvent.EventType.REMOVE ) {
Element paragraph = getParagraphElement( chng.getOffset() );
firstPStart = paragraph.getStartOffset();
lastPEnd = paragraph.getEndOffset();
} else {
throw new Error("Internal error: unknown event type.");
}
//System.out.println("updateBidi: firstPStart = " + firstPStart + " lastPEnd = " + lastPEnd );
// Calculate the bidi levels for the affected range of paragraphs. The
// levels array will contain a bidi level for each character in the
// affected text.
byte levels[] = calculateBidiLevels( firstPStart, lastPEnd );
Vector newElements = new Vector();
// Calculate the first span of characters in the affected range with
// the same bidi level. If this level is the same as the level of the
// previous bidi element (the existing bidi element containing
// firstPStart-1), then merge in the previous element. If not, but
// the previous element overlaps the affected range, truncate the
// previous element at firstPStart.
int firstSpanStart = firstPStart;
int removeFromIndex = 0;
if( firstSpanStart > 0 ) {
int prevElemIndex = bidiRoot.getElementIndex(firstPStart-1);
removeFromIndex = prevElemIndex;
Element prevElem = bidiRoot.getElement(prevElemIndex);
int prevLevel=StyleConstants.getBidiLevel(prevElem.getAttributes());
//System.out.println("createbidiElements: prevElem= " + prevElem + " prevLevel= " + prevLevel + "level[0] = " + levels[0]);
if( prevLevel==levels[0] ) {
firstSpanStart = prevElem.getStartOffset();
} else if( prevElem.getEndOffset() > firstPStart ) {
newElements.addElement(new BidiElement(bidiRoot,
prevElem.getStartOffset(),
firstPStart, prevLevel));
} else {
removeFromIndex++;
}
}
int firstSpanEnd = 0;
while((firstSpanEnd<levels.length) && (levels[firstSpanEnd]==levels[0]))
firstSpanEnd++;
// Calculate the last span of characters in the affected range with
// the same bidi level. If this level is the same as the level of the
// next bidi element (the existing bidi element containing lastPEnd),
// then merge in the next element. If not, but the next element
// overlaps the affected range, adjust the next element to start at
// lastPEnd.
int lastSpanEnd = lastPEnd;
Element newNextElem = null;
int removeToIndex = bidiRoot.getElementCount() - 1;
if( lastSpanEnd <= getLength() ) {
int nextElemIndex = bidiRoot.getElementIndex( lastPEnd );
removeToIndex = nextElemIndex;
Element nextElem = bidiRoot.getElement( nextElemIndex );
int nextLevel = StyleConstants.getBidiLevel(nextElem.getAttributes());
if( nextLevel == levels[levels.length-1] ) {
lastSpanEnd = nextElem.getEndOffset();
} else if( nextElem.getStartOffset() < lastPEnd ) {
newNextElem = new BidiElement(bidiRoot, lastPEnd,
nextElem.getEndOffset(),
nextLevel);
} else {
removeToIndex--;
}
}
int lastSpanStart = levels.length;
while( (lastSpanStart>firstSpanEnd)
&& (levels[lastSpanStart-1]==levels[levels.length-1]) )
lastSpanStart--;
// If the first and last spans are contiguous and have the same level,
// merge them and create a single new element for the entire span.
// Otherwise, create elements for the first and last spans as well as
// any spans in between.
if((firstSpanEnd==lastSpanStart)&&(levels[0]==levels[levels.length-1])){
newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
lastSpanEnd, levels[0]));
} else {
// Create an element for the first span.
newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
firstSpanEnd+firstPStart,
levels[0]));
// Create elements for the spans in between the first and last
for( int i=firstSpanEnd; i<lastSpanStart; ) {
//System.out.println("executed line 872");
int j;
for( j=i; (j<levels.length) && (levels[j] == levels[i]); j++ );
newElements.addElement(new BidiElement(bidiRoot, firstPStart+i,
firstPStart+j,
(int)levels[i]));
i=j;
}
// Create an element for the last span.
newElements.addElement(new BidiElement(bidiRoot,
lastSpanStart+firstPStart,
lastSpanEnd,
levels[levels.length-1]));
}
if( newNextElem != null )
newElements.addElement( newNextElem );
// Calculate the set of existing bidi elements which must be
// removed.
int removedElemCount = 0;
if( bidiRoot.getElementCount() > 0 ) {
removedElemCount = removeToIndex - removeFromIndex + 1;
}
Element[] removedElems = new Element[removedElemCount];
for( int i=0; i<removedElemCount; i++ ) {
removedElems[i] = bidiRoot.getElement(removeFromIndex+i);
}
Element[] addedElems = new Element[ newElements.size() ];
newElements.copyInto( addedElems );
// Update the change record.
ElementEdit ee = new ElementEdit( bidiRoot, removeFromIndex,
removedElems, addedElems );
chng.addEdit( ee );
// Update the bidi element structure.
bidiRoot.replace( removeFromIndex, removedElems.length, addedElems );
}
/** {@collect.stats}
* Calculate the levels array for a range of paragraphs.
*/
private byte[] calculateBidiLevels( int firstPStart, int lastPEnd ) {
byte levels[] = new byte[ lastPEnd - firstPStart ];
int levelsEnd = 0;
Boolean defaultDirection = null;
Object d = getProperty(TextAttribute.RUN_DIRECTION);
if (d instanceof Boolean) {
defaultDirection = (Boolean) d;
}
// For each paragraph in the given range of paragraphs, get its
// levels array and add it to the levels array for the entire span.
for(int o=firstPStart; o<lastPEnd; ) {
Element p = getParagraphElement( o );
int pStart = p.getStartOffset();
int pEnd = p.getEndOffset();
// default run direction for the paragraph. This will be
// null if there is no direction override specified (i.e.
// the direction will be determined from the content).
Boolean direction = defaultDirection;
d = p.getAttributes().getAttribute(TextAttribute.RUN_DIRECTION);
if (d instanceof Boolean) {
direction = (Boolean) d;
}
//System.out.println("updateBidi: paragraph start = " + pStart + " paragraph end = " + pEnd);
// Create a Bidi over this paragraph then get the level
// array.
Segment seg = SegmentCache.getSharedSegment();
try {
getText(pStart, pEnd-pStart, seg);
} catch (BadLocationException e ) {
throw new Error("Internal error: " + e.toString());
}
// REMIND(bcb) we should really be using a Segment here.
Bidi bidiAnalyzer;
int bidiflag = Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
if (direction != null) {
if (TextAttribute.RUN_DIRECTION_LTR.equals(direction)) {
bidiflag = Bidi.DIRECTION_LEFT_TO_RIGHT;
} else {
bidiflag = Bidi.DIRECTION_RIGHT_TO_LEFT;
}
}
bidiAnalyzer = new Bidi(seg.array, seg.offset, null, 0, seg.count,
bidiflag);
BidiUtils.getLevels(bidiAnalyzer, levels, levelsEnd);
levelsEnd += bidiAnalyzer.getLength();
o = p.getEndOffset();
SegmentCache.releaseSharedSegment(seg);
}
// REMIND(bcb) remove this code when debugging is done.
if( levelsEnd != levels.length )
throw new Error("levelsEnd assertion failed.");
return levels;
}
/** {@collect.stats}
* Gives a diagnostic dump.
*
* @param out the output stream
*/
public void dump(PrintStream out) {
Element root = getDefaultRootElement();
if (root instanceof AbstractElement) {
((AbstractElement)root).dump(out, 0);
}
bidiRoot.dump(out,0);
}
/** {@collect.stats}
* Gets the content for the document.
*
* @return the content
*/
protected final Content getContent() {
return data;
}
/** {@collect.stats}
* Creates a document leaf element.
* Hook through which elements are created to represent the
* document structure. Because this implementation keeps
* structure and content separate, elements grow automatically
* when content is extended so splits of existing elements
* follow. The document itself gets to decide how to generate
* elements to give flexibility in the type of elements used.
*
* @param parent the parent element
* @param a the attributes for the element
* @param p0 the beginning of the range >= 0
* @param p1 the end of the range >= p0
* @return the new element
*/
protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
return new LeafElement(parent, a, p0, p1);
}
/** {@collect.stats}
* Creates a document branch element, that can contain other elements.
*
* @param parent the parent element
* @param a the attributes
* @return the element
*/
protected Element createBranchElement(Element parent, AttributeSet a) {
return new BranchElement(parent, a);
}
// --- Document locking ----------------------------------
/** {@collect.stats}
* Fetches the current writing thread if there is one.
* This can be used to distinguish whether a method is
* being called as part of an existing modification or
* if a lock needs to be acquired and a new transaction
* started.
*
* @return the thread actively modifying the document
* or <code>null</code> if there are no modifications in progress
*/
protected synchronized final Thread getCurrentWriter() {
return currWriter;
}
/** {@collect.stats}
* Acquires a lock to begin mutating the document this lock
* protects. There can be no writing, notification of changes, or
* reading going on in order to gain the lock. Additionally a thread is
* allowed to gain more than one <code>writeLock</code>,
* as long as it doesn't attempt to gain additional <code>writeLock</code>s
* from within document notification. Attempting to gain a
* <code>writeLock</code> from within a DocumentListener notification will
* result in an <code>IllegalStateException</code>. The ability
* to obtain more than one <code>writeLock</code> per thread allows
* subclasses to gain a writeLock, perform a number of operations, then
* release the lock.
* <p>
* Calls to <code>writeLock</code>
* must be balanced with calls to <code>writeUnlock</code>, else the
* <code>Document</code> will be left in a locked state so that no
* reading or writing can be done.
*
* @exception IllegalStateException thrown on illegal lock
* attempt. If the document is implemented properly, this can
* only happen if a document listener attempts to mutate the
* document. This situation violates the bean event model
* where order of delivery is not guaranteed and all listeners
* should be notified before further mutations are allowed.
*/
protected synchronized final void writeLock() {
try {
while ((numReaders > 0) || (currWriter != null)) {
if (Thread.currentThread() == currWriter) {
if (notifyingListeners) {
// Assuming one doesn't do something wrong in a
// subclass this should only happen if a
// DocumentListener tries to mutate the document.
throw new IllegalStateException(
"Attempt to mutate in notification");
}
numWriters++;
return;
}
wait();
}
currWriter = Thread.currentThread();
numWriters = 1;
} catch (InterruptedException e) {
throw new Error("Interrupted attempt to aquire write lock");
}
}
/** {@collect.stats}
* Releases a write lock previously obtained via <code>writeLock</code>.
* After decrementing the lock count if there are no oustanding locks
* this will allow a new writer, or readers.
*
* @see #writeLock
*/
protected synchronized final void writeUnlock() {
if (--numWriters <= 0) {
numWriters = 0;
currWriter = null;
notifyAll();
}
}
/** {@collect.stats}
* Acquires a lock to begin reading some state from the
* document. There can be multiple readers at the same time.
* Writing blocks the readers until notification of the change
* to the listeners has been completed. This method should
* be used very carefully to avoid unintended compromise
* of the document. It should always be balanced with a
* <code>readUnlock</code>.
*
* @see #readUnlock
*/
public synchronized final void readLock() {
try {
while (currWriter != null) {
if (currWriter == Thread.currentThread()) {
// writer has full read access.... may try to acquire
// lock in notification
return;
}
wait();
}
numReaders += 1;
} catch (InterruptedException e) {
throw new Error("Interrupted attempt to aquire read lock");
}
}
/** {@collect.stats}
* Does a read unlock. This signals that one
* of the readers is done. If there are no more readers
* then writing can begin again. This should be balanced
* with a readLock, and should occur in a finally statement
* so that the balance is guaranteed. The following is an
* example.
* <pre><code>
* readLock();
* try {
* // do something
* } finally {
* readUnlock();
* }
* </code></pre>
*
* @see #readLock
*/
public synchronized final void readUnlock() {
if (currWriter == Thread.currentThread()) {
// writer has full read access.... may try to acquire
// lock in notification
return;
}
if (numReaders <= 0) {
throw new StateInvariantError(BAD_LOCK_STATE);
}
numReaders -= 1;
notify();
}
// --- serialization ---------------------------------------------
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
listenerList = new EventListenerList();
// Restore bidi structure
//REMIND(bcb) This creates an initial bidi element to account for
//the \n that exists by default in the content.
bidiRoot = new BidiRootElement();
try {
writeLock();
Element[] p = new Element[1];
p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
bidiRoot.replace(0,0,p);
} finally {
writeUnlock();
}
// At this point bidi root is only partially correct. To fully
// restore it we need access to getDefaultRootElement. But, this
// is created by the subclass and at this point will be null. We
// thus use registerValidation.
s.registerValidation(new ObjectInputValidation() {
public void validateObject() {
try {
writeLock();
DefaultDocumentEvent e = new DefaultDocumentEvent
(0, getLength(),
DocumentEvent.EventType.INSERT);
updateBidi( e );
}
finally {
writeUnlock();
}
}
}, 0);
}
// ----- member variables ------------------------------------------
private transient int numReaders;
private transient Thread currWriter;
/** {@collect.stats}
* The number of writers, all obtained from <code>currWriter</code>.
*/
private transient int numWriters;
/** {@collect.stats}
* True will notifying listeners.
*/
private transient boolean notifyingListeners;
private static Boolean defaultI18NProperty;
/** {@collect.stats}
* Storage for document-wide properties.
*/
private Dictionary<Object,Object> documentProperties = null;
/** {@collect.stats}
* The event listener list for the document.
*/
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Where the text is actually stored, and a set of marks
* that track change as the document is edited are managed.
*/
private Content data;
/** {@collect.stats}
* Factory for the attributes. This is the strategy for
* attribute compression and control of the lifetime of
* a set of attributes as a collection. This may be shared
* with other documents.
*/
private AttributeContext context;
/** {@collect.stats}
* The root of the bidirectional structure for this document. Its children
* represent character runs with the same Unicode bidi level.
*/
private transient BranchElement bidiRoot;
/** {@collect.stats}
* Filter for inserting/removing of text.
*/
private DocumentFilter documentFilter;
/** {@collect.stats}
* Used by DocumentFilter to do actual insert/remove.
*/
private transient DocumentFilter.FilterBypass filterBypass;
private static final String BAD_LOCK_STATE = "document lock failure";
/** {@collect.stats}
* Error message to indicate a bad location.
*/
protected static final String BAD_LOCATION = "document location failure";
/** {@collect.stats}
* Name of elements used to represent paragraphs
*/
public static final String ParagraphElementName = "paragraph";
/** {@collect.stats}
* Name of elements used to represent content
*/
public static final String ContentElementName = "content";
/** {@collect.stats}
* Name of elements used to hold sections (lines/paragraphs).
*/
public static final String SectionElementName = "section";
/** {@collect.stats}
* Name of elements used to hold a unidirectional run
*/
public static final String BidiElementName = "bidi level";
/** {@collect.stats}
* Name of the attribute used to specify element
* names.
*/
public static final String ElementNameAttribute = "$ename";
/** {@collect.stats}
* Document property that indicates whether internationalization
* functions such as text reordering or reshaping should be
* performed. This property should not be publicly exposed,
* since it is used for implementation convenience only. As a
* side effect, copies of this property may be in its subclasses
* that live in different packages (e.g. HTMLDocument as of now),
* so those copies should also be taken care of when this property
* needs to be modified.
*/
static final String I18NProperty = "i18n";
/** {@collect.stats}
* Document property that indicates if a character has been inserted
* into the document that is more than one byte long. GlyphView uses
* this to determine if it should use BreakIterator.
*/
static final Object MultiByteProperty = "multiByte";
/** {@collect.stats}
* Document property that indicates asynchronous loading is
* desired, with the thread priority given as the value.
*/
static final String AsyncLoadPriority = "load priority";
/** {@collect.stats}
* Interface to describe a sequence of character content that
* can be edited. Implementations may or may not support a
* history mechanism which will be reflected by whether or not
* mutations return an UndoableEdit implementation.
* @see AbstractDocument
*/
public interface Content {
/** {@collect.stats}
* Creates a position within the content that will
* track change as the content is mutated.
*
* @param offset the offset in the content >= 0
* @return a Position
* @exception BadLocationException for an invalid offset
*/
public Position createPosition(int offset) throws BadLocationException;
/** {@collect.stats}
* Current length of the sequence of character content.
*
* @return the length >= 0
*/
public int length();
/** {@collect.stats}
* Inserts a string of characters into the sequence.
*
* @param where offset into the sequence to make the insertion >= 0
* @param str string to insert
* @return if the implementation supports a history mechanism,
* a reference to an <code>Edit</code> implementation will be returned,
* otherwise returns <code>null</code>
* @exception BadLocationException thrown if the area covered by
* the arguments is not contained in the character sequence
*/
public UndoableEdit insertString(int where, String str) throws BadLocationException;
/** {@collect.stats}
* Removes some portion of the sequence.
*
* @param where The offset into the sequence to make the
* insertion >= 0.
* @param nitems The number of items in the sequence to remove >= 0.
* @return If the implementation supports a history mechansim,
* a reference to an Edit implementation will be returned,
* otherwise null.
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException;
/** {@collect.stats}
* Fetches a string of characters contained in the sequence.
*
* @param where Offset into the sequence to fetch >= 0.
* @param len number of characters to copy >= 0.
* @return the string
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public String getString(int where, int len) throws BadLocationException;
/** {@collect.stats}
* Gets a sequence of characters and copies them into a Segment.
*
* @param where the starting offset >= 0
* @param len the number of characters >= 0
* @param txt the target location to copy into
* @exception BadLocationException Thrown if the area covered by
* the arguments is not contained in the character sequence.
*/
public void getChars(int where, int len, Segment txt) throws BadLocationException;
}
/** {@collect.stats}
* An interface that can be used to allow MutableAttributeSet
* implementations to use pluggable attribute compression
* techniques. Each mutation of the attribute set can be
* used to exchange a previous AttributeSet instance with
* another, preserving the possibility of the AttributeSet
* remaining immutable. An implementation is provided by
* the StyleContext class.
*
* The Element implementations provided by this class use
* this interface to provide their MutableAttributeSet
* implementations, so that different AttributeSet compression
* techniques can be employed. The method
* <code>getAttributeContext</code> should be implemented to
* return the object responsible for implementing the desired
* compression technique.
*
* @see StyleContext
*/
public interface AttributeContext {
/** {@collect.stats}
* Adds an attribute to the given set, and returns
* the new representative set.
*
* @param old the old attribute set
* @param name the non-null attribute name
* @param value the attribute value
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public AttributeSet addAttribute(AttributeSet old, Object name, Object value);
/** {@collect.stats}
* Adds a set of attributes to the element.
*
* @param old the old attribute set
* @param attr the attributes to add
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public AttributeSet addAttributes(AttributeSet old, AttributeSet attr);
/** {@collect.stats}
* Removes an attribute from the set.
*
* @param old the old attribute set
* @param name the non-null attribute name
* @return the updated attribute set
* @see MutableAttributeSet#removeAttribute
*/
public AttributeSet removeAttribute(AttributeSet old, Object name);
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param old the old attribute set
* @param names the attribute names
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public AttributeSet removeAttributes(AttributeSet old, Enumeration<?> names);
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param old the old attribute set
* @param attrs the attributes
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs);
/** {@collect.stats}
* Fetches an empty AttributeSet.
*
* @return the attribute set
*/
public AttributeSet getEmptySet();
/** {@collect.stats}
* Reclaims an attribute set.
* This is a way for a MutableAttributeSet to mark that it no
* longer need a particular immutable set. This is only necessary
* in 1.1 where there are no weak references. A 1.1 implementation
* would call this in its finalize method.
*
* @param a the attribute set to reclaim
*/
public void reclaim(AttributeSet a);
}
/** {@collect.stats}
* Implements the abstract part of an element. By default elements
* support attributes by having a field that represents the immutable
* part of the current attribute set for the element. The element itself
* implements MutableAttributeSet which can be used to modify the set
* by fetching a new immutable set. The immutable sets are provided
* by the AttributeContext associated with the document.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public abstract class AbstractElement implements Element, MutableAttributeSet, Serializable, TreeNode {
/** {@collect.stats}
* Creates a new AbstractElement.
*
* @param parent the parent element
* @param a the attributes for the element
* @since 1.4
*/
public AbstractElement(Element parent, AttributeSet a) {
this.parent = parent;
attributes = getAttributeContext().getEmptySet();
if (a != null) {
addAttributes(a);
}
}
private final void indent(PrintWriter out, int n) {
for (int i = 0; i < n; i++) {
out.print(" ");
}
}
/** {@collect.stats}
* Dumps a debugging representation of the element hierarchy.
*
* @param psOut the output stream
* @param indentAmount the indentation level >= 0
*/
public void dump(PrintStream psOut, int indentAmount) {
PrintWriter out;
try {
out = new PrintWriter(new OutputStreamWriter(psOut,"JavaEsc"),
true);
} catch (UnsupportedEncodingException e){
out = new PrintWriter(psOut,true);
}
indent(out, indentAmount);
if (getName() == null) {
out.print("<??");
} else {
out.print("<" + getName());
}
if (getAttributeCount() > 0) {
out.println("");
// dump the attributes
Enumeration names = attributes.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
indent(out, indentAmount + 1);
out.println(name + "=" + getAttribute(name));
}
indent(out, indentAmount);
}
out.println(">");
if (isLeaf()) {
indent(out, indentAmount+1);
out.print("[" + getStartOffset() + "," + getEndOffset() + "]");
Content c = getContent();
try {
String contentStr = c.getString(getStartOffset(),
getEndOffset() - getStartOffset())/*.trim()*/;
if (contentStr.length() > 40) {
contentStr = contentStr.substring(0, 40) + "...";
}
out.println("["+contentStr+"]");
} catch (BadLocationException e) {
;
}
} else {
int n = getElementCount();
for (int i = 0; i < n; i++) {
AbstractElement e = (AbstractElement) getElement(i);
e.dump(psOut, indentAmount+1);
}
}
}
// --- AttributeSet ----------------------------
// delegated to the immutable field "attributes"
/** {@collect.stats}
* Gets the number of attributes that are defined.
*
* @return the number of attributes >= 0
* @see AttributeSet#getAttributeCount
*/
public int getAttributeCount() {
return attributes.getAttributeCount();
}
/** {@collect.stats}
* Checks whether a given attribute is defined.
*
* @param attrName the non-null attribute name
* @return true if the attribute is defined
* @see AttributeSet#isDefined
*/
public boolean isDefined(Object attrName) {
return attributes.isDefined(attrName);
}
/** {@collect.stats}
* Checks whether two attribute sets are equal.
*
* @param attr the attribute set to check against
* @return true if the same
* @see AttributeSet#isEqual
*/
public boolean isEqual(AttributeSet attr) {
return attributes.isEqual(attr);
}
/** {@collect.stats}
* Copies a set of attributes.
*
* @return the copy
* @see AttributeSet#copyAttributes
*/
public AttributeSet copyAttributes() {
return attributes.copyAttributes();
}
/** {@collect.stats}
* Gets the value of an attribute.
*
* @param attrName the non-null attribute name
* @return the attribute value
* @see AttributeSet#getAttribute
*/
public Object getAttribute(Object attrName) {
Object value = attributes.getAttribute(attrName);
if (value == null) {
// The delegate nor it's resolvers had a match,
// so we'll try to resolve through the parent
// element.
AttributeSet a = (parent != null) ? parent.getAttributes() : null;
if (a != null) {
value = a.getAttribute(attrName);
}
}
return value;
}
/** {@collect.stats}
* Gets the names of all attributes.
*
* @return the attribute names as an enumeration
* @see AttributeSet#getAttributeNames
*/
public Enumeration<?> getAttributeNames() {
return attributes.getAttributeNames();
}
/** {@collect.stats}
* Checks whether a given attribute name/value is defined.
*
* @param name the non-null attribute name
* @param value the attribute value
* @return true if the name/value is defined
* @see AttributeSet#containsAttribute
*/
public boolean containsAttribute(Object name, Object value) {
return attributes.containsAttribute(name, value);
}
/** {@collect.stats}
* Checks whether the element contains all the attributes.
*
* @param attrs the attributes to check
* @return true if the element contains all the attributes
* @see AttributeSet#containsAttributes
*/
public boolean containsAttributes(AttributeSet attrs) {
return attributes.containsAttributes(attrs);
}
/** {@collect.stats}
* Gets the resolving parent.
* If not overridden, the resolving parent defaults to
* the parent element.
*
* @return the attributes from the parent, <code>null</code> if none
* @see AttributeSet#getResolveParent
*/
public AttributeSet getResolveParent() {
AttributeSet a = attributes.getResolveParent();
if ((a == null) && (parent != null)) {
a = parent.getAttributes();
}
return a;
}
// --- MutableAttributeSet ----------------------------------
// should fetch a new immutable record for the field
// "attributes".
/** {@collect.stats}
* Adds an attribute to the element.
*
* @param name the non-null attribute name
* @param value the attribute value
* @see MutableAttributeSet#addAttribute
*/
public void addAttribute(Object name, Object value) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.addAttribute(attributes, name, value);
}
/** {@collect.stats}
* Adds a set of attributes to the element.
*
* @param attr the attributes to add
* @see MutableAttributeSet#addAttribute
*/
public void addAttributes(AttributeSet attr) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.addAttributes(attributes, attr);
}
/** {@collect.stats}
* Removes an attribute from the set.
*
* @param name the non-null attribute name
* @see MutableAttributeSet#removeAttribute
*/
public void removeAttribute(Object name) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.removeAttribute(attributes, name);
}
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param names the attribute names
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(Enumeration<?> names) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
attributes = context.removeAttributes(attributes, names);
}
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param attrs the attributes
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(AttributeSet attrs) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
if (attrs == this) {
attributes = context.getEmptySet();
} else {
attributes = context.removeAttributes(attributes, attrs);
}
}
/** {@collect.stats}
* Sets the resolving parent.
*
* @param parent the parent, null if none
* @see MutableAttributeSet#setResolveParent
*/
public void setResolveParent(AttributeSet parent) {
checkForIllegalCast();
AttributeContext context = getAttributeContext();
if (parent != null) {
attributes =
context.addAttribute(attributes, StyleConstants.ResolveAttribute,
parent);
} else {
attributes =
context.removeAttribute(attributes, StyleConstants.ResolveAttribute);
}
}
private final void checkForIllegalCast() {
Thread t = getCurrentWriter();
if ((t == null) || (t != Thread.currentThread())) {
throw new StateInvariantError("Illegal cast to MutableAttributeSet");
}
}
// --- Element methods -------------------------------------
/** {@collect.stats}
* Retrieves the underlying model.
*
* @return the model
*/
public Document getDocument() {
return AbstractDocument.this;
}
/** {@collect.stats}
* Gets the parent of the element.
*
* @return the parent
*/
public Element getParentElement() {
return parent;
}
/** {@collect.stats}
* Gets the attributes for the element.
*
* @return the attribute set
*/
public AttributeSet getAttributes() {
return this;
}
/** {@collect.stats}
* Gets the name of the element.
*
* @return the name, null if none
*/
public String getName() {
if (attributes.isDefined(ElementNameAttribute)) {
return (String) attributes.getAttribute(ElementNameAttribute);
}
return null;
}
/** {@collect.stats}
* Gets the starting offset in the model for the element.
*
* @return the offset >= 0
*/
public abstract int getStartOffset();
/** {@collect.stats}
* Gets the ending offset in the model for the element.
*
* @return the offset >= 0
*/
public abstract int getEndOffset();
/** {@collect.stats}
* Gets a child element.
*
* @param index the child index, >= 0 && < getElementCount()
* @return the child element
*/
public abstract Element getElement(int index);
/** {@collect.stats}
* Gets the number of children for the element.
*
* @return the number of children >= 0
*/
public abstract int getElementCount();
/** {@collect.stats}
* Gets the child element index closest to the given model offset.
*
* @param offset the offset >= 0
* @return the element index >= 0
*/
public abstract int getElementIndex(int offset);
/** {@collect.stats}
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public abstract boolean isLeaf();
// --- TreeNode methods -------------------------------------
/** {@collect.stats}
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
public TreeNode getChildAt(int childIndex) {
return (TreeNode)getElement(childIndex);
}
/** {@collect.stats}
* Returns the number of children <code>TreeNode</code>'s
* receiver contains.
* @return the number of children <code>TreeNodews</code>'s
* receiver contains
*/
public int getChildCount() {
return getElementCount();
}
/** {@collect.stats}
* Returns the parent <code>TreeNode</code> of the receiver.
* @return the parent <code>TreeNode</code> of the receiver
*/
public TreeNode getParent() {
return (TreeNode)getParentElement();
}
/** {@collect.stats}
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
* @param node the location of interest
* @return the index of <code>node</code> in the receiver's
* children, or -1 if absent
*/
public int getIndex(TreeNode node) {
for(int counter = getChildCount() - 1; counter >= 0; counter--)
if(getChildAt(counter) == node)
return counter;
return -1;
}
/** {@collect.stats}
* Returns true if the receiver allows children.
* @return true if the receiver allows children, otherwise false
*/
public abstract boolean getAllowsChildren();
/** {@collect.stats}
* Returns the children of the receiver as an
* <code>Enumeration</code>.
* @return the children of the receiver as an <code>Enumeration</code>
*/
public abstract Enumeration children();
// --- serialization ---------------------------------------------
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
StyleContext.writeAttributeSet(s, attributes);
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
MutableAttributeSet attr = new SimpleAttributeSet();
StyleContext.readAttributeSet(s, attr);
AttributeContext context = getAttributeContext();
attributes = context.addAttributes(SimpleAttributeSet.EMPTY, attr);
}
// ---- variables -----------------------------------------------------
private Element parent;
private transient AttributeSet attributes;
}
/** {@collect.stats}
* Implements a composite element that contains other elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public class BranchElement extends AbstractElement {
/** {@collect.stats}
* Constructs a composite element that initially contains
* no children.
*
* @param parent The parent element
* @param a the attributes for the element
* @since 1.4
*/
public BranchElement(Element parent, AttributeSet a) {
super(parent, a);
children = new AbstractElement[1];
nchildren = 0;
lastIndex = -1;
}
/** {@collect.stats}
* Gets the child element that contains
* the given model position.
*
* @param pos the position >= 0
* @return the element, null if none
*/
public Element positionToElement(int pos) {
int index = getElementIndex(pos);
Element child = children[index];
int p0 = child.getStartOffset();
int p1 = child.getEndOffset();
if ((pos >= p0) && (pos < p1)) {
return child;
}
return null;
}
/** {@collect.stats}
* Replaces content with a new set of elements.
*
* @param offset the starting offset >= 0
* @param length the length to replace >= 0
* @param elems the new elements
*/
public void replace(int offset, int length, Element[] elems) {
int delta = elems.length - length;
int src = offset + length;
int nmove = nchildren - src;
int dest = src + delta;
if ((nchildren + delta) >= children.length) {
// need to grow the array
int newLength = Math.max(2*children.length, nchildren + delta);
AbstractElement[] newChildren = new AbstractElement[newLength];
System.arraycopy(children, 0, newChildren, 0, offset);
System.arraycopy(elems, 0, newChildren, offset, elems.length);
System.arraycopy(children, src, newChildren, dest, nmove);
children = newChildren;
} else {
// patch the existing array
System.arraycopy(children, src, children, dest, nmove);
System.arraycopy(elems, 0, children, offset, elems.length);
}
nchildren = nchildren + delta;
}
/** {@collect.stats}
* Converts the element to a string.
*
* @return the string
*/
public String toString() {
return "BranchElement(" + getName() + ") " + getStartOffset() + "," +
getEndOffset() + "\n";
}
// --- Element methods -----------------------------------
/** {@collect.stats}
* Gets the element name.
*
* @return the element name
*/
public String getName() {
String nm = super.getName();
if (nm == null) {
nm = ParagraphElementName;
}
return nm;
}
/** {@collect.stats}
* Gets the starting offset in the model for the element.
*
* @return the offset >= 0
*/
public int getStartOffset() {
return children[0].getStartOffset();
}
/** {@collect.stats}
* Gets the ending offset in the model for the element.
* @throws NullPointerException if this element has no children
*
* @return the offset >= 0
*/
public int getEndOffset() {
Element child =
(nchildren > 0) ? children[nchildren - 1] : children[0];
return child.getEndOffset();
}
/** {@collect.stats}
* Gets a child element.
*
* @param index the child index, >= 0 && < getElementCount()
* @return the child element, null if none
*/
public Element getElement(int index) {
if (index < nchildren) {
return children[index];
}
return null;
}
/** {@collect.stats}
* Gets the number of children for the element.
*
* @return the number of children >= 0
*/
public int getElementCount() {
return nchildren;
}
/** {@collect.stats}
* Gets the child element index closest to the given model offset.
*
* @param offset the offset >= 0
* @return the element index >= 0
*/
public int getElementIndex(int offset) {
int index;
int lower = 0;
int upper = nchildren - 1;
int mid = 0;
int p0 = getStartOffset();
int p1;
if (nchildren == 0) {
return 0;
}
if (offset >= getEndOffset()) {
return nchildren - 1;
}
// see if the last index can be used.
if ((lastIndex >= lower) && (lastIndex <= upper)) {
Element lastHit = children[lastIndex];
p0 = lastHit.getStartOffset();
p1 = lastHit.getEndOffset();
if ((offset >= p0) && (offset < p1)) {
return lastIndex;
}
// last index wasn't a hit, but it does give useful info about
// where a hit (if any) would be.
if (offset < p0) {
upper = lastIndex;
} else {
lower = lastIndex;
}
}
while (lower <= upper) {
mid = lower + ((upper - lower) / 2);
Element elem = children[mid];
p0 = elem.getStartOffset();
p1 = elem.getEndOffset();
if ((offset >= p0) && (offset < p1)) {
// found the location
index = mid;
lastIndex = index;
return index;
} else if (offset < p0) {
upper = mid - 1;
} else {
lower = mid + 1;
}
}
// didn't find it, but we indicate the index of where it would belong
if (offset < p0) {
index = mid;
} else {
index = mid + 1;
}
lastIndex = index;
return index;
}
/** {@collect.stats}
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public boolean isLeaf() {
return false;
}
// ------ TreeNode ----------------------------------------------
/** {@collect.stats}
* Returns true if the receiver allows children.
* @return true if the receiver allows children, otherwise false
*/
public boolean getAllowsChildren() {
return true;
}
/** {@collect.stats}
* Returns the children of the receiver as an
* <code>Enumeration</code>.
* @return the children of the receiver
*/
public Enumeration children() {
if(nchildren == 0)
return null;
Vector tempVector = new Vector(nchildren);
for(int counter = 0; counter < nchildren; counter++)
tempVector.addElement(children[counter]);
return tempVector.elements();
}
// ------ members ----------------------------------------------
private AbstractElement[] children;
private int nchildren;
private int lastIndex;
}
/** {@collect.stats}
* Implements an element that directly represents content of
* some kind.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see Element
*/
public class LeafElement extends AbstractElement {
/** {@collect.stats}
* Constructs an element that represents content within the
* document (has no children).
*
* @param parent The parent element
* @param a The element attributes
* @param offs0 The start offset >= 0
* @param offs1 The end offset >= offs0
* @since 1.4
*/
public LeafElement(Element parent, AttributeSet a, int offs0, int offs1) {
super(parent, a);
try {
p0 = createPosition(offs0);
p1 = createPosition(offs1);
} catch (BadLocationException e) {
p0 = null;
p1 = null;
throw new StateInvariantError("Can't create Position references");
}
}
/** {@collect.stats}
* Converts the element to a string.
*
* @return the string
*/
public String toString() {
return "LeafElement(" + getName() + ") " + p0 + "," + p1 + "\n";
}
// --- Element methods ---------------------------------------------
/** {@collect.stats}
* Gets the starting offset in the model for the element.
*
* @return the offset >= 0
*/
public int getStartOffset() {
return p0.getOffset();
}
/** {@collect.stats}
* Gets the ending offset in the model for the element.
*
* @return the offset >= 0
*/
public int getEndOffset() {
return p1.getOffset();
}
/** {@collect.stats}
* Gets the element name.
*
* @return the name
*/
public String getName() {
String nm = super.getName();
if (nm == null) {
nm = ContentElementName;
}
return nm;
}
/** {@collect.stats}
* Gets the child element index closest to the given model offset.
*
* @param pos the offset >= 0
* @return the element index >= 0
*/
public int getElementIndex(int pos) {
return -1;
}
/** {@collect.stats}
* Gets a child element.
*
* @param index the child index, >= 0 && < getElementCount()
* @return the child element
*/
public Element getElement(int index) {
return null;
}
/** {@collect.stats}
* Returns the number of child elements.
*
* @return the number of children >= 0
*/
public int getElementCount() {
return 0;
}
/** {@collect.stats}
* Checks whether the element is a leaf.
*
* @return true if a leaf
*/
public boolean isLeaf() {
return true;
}
// ------ TreeNode ----------------------------------------------
/** {@collect.stats}
* Returns true if the receiver allows children.
* @return true if the receiver allows children, otherwise false
*/
public boolean getAllowsChildren() {
return false;
}
/** {@collect.stats}
* Returns the children of the receiver as an
* <code>Enumeration</code>.
* @return the children of the receiver
*/
public Enumeration children() {
return null;
}
// --- serialization ---------------------------------------------
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(p0.getOffset());
s.writeInt(p1.getOffset());
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
// set the range with positions that track change
int off0 = s.readInt();
int off1 = s.readInt();
try {
p0 = createPosition(off0);
p1 = createPosition(off1);
} catch (BadLocationException e) {
p0 = null;
p1 = null;
throw new IOException("Can't restore Position references");
}
}
// ---- members -----------------------------------------------------
private transient Position p0;
private transient Position p1;
}
/** {@collect.stats}
* Represents the root element of the bidirectional element structure.
* The root element is the only element in the bidi element structure
* which contains children.
*/
class BidiRootElement extends BranchElement {
BidiRootElement() {
super( null, null );
}
/** {@collect.stats}
* Gets the name of the element.
* @return the name
*/
public String getName() {
return "bidi root";
}
}
/** {@collect.stats}
* Represents an element of the bidirectional element structure.
*/
class BidiElement extends LeafElement {
/** {@collect.stats}
* Creates a new BidiElement.
*/
BidiElement(Element parent, int start, int end, int level) {
super(parent, new SimpleAttributeSet(), start, end);
addAttribute(StyleConstants.BidiLevel, new Integer(level));
//System.out.println("BidiElement: start = " + start
// + " end = " + end + " level = " + level );
}
/** {@collect.stats}
* Gets the name of the element.
* @return the name
*/
public String getName() {
return BidiElementName;
}
int getLevel() {
Integer o = (Integer) getAttribute(StyleConstants.BidiLevel);
if (o != null) {
return o.intValue();
}
return 0; // Level 0 is base level (non-embedded) left-to-right
}
boolean isLeftToRight() {
return ((getLevel() % 2) == 0);
}
}
/** {@collect.stats}
* Stores document changes as the document is being
* modified. Can subsequently be used for change notification
* when done with the document modification transaction.
* This is used by the AbstractDocument class and its extensions
* for broadcasting change information to the document listeners.
*/
public class DefaultDocumentEvent extends CompoundEdit implements DocumentEvent {
/** {@collect.stats}
* Constructs a change record.
*
* @param offs the offset into the document of the change >= 0
* @param len the length of the change >= 0
* @param type the type of event (DocumentEvent.EventType)
* @since 1.4
*/
public DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type) {
super();
offset = offs;
length = len;
this.type = type;
}
/** {@collect.stats}
* Returns a string description of the change event.
*
* @return a string
*/
public String toString() {
return edits.toString();
}
// --- CompoundEdit methods --------------------------
/** {@collect.stats}
* Adds a document edit. If the number of edits crosses
* a threshold, this switches on a hashtable lookup for
* ElementChange implementations since access of these
* needs to be relatively quick.
*
* @param anEdit a document edit record
* @return true if the edit was added
*/
public boolean addEdit(UndoableEdit anEdit) {
// if the number of changes gets too great, start using
// a hashtable for to locate the change for a given element.
if ((changeLookup == null) && (edits.size() > 10)) {
changeLookup = new Hashtable();
int n = edits.size();
for (int i = 0; i < n; i++) {
Object o = edits.elementAt(i);
if (o instanceof DocumentEvent.ElementChange) {
DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) o;
changeLookup.put(ec.getElement(), ec);
}
}
}
// if we have a hashtable... add the entry if it's
// an ElementChange.
if ((changeLookup != null) && (anEdit instanceof DocumentEvent.ElementChange)) {
DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) anEdit;
changeLookup.put(ec.getElement(), ec);
}
return super.addEdit(anEdit);
}
/** {@collect.stats}
* Redoes a change.
*
* @exception CannotRedoException if the change cannot be redone
*/
public void redo() throws CannotRedoException {
writeLock();
try {
// change the state
super.redo();
// fire a DocumentEvent to notify the view(s)
UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, false);
if (type == DocumentEvent.EventType.INSERT) {
fireInsertUpdate(ev);
} else if (type == DocumentEvent.EventType.REMOVE) {
fireRemoveUpdate(ev);
} else {
fireChangedUpdate(ev);
}
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* Undoes a change.
*
* @exception CannotUndoException if the change cannot be undone
*/
public void undo() throws CannotUndoException {
writeLock();
try {
// change the state
super.undo();
// fire a DocumentEvent to notify the view(s)
UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, true);
if (type == DocumentEvent.EventType.REMOVE) {
fireInsertUpdate(ev);
} else if (type == DocumentEvent.EventType.INSERT) {
fireRemoveUpdate(ev);
} else {
fireChangedUpdate(ev);
}
} finally {
writeUnlock();
}
}
/** {@collect.stats}
* DefaultDocument events are significant. If you wish to aggregate
* DefaultDocumentEvents to present them as a single edit to the user
* place them into a CompoundEdit.
*
* @return whether the event is significant for edit undo purposes
*/
public boolean isSignificant() {
return true;
}
/** {@collect.stats}
* Provides a localized, human readable description of this edit
* suitable for use in, say, a change log.
*
* @return the description
*/
public String getPresentationName() {
DocumentEvent.EventType type = getType();
if(type == DocumentEvent.EventType.INSERT)
return UIManager.getString("AbstractDocument.additionText");
if(type == DocumentEvent.EventType.REMOVE)
return UIManager.getString("AbstractDocument.deletionText");
return UIManager.getString("AbstractDocument.styleChangeText");
}
/** {@collect.stats}
* Provides a localized, human readable description of the undoable
* form of this edit, e.g. for use as an Undo menu item. Typically
* derived from getDescription();
*
* @return the description
*/
public String getUndoPresentationName() {
return UIManager.getString("AbstractDocument.undoText") + " " +
getPresentationName();
}
/** {@collect.stats}
* Provides a localized, human readable description of the redoable
* form of this edit, e.g. for use as a Redo menu item. Typically
* derived from getPresentationName();
*
* @return the description
*/
public String getRedoPresentationName() {
return UIManager.getString("AbstractDocument.redoText") + " " +
getPresentationName();
}
// --- DocumentEvent methods --------------------------
/** {@collect.stats}
* Returns the type of event.
*
* @return the event type as a DocumentEvent.EventType
* @see DocumentEvent#getType
*/
public DocumentEvent.EventType getType() {
return type;
}
/** {@collect.stats}
* Returns the offset within the document of the start of the change.
*
* @return the offset >= 0
* @see DocumentEvent#getOffset
*/
public int getOffset() {
return offset;
}
/** {@collect.stats}
* Returns the length of the change.
*
* @return the length >= 0
* @see DocumentEvent#getLength
*/
public int getLength() {
return length;
}
/** {@collect.stats}
* Gets the document that sourced the change event.
*
* @return the document
* @see DocumentEvent#getDocument
*/
public Document getDocument() {
return AbstractDocument.this;
}
/** {@collect.stats}
* Gets the changes for an element.
*
* @param elem the element
* @return the changes
*/
public DocumentEvent.ElementChange getChange(Element elem) {
if (changeLookup != null) {
return (DocumentEvent.ElementChange) changeLookup.get(elem);
}
int n = edits.size();
for (int i = 0; i < n; i++) {
Object o = edits.elementAt(i);
if (o instanceof DocumentEvent.ElementChange) {
DocumentEvent.ElementChange c = (DocumentEvent.ElementChange) o;
if (elem.equals(c.getElement())) {
return c;
}
}
}
return null;
}
// --- member variables ------------------------------------
private int offset;
private int length;
private Hashtable changeLookup;
private DocumentEvent.EventType type;
}
/** {@collect.stats}
* This event used when firing document changes while Undo/Redo
* operations. It just wraps DefaultDocumentEvent and delegates
* all calls to it except getType() which depends on operation
* (Undo or Redo).
*/
class UndoRedoDocumentEvent implements DocumentEvent {
private DefaultDocumentEvent src = null;
private boolean isUndo;
private EventType type = null;
public UndoRedoDocumentEvent(DefaultDocumentEvent src, boolean isUndo) {
this.src = src;
this.isUndo = isUndo;
if(isUndo) {
if(src.getType().equals(EventType.INSERT)) {
type = EventType.REMOVE;
} else if(src.getType().equals(EventType.REMOVE)) {
type = EventType.INSERT;
} else {
type = src.getType();
}
} else {
type = src.getType();
}
}
public DefaultDocumentEvent getSource() {
return src;
}
// DocumentEvent methods delegated to DefaultDocumentEvent source
// except getType() which depends on operation (Undo or Redo).
public int getOffset() {
return src.getOffset();
}
public int getLength() {
return src.getLength();
}
public Document getDocument() {
return src.getDocument();
}
public DocumentEvent.EventType getType() {
return type;
}
public DocumentEvent.ElementChange getChange(Element elem) {
return src.getChange(elem);
}
}
/** {@collect.stats}
* An implementation of ElementChange that can be added to the document
* event.
*/
public static class ElementEdit extends AbstractUndoableEdit implements DocumentEvent.ElementChange {
/** {@collect.stats}
* Constructs an edit record. This does not modify the element
* so it can safely be used to <em>catch up</em> a view to the
* current model state for views that just attached to a model.
*
* @param e the element
* @param index the index into the model >= 0
* @param removed a set of elements that were removed
* @param added a set of elements that were added
*/
public ElementEdit(Element e, int index, Element[] removed, Element[] added) {
super();
this.e = e;
this.index = index;
this.removed = removed;
this.added = added;
}
/** {@collect.stats}
* Returns the underlying element.
*
* @return the element
*/
public Element getElement() {
return e;
}
/** {@collect.stats}
* Returns the index into the list of elements.
*
* @return the index >= 0
*/
public int getIndex() {
return index;
}
/** {@collect.stats}
* Gets a list of children that were removed.
*
* @return the list
*/
public Element[] getChildrenRemoved() {
return removed;
}
/** {@collect.stats}
* Gets a list of children that were added.
*
* @return the list
*/
public Element[] getChildrenAdded() {
return added;
}
/** {@collect.stats}
* Redoes a change.
*
* @exception CannotRedoException if the change cannot be redone
*/
public void redo() throws CannotRedoException {
super.redo();
// Since this event will be reused, switch around added/removed.
Element[] tmp = removed;
removed = added;
added = tmp;
// PENDING(prinz) need MutableElement interface, canRedo() should check
((AbstractDocument.BranchElement)e).replace(index, removed.length, added);
}
/** {@collect.stats}
* Undoes a change.
*
* @exception CannotUndoException if the change cannot be undone
*/
public void undo() throws CannotUndoException {
super.undo();
// PENDING(prinz) need MutableElement interface, canUndo() should check
((AbstractDocument.BranchElement)e).replace(index, added.length, removed);
// Since this event will be reused, switch around added/removed.
Element[] tmp = removed;
removed = added;
added = tmp;
}
private Element e;
private int index;
private Element[] removed;
private Element[] added;
}
private class DefaultFilterBypass extends DocumentFilter.FilterBypass {
public Document getDocument() {
return AbstractDocument.this;
}
public void remove(int offset, int length) throws
BadLocationException {
handleRemove(offset, length);
}
public void insertString(int offset, String string,
AttributeSet attr) throws
BadLocationException {
handleInsertString(offset, string, attr);
}
public void replace(int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
handleRemove(offset, length);
handleInsertString(offset, text, attrs);
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text;
import java.awt.*;
import java.util.*;
import java.io.*;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.ChangeEvent;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
import sun.font.FontManager;
/** {@collect.stats}
* A pool of styles and their associated resources. This class determines
* the lifetime of a group of resources by being a container that holds
* caches for various resources such as font and color that get reused
* by the various style definitions. This can be shared by multiple
* documents if desired to maximize the sharing of related resources.
* <p>
* This class also provides efficient support for small sets of attributes
* and compresses them by sharing across uses and taking advantage of
* their immutable nature. Since many styles are replicated, the potential
* for sharing is significant, and copies can be extremely cheap.
* Larger sets reduce the possibility of sharing, and therefore revert
* automatically to a less space-efficient implementation.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
public class StyleContext implements Serializable, AbstractDocument.AttributeContext {
/** {@collect.stats}
* Returns default AttributeContext shared by all documents that
* don't bother to define/supply their own context.
*
* @return the context
*/
public static final StyleContext getDefaultStyleContext() {
if (defaultContext == null) {
defaultContext = new StyleContext();
}
return defaultContext;
}
private static StyleContext defaultContext;
/** {@collect.stats}
* Creates a new StyleContext object.
*/
public StyleContext() {
styles = new NamedStyle(null);
addStyle(DEFAULT_STYLE, null);
}
/** {@collect.stats}
* Adds a new style into the style hierarchy. Style attributes
* resolve from bottom up so an attribute specified in a child
* will override an attribute specified in the parent.
*
* @param nm the name of the style (must be unique within the
* collection of named styles in the document). The name may
* be null if the style is unnamed, but the caller is responsible
* for managing the reference returned as an unnamed style can't
* be fetched by name. An unnamed style may be useful for things
* like character attribute overrides such as found in a style
* run.
* @param parent the parent style. This may be null if unspecified
* attributes need not be resolved in some other style.
* @return the created style
*/
public Style addStyle(String nm, Style parent) {
Style style = new NamedStyle(nm, parent);
if (nm != null) {
// add a named style, a class of attributes
styles.addAttribute(nm, style);
}
return style;
}
/** {@collect.stats}
* Removes a named style previously added to the document.
*
* @param nm the name of the style to remove
*/
public void removeStyle(String nm) {
styles.removeAttribute(nm);
}
/** {@collect.stats}
* Fetches a named style previously added to the document
*
* @param nm the name of the style
* @return the style
*/
public Style getStyle(String nm) {
return (Style) styles.getAttribute(nm);
}
/** {@collect.stats}
* Fetches the names of the styles defined.
*
* @return the list of names as an enumeration
*/
public Enumeration<?> getStyleNames() {
return styles.getAttributeNames();
}
/** {@collect.stats}
* Adds a listener to track when styles are added
* or removed.
*
* @param l the change listener
*/
public void addChangeListener(ChangeListener l) {
styles.addChangeListener(l);
}
/** {@collect.stats}
* Removes a listener that was tracking styles being
* added or removed.
*
* @param l the change listener
*/
public void removeChangeListener(ChangeListener l) {
styles.removeChangeListener(l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this StyleContext with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return ((NamedStyle)styles).getChangeListeners();
}
/** {@collect.stats}
* Gets the font from an attribute set. This is
* implemented to try and fetch a cached font
* for the given AttributeSet, and if that fails
* the font features are resolved and the
* font is fetched from the low-level font cache.
*
* @param attr the attribute set
* @return the font
*/
public Font getFont(AttributeSet attr) {
// PENDING(prinz) add cache behavior
int style = Font.PLAIN;
if (StyleConstants.isBold(attr)) {
style |= Font.BOLD;
}
if (StyleConstants.isItalic(attr)) {
style |= Font.ITALIC;
}
String family = StyleConstants.getFontFamily(attr);
int size = StyleConstants.getFontSize(attr);
/** {@collect.stats}
* if either superscript or subscript is
* is set, we need to reduce the font size
* by 2.
*/
if (StyleConstants.isSuperscript(attr) ||
StyleConstants.isSubscript(attr)) {
size -= 2;
}
return getFont(family, style, size);
}
/** {@collect.stats}
* Takes a set of attributes and turn it into a foreground color
* specification. This might be used to specify things
* like brighter, more hue, etc. By default it simply returns
* the value specified by the StyleConstants.Foreground attribute.
*
* @param attr the set of attributes
* @return the color
*/
public Color getForeground(AttributeSet attr) {
return StyleConstants.getForeground(attr);
}
/** {@collect.stats}
* Takes a set of attributes and turn it into a background color
* specification. This might be used to specify things
* like brighter, more hue, etc. By default it simply returns
* the value specified by the StyleConstants.Background attribute.
*
* @param attr the set of attributes
* @return the color
*/
public Color getBackground(AttributeSet attr) {
return StyleConstants.getBackground(attr);
}
/** {@collect.stats}
* Gets a new font. This returns a Font from a cache
* if a cached font exists. If not, a Font is added to
* the cache. This is basically a low-level cache for
* 1.1 font features.
*
* @param family the font family (such as "Monospaced")
* @param style the style of the font (such as Font.PLAIN)
* @param size the point size >= 1
* @return the new font
*/
public Font getFont(String family, int style, int size) {
fontSearch.setValue(family, style, size);
Font f = (Font) fontTable.get(fontSearch);
if (f == null) {
// haven't seen this one yet.
Style defaultStyle =
getStyle(StyleContext.DEFAULT_STYLE);
if (defaultStyle != null) {
final String FONT_ATTRIBUTE_KEY = "FONT_ATTRIBUTE_KEY";
Font defaultFont =
(Font) defaultStyle.getAttribute(FONT_ATTRIBUTE_KEY);
if (defaultFont != null
&& defaultFont.getFamily().equalsIgnoreCase(family)) {
f = defaultFont.deriveFont(style, size);
}
}
if (f == null) {
f = new Font(family, style, size);
}
if (! FontManager.fontSupportsDefaultEncoding(f)) {
f = FontManager.getCompositeFontUIResource(f);
}
FontKey key = new FontKey(family, style, size);
fontTable.put(key, f);
}
return f;
}
/** {@collect.stats}
* Returns font metrics for a font.
*
* @param f the font
* @return the metrics
*/
public FontMetrics getFontMetrics(Font f) {
// The Toolkit implementations cache, so we just forward
// to the default toolkit.
return Toolkit.getDefaultToolkit().getFontMetrics(f);
}
// --- AttributeContext methods --------------------
/** {@collect.stats}
* Adds an attribute to the given set, and returns
* the new representative set.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param old the old attribute set
* @param name the non-null attribute name
* @param value the attribute value
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public synchronized AttributeSet addAttribute(AttributeSet old, Object name, Object value) {
if ((old.getAttributeCount() + 1) <= getCompressionThreshold()) {
// build a search key and find/create an immutable and unique
// set.
search.removeAttributes(search);
search.addAttributes(old);
search.addAttribute(name, value);
reclaim(old);
return getImmutableUniqueSet();
}
MutableAttributeSet ma = getMutableAttributeSet(old);
ma.addAttribute(name, value);
return ma;
}
/** {@collect.stats}
* Adds a set of attributes to the element.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param old the old attribute set
* @param attr the attributes to add
* @return the updated attribute set
* @see MutableAttributeSet#addAttribute
*/
public synchronized AttributeSet addAttributes(AttributeSet old, AttributeSet attr) {
if ((old.getAttributeCount() + attr.getAttributeCount()) <= getCompressionThreshold()) {
// build a search key and find/create an immutable and unique
// set.
search.removeAttributes(search);
search.addAttributes(old);
search.addAttributes(attr);
reclaim(old);
return getImmutableUniqueSet();
}
MutableAttributeSet ma = getMutableAttributeSet(old);
ma.addAttributes(attr);
return ma;
}
/** {@collect.stats}
* Removes an attribute from the set.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param old the old set of attributes
* @param name the non-null attribute name
* @return the updated attribute set
* @see MutableAttributeSet#removeAttribute
*/
public synchronized AttributeSet removeAttribute(AttributeSet old, Object name) {
if ((old.getAttributeCount() - 1) <= getCompressionThreshold()) {
// build a search key and find/create an immutable and unique
// set.
search.removeAttributes(search);
search.addAttributes(old);
search.removeAttribute(name);
reclaim(old);
return getImmutableUniqueSet();
}
MutableAttributeSet ma = getMutableAttributeSet(old);
ma.removeAttribute(name);
return ma;
}
/** {@collect.stats}
* Removes a set of attributes for the element.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param old the old attribute set
* @param names the attribute names
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public synchronized AttributeSet removeAttributes(AttributeSet old, Enumeration<?> names) {
if (old.getAttributeCount() <= getCompressionThreshold()) {
// build a search key and find/create an immutable and unique
// set.
search.removeAttributes(search);
search.addAttributes(old);
search.removeAttributes(names);
reclaim(old);
return getImmutableUniqueSet();
}
MutableAttributeSet ma = getMutableAttributeSet(old);
ma.removeAttributes(names);
return ma;
}
/** {@collect.stats}
* Removes a set of attributes for the element.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param old the old attribute set
* @param attrs the attributes
* @return the updated attribute set
* @see MutableAttributeSet#removeAttributes
*/
public synchronized AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs) {
if (old.getAttributeCount() <= getCompressionThreshold()) {
// build a search key and find/create an immutable and unique
// set.
search.removeAttributes(search);
search.addAttributes(old);
search.removeAttributes(attrs);
reclaim(old);
return getImmutableUniqueSet();
}
MutableAttributeSet ma = getMutableAttributeSet(old);
ma.removeAttributes(attrs);
return ma;
}
/** {@collect.stats}
* Fetches an empty AttributeSet.
*
* @return the set
*/
public AttributeSet getEmptySet() {
return SimpleAttributeSet.EMPTY;
}
/** {@collect.stats}
* Returns a set no longer needed by the MutableAttributeSet implmentation.
* This is useful for operation under 1.1 where there are no weak
* references. This would typically be called by the finalize method
* of the MutableAttributeSet implementation.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
* to Use Threads</A> for more information.
*
* @param a the set to reclaim
*/
public void reclaim(AttributeSet a) {
if (SwingUtilities.isEventDispatchThread()) {
attributesPool.size(); // force WeakHashMap to expunge stale entries
}
// if current thread is not event dispatching thread
// do not bother with expunging stale entries.
}
// --- local methods -----------------------------------------------
/** {@collect.stats}
* Returns the maximum number of key/value pairs to try and
* compress into unique/immutable sets. Any sets above this
* limit will use hashtables and be a MutableAttributeSet.
*
* @return the threshold
*/
protected int getCompressionThreshold() {
return THRESHOLD;
}
/** {@collect.stats}
* Create a compact set of attributes that might be shared.
* This is a hook for subclasses that want to alter the
* behavior of SmallAttributeSet. This can be reimplemented
* to return an AttributeSet that provides some sort of
* attribute conversion.
*
* @param a The set of attributes to be represented in the
* the compact form.
*/
protected SmallAttributeSet createSmallAttributeSet(AttributeSet a) {
return new SmallAttributeSet(a);
}
/** {@collect.stats}
* Create a large set of attributes that should trade off
* space for time. This set will not be shared. This is
* a hook for subclasses that want to alter the behavior
* of the larger attribute storage format (which is
* SimpleAttributeSet by default). This can be reimplemented
* to return a MutableAttributeSet that provides some sort of
* attribute conversion.
*
* @param a The set of attributes to be represented in the
* the larger form.
*/
protected MutableAttributeSet createLargeAttributeSet(AttributeSet a) {
return new SimpleAttributeSet(a);
}
/** {@collect.stats}
* Clean the unused immutable sets out of the hashtable.
*/
synchronized void removeUnusedSets() {
attributesPool.size(); // force WeakHashMap to expunge stale entries
}
/** {@collect.stats}
* Search for an existing attribute set using the current search
* parameters. If a matching set is found, return it. If a match
* is not found, we create a new set and add it to the pool.
*/
AttributeSet getImmutableUniqueSet() {
// PENDING(prinz) should consider finding a alternative to
// generating extra garbage on search key.
SmallAttributeSet key = createSmallAttributeSet(search);
WeakReference reference = (WeakReference)attributesPool.get(key);
SmallAttributeSet a;
if (reference == null
|| (a = (SmallAttributeSet)reference.get()) == null) {
a = key;
attributesPool.put(a, new WeakReference(a));
}
return a;
}
/** {@collect.stats}
* Creates a mutable attribute set to hand out because the current
* needs are too big to try and use a shared version.
*/
MutableAttributeSet getMutableAttributeSet(AttributeSet a) {
if (a instanceof MutableAttributeSet &&
a != SimpleAttributeSet.EMPTY) {
return (MutableAttributeSet) a;
}
return createLargeAttributeSet(a);
}
/** {@collect.stats}
* Converts a StyleContext to a String.
*
* @return the string
*/
public String toString() {
removeUnusedSets();
String s = "";
Iterator iterator = attributesPool.keySet().iterator();
while (iterator.hasNext()) {
SmallAttributeSet set = (SmallAttributeSet)iterator.next();
s = s + set + "\n";
}
return s;
}
// --- serialization ---------------------------------------------
/** {@collect.stats}
* Context-specific handling of writing out attributes
*/
public void writeAttributes(ObjectOutputStream out,
AttributeSet a) throws IOException {
writeAttributeSet(out, a);
}
/** {@collect.stats}
* Context-specific handling of reading in attributes
*/
public void readAttributes(ObjectInputStream in,
MutableAttributeSet a) throws ClassNotFoundException, IOException {
readAttributeSet(in, a);
}
/** {@collect.stats}
* Writes a set of attributes to the given object stream
* for the purpose of serialization. This will take
* special care to deal with static attribute keys that
* have been registered wit the
* <code>registerStaticAttributeKey</code> method.
* Any attribute key not regsitered as a static key
* will be serialized directly. All values are expected
* to be serializable.
*
* @param out the output stream
* @param a the attribute set
* @exception IOException on any I/O error
*/
public static void writeAttributeSet(ObjectOutputStream out,
AttributeSet a) throws IOException {
int n = a.getAttributeCount();
out.writeInt(n);
Enumeration keys = a.getAttributeNames();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof Serializable) {
out.writeObject(key);
} else {
Object ioFmt = freezeKeyMap.get(key);
if (ioFmt == null) {
throw new NotSerializableException(key.getClass().
getName() + " is not serializable as a key in an AttributeSet");
}
out.writeObject(ioFmt);
}
Object value = a.getAttribute(key);
Object ioFmt = freezeKeyMap.get(value);
if (value instanceof Serializable) {
out.writeObject((ioFmt != null) ? ioFmt : value);
} else {
if (ioFmt == null) {
throw new NotSerializableException(value.getClass().
getName() + " is not serializable as a value in an AttributeSet");
}
out.writeObject(ioFmt);
}
}
}
/** {@collect.stats}
* Reads a set of attributes from the given object input
* stream that have been previously written out with
* <code>writeAttributeSet</code>. This will try to restore
* keys that were static objects to the static objects in
* the current virtual machine considering only those keys
* that have been registered with the
* <code>registerStaticAttributeKey</code> method.
* The attributes retrieved from the stream will be placed
* into the given mutable set.
*
* @param in the object stream to read the attribute data from.
* @param a the attribute set to place the attribute
* definitions in.
* @exception ClassNotFoundException passed upward if encountered
* when reading the object stream.
* @exception IOException passed upward if encountered when
* reading the object stream.
*/
public static void readAttributeSet(ObjectInputStream in,
MutableAttributeSet a) throws ClassNotFoundException, IOException {
int n = in.readInt();
for (int i = 0; i < n; i++) {
Object key = in.readObject();
Object value = in.readObject();
if (thawKeyMap != null) {
Object staticKey = thawKeyMap.get(key);
if (staticKey != null) {
key = staticKey;
}
Object staticValue = thawKeyMap.get(value);
if (staticValue != null) {
value = staticValue;
}
}
a.addAttribute(key, value);
}
}
/** {@collect.stats}
* Registers an object as a static object that is being
* used as a key in attribute sets. This allows the key
* to be treated specially for serialization.
* <p>
* For operation under a 1.1 virtual machine, this
* uses the value returned by <code>toString</code>
* concatenated to the classname. The value returned
* by toString should not have the class reference
* in it (ie it should be reimplemented from the
* definition in Object) in order to be the same when
* recomputed later.
*
* @param key the non-null object key
*/
public static void registerStaticAttributeKey(Object key) {
String ioFmt = key.getClass().getName() + "." + key.toString();
if (freezeKeyMap == null) {
freezeKeyMap = new Hashtable();
thawKeyMap = new Hashtable();
}
freezeKeyMap.put(key, ioFmt);
thawKeyMap.put(ioFmt, key);
}
/** {@collect.stats}
* Returns the object previously registered with
* <code>registerStaticAttributeKey</code>.
*/
public static Object getStaticAttribute(Object key) {
if (thawKeyMap == null || key == null) {
return null;
}
return thawKeyMap.get(key);
}
/** {@collect.stats}
* Returns the String that <code>key</code> will be registered with
* @see #getStaticAttribute
* @see #registerStaticAttributeKey
*/
public static Object getStaticAttributeKey(Object key) {
return key.getClass().getName() + "." + key.toString();
}
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// clean out unused sets before saving
removeUnusedSets();
s.defaultWriteObject();
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
fontSearch = new FontKey(null, 0, 0);
fontTable = new Hashtable();
search = new SimpleAttributeSet();
attributesPool = Collections.
synchronizedMap(new WeakHashMap());
s.defaultReadObject();
}
// --- variables ---------------------------------------------------
/** {@collect.stats}
* The name given to the default logical style attached
* to paragraphs.
*/
public static final String DEFAULT_STYLE = "default";
private static Hashtable freezeKeyMap;
private static Hashtable thawKeyMap;
private Style styles;
private transient FontKey fontSearch = new FontKey(null, 0, 0);
private transient Hashtable fontTable = new Hashtable();
private transient Map attributesPool = Collections.
synchronizedMap(new WeakHashMap());
private transient MutableAttributeSet search = new SimpleAttributeSet();
/** {@collect.stats}
* Number of immutable sets that are not currently
* being used. This helps indicate when the sets need
* to be cleaned out of the hashtable they are stored
* in.
*/
private int unusedSets;
/** {@collect.stats}
* The threshold for no longer sharing the set of attributes
* in an immutable table.
*/
static final int THRESHOLD = 9;
/** {@collect.stats}
* This class holds a small number of attributes in an array.
* The storage format is key, value, key, value, etc. The size
* of the set is the length of the array divided by two. By
* default, this is the class that will be used to store attributes
* when held in the compact sharable form.
*/
public class SmallAttributeSet implements AttributeSet {
public SmallAttributeSet(Object[] attributes) {
this.attributes = attributes;
updateResolveParent();
}
public SmallAttributeSet(AttributeSet attrs) {
int n = attrs.getAttributeCount();
Object[] tbl = new Object[2 * n];
Enumeration names = attrs.getAttributeNames();
int i = 0;
while (names.hasMoreElements()) {
tbl[i] = names.nextElement();
tbl[i+1] = attrs.getAttribute(tbl[i]);
i += 2;
}
attributes = tbl;
updateResolveParent();
}
private void updateResolveParent() {
resolveParent = null;
Object[] tbl = attributes;
for (int i = 0; i < tbl.length; i += 2) {
if (tbl[i] == StyleConstants.ResolveAttribute) {
resolveParent = (AttributeSet)tbl[i + 1];
break;
}
}
}
Object getLocalAttribute(Object nm) {
if (nm == StyleConstants.ResolveAttribute) {
return resolveParent;
}
Object[] tbl = attributes;
for (int i = 0; i < tbl.length; i += 2) {
if (nm.equals(tbl[i])) {
return tbl[i+1];
}
}
return null;
}
// --- Object methods -------------------------
/** {@collect.stats}
* Returns a string showing the key/value pairs
*/
public String toString() {
String s = "{";
Object[] tbl = attributes;
for (int i = 0; i < tbl.length; i += 2) {
if (tbl[i+1] instanceof AttributeSet) {
// don't recurse
s = s + tbl[i] + "=" + "AttributeSet" + ",";
} else {
s = s + tbl[i] + "=" + tbl[i+1] + ",";
}
}
s = s + "}";
return s;
}
/** {@collect.stats}
* Returns a hashcode for this set of attributes.
* @return a hashcode value for this set of attributes.
*/
public int hashCode() {
int code = 0;
Object[] tbl = attributes;
for (int i = 1; i < tbl.length; i += 2) {
code ^= tbl[i].hashCode();
}
return code;
}
/** {@collect.stats}
* Compares this object to the specifed object.
* The result is <code>true</code> if the object is an equivalent
* set of attributes.
* @param obj the object to compare with.
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof AttributeSet) {
AttributeSet attrs = (AttributeSet) obj;
return ((getAttributeCount() == attrs.getAttributeCount()) &&
containsAttributes(attrs));
}
return false;
}
/** {@collect.stats}
* Clones a set of attributes. Since the set is immutable, a
* clone is basically the same set.
*
* @return the set of attributes
*/
public Object clone() {
return this;
}
// --- AttributeSet methods ----------------------------
/** {@collect.stats}
* Gets the number of attributes that are defined.
*
* @return the number of attributes
* @see AttributeSet#getAttributeCount
*/
public int getAttributeCount() {
return attributes.length / 2;
}
/** {@collect.stats}
* Checks whether a given attribute is defined.
*
* @param key the attribute key
* @return true if the attribute is defined
* @see AttributeSet#isDefined
*/
public boolean isDefined(Object key) {
Object[] a = attributes;
int n = a.length;
for (int i = 0; i < n; i += 2) {
if (key.equals(a[i])) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Checks whether two attribute sets are equal.
*
* @param attr the attribute set to check against
* @return true if the same
* @see AttributeSet#isEqual
*/
public boolean isEqual(AttributeSet attr) {
if (attr instanceof SmallAttributeSet) {
return attr == this;
}
return ((getAttributeCount() == attr.getAttributeCount()) &&
containsAttributes(attr));
}
/** {@collect.stats}
* Copies a set of attributes.
*
* @return the copy
* @see AttributeSet#copyAttributes
*/
public AttributeSet copyAttributes() {
return this;
}
/** {@collect.stats}
* Gets the value of an attribute.
*
* @param key the attribute name
* @return the attribute value
* @see AttributeSet#getAttribute
*/
public Object getAttribute(Object key) {
Object value = getLocalAttribute(key);
if (value == null) {
AttributeSet parent = getResolveParent();
if (parent != null)
value = parent.getAttribute(key);
}
return value;
}
/** {@collect.stats}
* Gets the names of all attributes.
*
* @return the attribute names
* @see AttributeSet#getAttributeNames
*/
public Enumeration<?> getAttributeNames() {
return new KeyEnumeration(attributes);
}
/** {@collect.stats}
* Checks whether a given attribute name/value is defined.
*
* @param name the attribute name
* @param value the attribute value
* @return true if the name/value is defined
* @see AttributeSet#containsAttribute
*/
public boolean containsAttribute(Object name, Object value) {
return value.equals(getAttribute(name));
}
/** {@collect.stats}
* Checks whether the attribute set contains all of
* the given attributes.
*
* @param attrs the attributes to check
* @return true if the element contains all the attributes
* @see AttributeSet#containsAttributes
*/
public boolean containsAttributes(AttributeSet attrs) {
boolean result = true;
Enumeration names = attrs.getAttributeNames();
while (result && names.hasMoreElements()) {
Object name = names.nextElement();
result = attrs.getAttribute(name).equals(getAttribute(name));
}
return result;
}
/** {@collect.stats}
* If not overriden, the resolving parent defaults to
* the parent element.
*
* @return the attributes from the parent
* @see AttributeSet#getResolveParent
*/
public AttributeSet getResolveParent() {
return resolveParent;
}
// --- variables -----------------------------------------
Object[] attributes;
// This is also stored in attributes
AttributeSet resolveParent;
}
/** {@collect.stats}
* An enumeration of the keys in a SmallAttributeSet.
*/
class KeyEnumeration implements Enumeration<Object> {
KeyEnumeration(Object[] attr) {
this.attr = attr;
i = 0;
}
/** {@collect.stats}
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if this enumeration contains more elements;
* <code>false</code> otherwise.
* @since JDK1.0
*/
public boolean hasMoreElements() {
return i < attr.length;
}
/** {@collect.stats}
* Returns the next element of this enumeration.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
* @since JDK1.0
*/
public Object nextElement() {
if (i < attr.length) {
Object o = attr[i];
i += 2;
return o;
}
throw new NoSuchElementException();
}
Object[] attr;
int i;
}
/** {@collect.stats}
* Sorts the key strings so that they can be very quickly compared
* in the attribute set searchs.
*/
class KeyBuilder {
public void initialize(AttributeSet a) {
if (a instanceof SmallAttributeSet) {
initialize(((SmallAttributeSet)a).attributes);
} else {
keys.removeAllElements();
data.removeAllElements();
Enumeration names = a.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
addAttribute(name, a.getAttribute(name));
}
}
}
/** {@collect.stats}
* Initialize with a set of already sorted
* keys (data from an existing SmallAttributeSet).
*/
private void initialize(Object[] sorted) {
keys.removeAllElements();
data.removeAllElements();
int n = sorted.length;
for (int i = 0; i < n; i += 2) {
keys.addElement(sorted[i]);
data.addElement(sorted[i+1]);
}
}
/** {@collect.stats}
* Creates a table of sorted key/value entries
* suitable for creation of an instance of
* SmallAttributeSet.
*/
public Object[] createTable() {
int n = keys.size();
Object[] tbl = new Object[2 * n];
for (int i = 0; i < n; i ++) {
int offs = 2 * i;
tbl[offs] = keys.elementAt(i);
tbl[offs + 1] = data.elementAt(i);
}
return tbl;
}
/** {@collect.stats}
* The number of key/value pairs contained
* in the current key being forged.
*/
int getCount() {
return keys.size();
}
/** {@collect.stats}
* Adds a key/value to the set.
*/
public void addAttribute(Object key, Object value) {
keys.addElement(key);
data.addElement(value);
}
/** {@collect.stats}
* Adds a set of key/value pairs to the set.
*/
public void addAttributes(AttributeSet attr) {
if (attr instanceof SmallAttributeSet) {
// avoid searching the keys, they are already interned.
Object[] tbl = ((SmallAttributeSet)attr).attributes;
int n = tbl.length;
for (int i = 0; i < n; i += 2) {
addAttribute(tbl[i], tbl[i+1]);
}
} else {
Enumeration names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
addAttribute(name, attr.getAttribute(name));
}
}
}
/** {@collect.stats}
* Removes the given name from the set.
*/
public void removeAttribute(Object key) {
int n = keys.size();
for (int i = 0; i < n; i++) {
if (keys.elementAt(i).equals(key)) {
keys.removeElementAt(i);
data.removeElementAt(i);
return;
}
}
}
/** {@collect.stats}
* Removes the set of keys from the set.
*/
public void removeAttributes(Enumeration names) {
while (names.hasMoreElements()) {
Object name = names.nextElement();
removeAttribute(name);
}
}
/** {@collect.stats}
* Removes the set of matching attributes from the set.
*/
public void removeAttributes(AttributeSet attr) {
Enumeration names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Object name = names.nextElement();
Object value = attr.getAttribute(name);
removeSearchAttribute(name, value);
}
}
private void removeSearchAttribute(Object ikey, Object value) {
int n = keys.size();
for (int i = 0; i < n; i++) {
if (keys.elementAt(i).equals(ikey)) {
if (data.elementAt(i).equals(value)) {
keys.removeElementAt(i);
data.removeElementAt(i);
}
return;
}
}
}
private Vector keys = new Vector();
private Vector data = new Vector();
}
/** {@collect.stats}
* key for a font table
*/
static class FontKey {
private String family;
private int style;
private int size;
/** {@collect.stats}
* Constructs a font key.
*/
public FontKey(String family, int style, int size) {
setValue(family, style, size);
}
public void setValue(String family, int style, int size) {
this.family = (family != null) ? family.intern() : null;
this.style = style;
this.size = size;
}
/** {@collect.stats}
* Returns a hashcode for this font.
* @return a hashcode value for this font.
*/
public int hashCode() {
int fhash = (family != null) ? family.hashCode() : 0;
return fhash ^ style ^ size;
}
/** {@collect.stats}
* Compares this object to the specifed object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>Font</code> object with the same
* name, style, and point size as this font.
* @param obj the object to compare this font with.
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof FontKey) {
FontKey font = (FontKey)obj;
return (size == font.size) && (style == font.style) && (family == font.family);
}
return false;
}
}
/** {@collect.stats}
* A collection of attributes, typically used to represent
* character and paragraph styles. This is an implementation
* of MutableAttributeSet that can be observed if desired.
* These styles will take advantage of immutability while
* the sets are small enough, and may be substantially more
* efficient than something like SimpleAttributeSet.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public class NamedStyle implements Style, Serializable {
/** {@collect.stats}
* Creates a new named style.
*
* @param name the style name, null for unnamed
* @param parent the parent style, null if none
* @since 1.4
*/
public NamedStyle(String name, Style parent) {
attributes = getEmptySet();
if (name != null) {
setName(name);
}
if (parent != null) {
setResolveParent(parent);
}
}
/** {@collect.stats}
* Creates a new named style.
*
* @param parent the parent style, null if none
* @since 1.4
*/
public NamedStyle(Style parent) {
this(null, parent);
}
/** {@collect.stats}
* Creates a new named style, with a null name and parent.
*/
public NamedStyle() {
attributes = getEmptySet();
}
/** {@collect.stats}
* Converts the style to a string.
*
* @return the string
*/
public String toString() {
return "NamedStyle:" + getName() + " " + attributes;
}
/** {@collect.stats}
* Fetches the name of the style. A style is not required to be named,
* so null is returned if there is no name associated with the style.
*
* @return the name
*/
public String getName() {
if (isDefined(StyleConstants.NameAttribute)) {
return getAttribute(StyleConstants.NameAttribute).toString();
}
return null;
}
/** {@collect.stats}
* Changes the name of the style. Does nothing with a null name.
*
* @param name the new name
*/
public void setName(String name) {
if (name != null) {
this.addAttribute(StyleConstants.NameAttribute, name);
}
}
/** {@collect.stats}
* Adds a change listener.
*
* @param l the change listener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a change listener.
*
* @param l the change listener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this NamedStyle with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @see EventListenerList
*/
protected void fireStateChanged() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Return an array of all the listeners of the given type that
* were added to this model.
*
* @return all of the objects receiving <em>listenerType</em> notifications
* from this model
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
// --- AttributeSet ----------------------------
// delegated to the immutable field "attributes"
/** {@collect.stats}
* Gets the number of attributes that are defined.
*
* @return the number of attributes >= 0
* @see AttributeSet#getAttributeCount
*/
public int getAttributeCount() {
return attributes.getAttributeCount();
}
/** {@collect.stats}
* Checks whether a given attribute is defined.
*
* @param attrName the non-null attribute name
* @return true if the attribute is defined
* @see AttributeSet#isDefined
*/
public boolean isDefined(Object attrName) {
return attributes.isDefined(attrName);
}
/** {@collect.stats}
* Checks whether two attribute sets are equal.
*
* @param attr the attribute set to check against
* @return true if the same
* @see AttributeSet#isEqual
*/
public boolean isEqual(AttributeSet attr) {
return attributes.isEqual(attr);
}
/** {@collect.stats}
* Copies a set of attributes.
*
* @return the copy
* @see AttributeSet#copyAttributes
*/
public AttributeSet copyAttributes() {
NamedStyle a = new NamedStyle();
a.attributes = attributes.copyAttributes();
return a;
}
/** {@collect.stats}
* Gets the value of an attribute.
*
* @param attrName the non-null attribute name
* @return the attribute value
* @see AttributeSet#getAttribute
*/
public Object getAttribute(Object attrName) {
return attributes.getAttribute(attrName);
}
/** {@collect.stats}
* Gets the names of all attributes.
*
* @return the attribute names as an enumeration
* @see AttributeSet#getAttributeNames
*/
public Enumeration<?> getAttributeNames() {
return attributes.getAttributeNames();
}
/** {@collect.stats}
* Checks whether a given attribute name/value is defined.
*
* @param name the non-null attribute name
* @param value the attribute value
* @return true if the name/value is defined
* @see AttributeSet#containsAttribute
*/
public boolean containsAttribute(Object name, Object value) {
return attributes.containsAttribute(name, value);
}
/** {@collect.stats}
* Checks whether the element contains all the attributes.
*
* @param attrs the attributes to check
* @return true if the element contains all the attributes
* @see AttributeSet#containsAttributes
*/
public boolean containsAttributes(AttributeSet attrs) {
return attributes.containsAttributes(attrs);
}
/** {@collect.stats}
* Gets attributes from the parent.
* If not overriden, the resolving parent defaults to
* the parent element.
*
* @return the attributes from the parent
* @see AttributeSet#getResolveParent
*/
public AttributeSet getResolveParent() {
return attributes.getResolveParent();
}
// --- MutableAttributeSet ----------------------------------
// should fetch a new immutable record for the field
// "attributes".
/** {@collect.stats}
* Adds an attribute.
*
* @param name the non-null attribute name
* @param value the attribute value
* @see MutableAttributeSet#addAttribute
*/
public void addAttribute(Object name, Object value) {
StyleContext context = StyleContext.this;
attributes = context.addAttribute(attributes, name, value);
fireStateChanged();
}
/** {@collect.stats}
* Adds a set of attributes to the element.
*
* @param attr the attributes to add
* @see MutableAttributeSet#addAttribute
*/
public void addAttributes(AttributeSet attr) {
StyleContext context = StyleContext.this;
attributes = context.addAttributes(attributes, attr);
fireStateChanged();
}
/** {@collect.stats}
* Removes an attribute from the set.
*
* @param name the non-null attribute name
* @see MutableAttributeSet#removeAttribute
*/
public void removeAttribute(Object name) {
StyleContext context = StyleContext.this;
attributes = context.removeAttribute(attributes, name);
fireStateChanged();
}
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param names the attribute names
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(Enumeration<?> names) {
StyleContext context = StyleContext.this;
attributes = context.removeAttributes(attributes, names);
fireStateChanged();
}
/** {@collect.stats}
* Removes a set of attributes for the element.
*
* @param attrs the attributes
* @see MutableAttributeSet#removeAttributes
*/
public void removeAttributes(AttributeSet attrs) {
StyleContext context = StyleContext.this;
if (attrs == this) {
attributes = context.getEmptySet();
} else {
attributes = context.removeAttributes(attributes, attrs);
}
fireStateChanged();
}
/** {@collect.stats}
* Sets the resolving parent.
*
* @param parent the parent, null if none
* @see MutableAttributeSet#setResolveParent
*/
public void setResolveParent(AttributeSet parent) {
if (parent != null) {
addAttribute(StyleConstants.ResolveAttribute, parent);
} else {
removeAttribute(StyleConstants.ResolveAttribute);
}
}
// --- serialization ---------------------------------------------
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
writeAttributeSet(s, attributes);
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
attributes = SimpleAttributeSet.EMPTY;
readAttributeSet(s, this);
}
// --- member variables -----------------------------------------------
/** {@collect.stats}
* The change listeners for the model.
*/
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Only one ChangeEvent is needed per model instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this".
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats}
* Inner AttributeSet implementation, which may be an
* immutable unique set being shared.
*/
private transient AttributeSet attributes;
}
static {
// initialize the static key registry with the StyleConstants keys
try {
int n = StyleConstants.keys.length;
for (int i = 0; i < n; i++) {
StyleContext.registerStaticAttributeKey(StyleConstants.keys[i]);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text;
import java.util.*;
import java.awt.*;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
/** {@collect.stats}
* A box that does layout asynchronously. This
* is useful to keep the GUI event thread moving by
* not doing any layout on it. The layout is done
* on a granularity of operations on the child views.
* After each child view is accessed for some part
* of layout (a potentially time consuming operation)
* the remaining tasks can be abandoned or a new higher
* priority task (i.e. to service a synchronous request
* or a visible area) can be taken on.
* <p>
* While the child view is being accessed
* a read lock is aquired on the associated document
* so that the model is stable while being accessed.
*
* @author Timothy Prinzing
* @since 1.3
*/
public class AsyncBoxView extends View {
/** {@collect.stats}
* Construct a box view that does asynchronous layout.
*
* @param elem the element of the model to represent
* @param axis the axis to tile along. This can be
* either X_AXIS or Y_AXIS.
*/
public AsyncBoxView(Element elem, int axis) {
super(elem);
stats = new ArrayList();
this.axis = axis;
locator = new ChildLocator();
flushTask = new FlushTask();
minorSpan = Short.MAX_VALUE;
estimatedMajorSpan = false;
}
/** {@collect.stats}
* Fetch the major axis (the axis the children
* are tiled along). This will have a value of
* either X_AXIS or Y_AXIS.
*/
public int getMajorAxis() {
return axis;
}
/** {@collect.stats}
* Fetch the minor axis (the axis orthoginal
* to the tiled axis). This will have a value of
* either X_AXIS or Y_AXIS.
*/
public int getMinorAxis() {
return (axis == X_AXIS) ? Y_AXIS : X_AXIS;
}
/** {@collect.stats}
* Get the top part of the margin around the view.
*/
public float getTopInset() {
return topInset;
}
/** {@collect.stats}
* Set the top part of the margin around the view.
*
* @param i the value of the inset
*/
public void setTopInset(float i) {
topInset = i;
}
/** {@collect.stats}
* Get the bottom part of the margin around the view.
*/
public float getBottomInset() {
return bottomInset;
}
/** {@collect.stats}
* Set the bottom part of the margin around the view.
*
* @param i the value of the inset
*/
public void setBottomInset(float i) {
bottomInset = i;
}
/** {@collect.stats}
* Get the left part of the margin around the view.
*/
public float getLeftInset() {
return leftInset;
}
/** {@collect.stats}
* Set the left part of the margin around the view.
*
* @param i the value of the inset
*/
public void setLeftInset(float i) {
leftInset = i;
}
/** {@collect.stats}
* Get the right part of the margin around the view.
*/
public float getRightInset() {
return rightInset;
}
/** {@collect.stats}
* Set the right part of the margin around the view.
*
* @param i the value of the inset
*/
public void setRightInset(float i) {
rightInset = i;
}
/** {@collect.stats}
* Fetch the span along an axis that is taken up by the insets.
*
* @param axis the axis to determine the total insets along,
* either X_AXIS or Y_AXIS.
* @since 1.4
*/
protected float getInsetSpan(int axis) {
float margin = (axis == X_AXIS) ?
getLeftInset() + getRightInset() : getTopInset() + getBottomInset();
return margin;
}
/** {@collect.stats}
* Set the estimatedMajorSpan property that determines if the
* major span should be treated as being estimated. If this
* property is true, the value of setSize along the major axis
* will change the requirements along the major axis and incremental
* changes will be ignored until all of the children have been updated
* (which will cause the property to automatically be set to false).
* If the property is false the value of the majorSpan will be
* considered to be accurate and incremental changes will be
* added into the total as they are calculated.
*
* @since 1.4
*/
protected void setEstimatedMajorSpan(boolean isEstimated) {
estimatedMajorSpan = isEstimated;
}
/** {@collect.stats}
* Is the major span currently estimated?
*
* @since 1.4
*/
protected boolean getEstimatedMajorSpan() {
return estimatedMajorSpan;
}
/** {@collect.stats}
* Fetch the object representing the layout state of
* of the child at the given index.
*
* @param index the child index. This should be a
* value >= 0 and < getViewCount().
*/
protected ChildState getChildState(int index) {
synchronized(stats) {
if ((index >= 0) && (index < stats.size())) {
return (ChildState) stats.get(index);
}
return null;
}
}
/** {@collect.stats}
* Fetch the queue to use for layout.
*/
protected LayoutQueue getLayoutQueue() {
return LayoutQueue.getDefaultQueue();
}
/** {@collect.stats}
* New ChildState records are created through
* this method to allow subclasses the extend
* the ChildState records to do/hold more
*/
protected ChildState createChildState(View v) {
return new ChildState(v);
}
/** {@collect.stats}
* Requirements changed along the major axis.
* This is called by the thread doing layout for
* the given ChildState object when it has completed
* fetching the child views new preferences.
* Typically this would be the layout thread, but
* might be the event thread if it is trying to update
* something immediately (such as to perform a
* model/view translation).
* <p>
* This is implemented to mark the major axis as having
* changed so that a future check to see if the requirements
* need to be published to the parent view will consider
* the major axis. If the span along the major axis is
* not estimated, it is updated by the given delta to reflect
* the incremental change. The delta is ignored if the
* major span is estimated.
*/
protected synchronized void majorRequirementChange(ChildState cs, float delta) {
if (estimatedMajorSpan == false) {
majorSpan += delta;
}
majorChanged = true;
}
/** {@collect.stats}
* Requirements changed along the minor axis.
* This is called by the thread doing layout for
* the given ChildState object when it has completed
* fetching the child views new preferences.
* Typically this would be the layout thread, but
* might be the GUI thread if it is trying to update
* something immediately (such as to perform a
* model/view translation).
*/
protected synchronized void minorRequirementChange(ChildState cs) {
minorChanged = true;
}
/** {@collect.stats}
* Publish the changes in preferences upward to the parent
* view. This is normally called by the layout thread.
*/
protected void flushRequirementChanges() {
AbstractDocument doc = (AbstractDocument) getDocument();
try {
doc.readLock();
View parent = null;
boolean horizontal = false;
boolean vertical = false;
synchronized(this) {
// perform tasks that iterate over the children while
// preventing the collection from changing.
synchronized(stats) {
int n = getViewCount();
if ((n > 0) && (minorChanged || estimatedMajorSpan)) {
LayoutQueue q = getLayoutQueue();
ChildState min = getChildState(0);
ChildState pref = getChildState(0);
float span = 0f;
for (int i = 1; i < n; i++) {
ChildState cs = getChildState(i);
if (minorChanged) {
if (cs.min > min.min) {
min = cs;
}
if (cs.pref > pref.pref) {
pref = cs;
}
}
if (estimatedMajorSpan) {
span += cs.getMajorSpan();
}
}
if (minorChanged) {
minRequest = min;
prefRequest = pref;
}
if (estimatedMajorSpan) {
majorSpan = span;
estimatedMajorSpan = false;
majorChanged = true;
}
}
}
// message preferenceChanged
if (majorChanged || minorChanged) {
parent = getParent();
if (parent != null) {
if (axis == X_AXIS) {
horizontal = majorChanged;
vertical = minorChanged;
} else {
vertical = majorChanged;
horizontal = minorChanged;
}
}
majorChanged = false;
minorChanged = false;
}
}
// propagate a preferenceChanged, using the
// layout thread.
if (parent != null) {
parent.preferenceChanged(this, horizontal, vertical);
// probably want to change this to be more exact.
Component c = getContainer();
if (c != null) {
c.repaint();
}
}
} finally {
doc.readUnlock();
}
}
/** {@collect.stats}
* Calls the superclass to update the child views, and
* updates the status records for the children. This
* is expected to be called while a write lock is held
* on the model so that interaction with the layout
* thread will not happen (i.e. the layout thread
* acquires a read lock before doing anything).
*
* @param offset the starting offset into the child views >= 0
* @param length the number of existing views to replace >= 0
* @param views the child views to insert
*/
public void replace(int offset, int length, View[] views) {
synchronized(stats) {
// remove the replaced state records
for (int i = 0; i < length; i++) {
ChildState cs = (ChildState)stats.remove(offset);
float csSpan = cs.getMajorSpan();
cs.getChildView().setParent(null);
if (csSpan != 0) {
majorRequirementChange(cs, -csSpan);
}
}
// insert the state records for the new children
LayoutQueue q = getLayoutQueue();
if (views != null) {
for (int i = 0; i < views.length; i++) {
ChildState s = createChildState(views[i]);
stats.add(offset + i, s);
q.addTask(s);
}
}
// notify that the size changed
q.addTask(flushTask);
}
}
/** {@collect.stats}
* Loads all of the children to initialize the view.
* This is called by the <a href="#setParent">setParent</a>
* method. Subclasses can reimplement this to initialize
* their child views in a different manner. The default
* implementation creates a child view for each
* child element.
* <p>
* Normally a write-lock is held on the Document while
* the children are being changed, which keeps the rendering
* and layout threads safe. The exception to this is when
* the view is initialized to represent an existing element
* (via this method), so it is synchronized to exclude
* preferenceChanged while we are initializing.
*
* @param f the view factory
* @see #setParent
*/
protected void loadChildren(ViewFactory f) {
Element e = getElement();
int n = e.getElementCount();
if (n > 0) {
View[] added = new View[n];
for (int i = 0; i < n; i++) {
added[i] = f.create(e.getElement(i));
}
replace(0, 0, added);
}
}
/** {@collect.stats}
* Fetches the child view index representing the given position in
* the model. This is implemented to fetch the view in the case
* where there is a child view for each child element.
*
* @param pos the position >= 0
* @return index of the view representing the given position, or
* -1 if no view represents that position
*/
protected synchronized int getViewIndexAtPosition(int pos, Position.Bias b) {
boolean isBackward = (b == Position.Bias.Backward);
pos = (isBackward) ? Math.max(0, pos - 1) : pos;
Element elem = getElement();
return elem.getElementIndex(pos);
}
/** {@collect.stats}
* Update the layout in response to receiving notification of
* change from the model. This is implemented to note the
* change on the ChildLocator so that offsets of the children
* will be correctly computed.
*
* @param ec changes to the element this view is responsible
* for (may be null if there were no changes).
* @param e the change information from the associated document
* @param a the current allocation of the view
* @see #insertUpdate
* @see #removeUpdate
* @see #changedUpdate
*/
protected void updateLayout(DocumentEvent.ElementChange ec,
DocumentEvent e, Shape a) {
if (ec != null) {
// the newly inserted children don't have a valid
// offset so the child locator needs to be messaged
// that the child prior to the new children has
// changed size.
int index = Math.max(ec.getIndex() - 1, 0);
ChildState cs = getChildState(index);
locator.childChanged(cs);
}
}
// --- View methods ------------------------------------
/** {@collect.stats}
* Sets the parent of the view.
* This is reimplemented to provide the superclass
* behavior as well as calling the <code>loadChildren</code>
* method if this view does not already have children.
* The children should not be loaded in the
* constructor because the act of setting the parent
* may cause them to try to search up the hierarchy
* (to get the hosting Container for example).
* If this view has children (the view is being moved
* from one place in the view hierarchy to another),
* the <code>loadChildren</code> method will not be called.
*
* @param parent the parent of the view, null if none
*/
public void setParent(View parent) {
super.setParent(parent);
if ((parent != null) && (getViewCount() == 0)) {
ViewFactory f = getViewFactory();
loadChildren(f);
}
}
/** {@collect.stats}
* Child views can call this on the parent to indicate that
* the preference has changed and should be reconsidered
* for layout. This is reimplemented to queue new work
* on the layout thread. This method gets messaged from
* multiple threads via the children.
*
* @param child the child view
* @param width true if the width preference has changed
* @param height true if the height preference has changed
* @see javax.swing.JComponent#revalidate
*/
public synchronized void preferenceChanged(View child, boolean width, boolean height) {
if (child == null) {
getParent().preferenceChanged(this, width, height);
} else {
if (changing != null) {
View cv = changing.getChildView();
if (cv == child) {
// size was being changed on the child, no need to
// queue work for it.
changing.preferenceChanged(width, height);
return;
}
}
int index = getViewIndex(child.getStartOffset(),
Position.Bias.Forward);
ChildState cs = getChildState(index);
cs.preferenceChanged(width, height);
LayoutQueue q = getLayoutQueue();
q.addTask(cs);
q.addTask(flushTask);
}
}
/** {@collect.stats}
* Sets the size of the view. This should cause
* layout of the view if the view caches any layout
* information.
* <p>
* Since the major axis is updated asynchronously and should be
* the sum of the tiled children the call is ignored for the major
* axis. Since the minor axis is flexible, work is queued to resize
* the children if the minor span changes.
*
* @param width the width >= 0
* @param height the height >= 0
*/
public void setSize(float width, float height) {
setSpanOnAxis(X_AXIS, width);
setSpanOnAxis(Y_AXIS, height);
}
/** {@collect.stats}
* Retrieves the size of the view along an axis.
*
* @param axis may be either <code>View.X_AXIS</code> or
* <code>View.Y_AXIS</code>
* @return the current span of the view along the given axis, >= 0
*/
float getSpanOnAxis(int axis) {
if (axis == getMajorAxis()) {
return majorSpan;
}
return minorSpan;
}
/** {@collect.stats}
* Sets the size of the view along an axis. Since the major
* axis is updated asynchronously and should be the sum of the
* tiled children the call is ignored for the major axis. Since
* the minor axis is flexible, work is queued to resize the
* children if the minor span changes.
*
* @param axis may be either <code>View.X_AXIS</code> or
* <code>View.Y_AXIS</code>
* @param span the span to layout to >= 0
*/
void setSpanOnAxis(int axis, float span) {
float margin = getInsetSpan(axis);
if (axis == getMinorAxis()) {
float targetSpan = span - margin;
if (targetSpan != minorSpan) {
minorSpan = targetSpan;
// mark all of the ChildState instances as needing to
// resize the child, and queue up work to fix them.
int n = getViewCount();
if (n != 0) {
LayoutQueue q = getLayoutQueue();
for (int i = 0; i < n; i++) {
ChildState cs = getChildState(i);
cs.childSizeValid = false;
q.addTask(cs);
}
q.addTask(flushTask);
}
}
} else {
// along the major axis the value is ignored
// unless the estimatedMajorSpan property is
// true.
if (estimatedMajorSpan) {
majorSpan = span - margin;
}
}
}
/** {@collect.stats}
* Render the view using the given allocation and
* rendering surface.
* <p>
* This is implemented to determine whether or not the
* desired region to be rendered (i.e. the unclipped
* area) is up to date or not. If up-to-date the children
* are rendered. If not up-to-date, a task to build
* the desired area is placed on the layout queue as
* a high priority task. This keeps by event thread
* moving by rendering if ready, and postponing until
* a later time if not ready (since paint requests
* can be rescheduled).
*
* @param g the rendering surface to use
* @param alloc the allocated region to render into
* @see View#paint
*/
public void paint(Graphics g, Shape alloc) {
synchronized (locator) {
locator.setAllocation(alloc);
locator.paintChildren(g);
}
}
/** {@collect.stats}
* Determines the preferred span for this view along an
* axis.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the span the view would like to be rendered into >= 0.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
* @exception IllegalArgumentException for an invalid axis type
*/
public float getPreferredSpan(int axis) {
float margin = getInsetSpan(axis);
if (axis == this.axis) {
return majorSpan + margin;
}
if (prefRequest != null) {
View child = prefRequest.getChildView();
return child.getPreferredSpan(axis) + margin;
}
// nothing is known about the children yet
return margin + 30;
}
/** {@collect.stats}
* Determines the minimum span for this view along an
* axis.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the span the view would like to be rendered into >= 0.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
* @exception IllegalArgumentException for an invalid axis type
*/
public float getMinimumSpan(int axis) {
if (axis == this.axis) {
return getPreferredSpan(axis);
}
if (minRequest != null) {
View child = minRequest.getChildView();
return child.getMinimumSpan(axis);
}
// nothing is known about the children yet
if (axis == X_AXIS) {
return getLeftInset() + getRightInset() + 5;
} else {
return getTopInset() + getBottomInset() + 5;
}
}
/** {@collect.stats}
* Determines the maximum span for this view along an
* axis.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the span the view would like to be rendered into >= 0.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
* @exception IllegalArgumentException for an invalid axis type
*/
public float getMaximumSpan(int axis) {
if (axis == this.axis) {
return getPreferredSpan(axis);
}
return Integer.MAX_VALUE;
}
/** {@collect.stats}
* Returns the number of views in this view. Since
* the default is to not be a composite view this
* returns 0.
*
* @return the number of views >= 0
* @see View#getViewCount
*/
public int getViewCount() {
synchronized(stats) {
return stats.size();
}
}
/** {@collect.stats}
* Gets the nth child view. Since there are no
* children by default, this returns null.
*
* @param n the number of the view to get, >= 0 && < getViewCount()
* @return the view
*/
public View getView(int n) {
ChildState cs = getChildState(n);
if (cs != null) {
return cs.getChildView();
}
return null;
}
/** {@collect.stats}
* Fetches the allocation for the given child view.
* This enables finding out where various views
* are located, without assuming the views store
* their location. This returns null since the
* default is to not have any child views.
*
* @param index the index of the child, >= 0 && < getViewCount()
* @param a the allocation to this view.
* @return the allocation to the child
*/
public Shape getChildAllocation(int index, Shape a) {
Shape ca = locator.getChildAllocation(index, a);
return ca;
}
/** {@collect.stats}
* 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.
*
* @param pos the position >= 0
* @return index of the view representing the given position, or
* -1 if no view represents that position
* @since 1.3
*/
public int getViewIndex(int pos, Position.Bias b) {
return getViewIndexAtPosition(pos, b);
}
/** {@collect.stats}
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert >= 0
* @param a the allocated region to render into
* @param b the bias toward the previous character or the
* next character represented by the offset, in case the
* position is a boundary of two views.
* @return the bounding box of the given position is returned
* @exception BadLocationException if the given position does
* not represent a valid location in the associated document
* @exception IllegalArgumentException for an invalid bias argument
* @see View#viewToModel
*/
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
int index = getViewIndex(pos, b);
Shape ca = locator.getChildAllocation(index, a);
// forward to the child view, and make sure we don't
// interact with the layout thread by synchronizing
// on the child state.
ChildState cs = getChildState(index);
synchronized (cs) {
View cv = cs.getChildView();
Shape v = cv.modelToView(pos, ca, b);
return v;
}
}
/** {@collect.stats}
* 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.
* <p>
* This is expected to be called by the GUI thread, holding a
* read-lock on the associated model. It is implemented to
* locate the child view and determine it's allocation with a
* lock on the ChildLocator object, and to call viewToModel
* on the child view with a lock on the ChildState object
* to avoid interaction with the layout thread.
*
* @param x the X coordinate >= 0
* @param y the Y coordinate >= 0
* @param a the allocated region to render into
* @return the location within the model that best represents the
* given point in the view >= 0. 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, Shape a, Position.Bias[] biasReturn) {
int pos; // return position
int index; // child index to forward to
Shape ca; // child allocation
// locate the child view and it's allocation so that
// we can forward to it. Make sure the layout thread
// doesn't change anything by trying to flush changes
// to the parent while the GUI thread is trying to
// find the child and it's allocation.
synchronized (locator) {
index = locator.getViewIndexAtPoint(x, y, a);
ca = locator.getChildAllocation(index, a);
}
// forward to the child view, and make sure we don't
// interact with the layout thread by synchronizing
// on the child state.
ChildState cs = getChildState(index);
synchronized (cs) {
View v = cs.getChildView();
pos = v.viewToModel(x, y, ca, biasReturn);
}
return pos;
}
/** {@collect.stats}
* Provides a way to determine the next visually represented model
* location that 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.
*
* @param pos the position to convert >= 0
* @param a the allocated region to render into
* @param direction the direction from the current position that can
* be thought of as the arrow keys typically found on a keyboard;
* this may be one of the following:
* <ul>
* <code>SwingConstants.WEST</code>
* <code>SwingConstants.EAST</code>
* <code>SwingConstants.NORTH</code>
* <code>SwingConstants.SOUTH</code>
* </ul>
* @param biasRet an array contain the bias that was checked
* @return the location within the model that best represents the next
* location visual position
* @exception BadLocationException
* @exception IllegalArgumentException if <code>direction</code> is invalid
*/
public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a,
int direction,
Position.Bias[] biasRet)
throws BadLocationException {
return Utilities.getNextVisualPositionFrom(
this, pos, b, a, direction, biasRet);
}
// --- variables -----------------------------------------
/** {@collect.stats}
* The major axis against which the children are
* tiled.
*/
int axis;
/** {@collect.stats}
* The children and their layout statistics.
*/
java.util.List stats;
/** {@collect.stats}
* Current span along the major axis. This
* is also the value returned by getMinimumSize,
* getPreferredSize, and getMaximumSize along
* the major axis.
*/
float majorSpan;
/** {@collect.stats}
* Is the span along the major axis estimated?
*/
boolean estimatedMajorSpan;
/** {@collect.stats}
* Current span along the minor axis. This
* is what layout was done against (i.e. things
* are flexible in this direction).
*/
float minorSpan;
/** {@collect.stats}
* Object that manages the offsets of the
* children. All locking for management of
* child locations is on this object.
*/
protected ChildLocator locator;
float topInset;
float bottomInset;
float leftInset;
float rightInset;
ChildState minRequest;
ChildState prefRequest;
boolean majorChanged;
boolean minorChanged;
Runnable flushTask;
/** {@collect.stats}
* Child that is actively changing size. This often
* causes a preferenceChanged, so this is a cache to
* possibly speed up the marking the state. It also
* helps flag an opportunity to avoid adding to flush
* task to the layout queue.
*/
ChildState changing;
/** {@collect.stats}
* A class to manage the effective position of the
* child views in a localized area while changes are
* being made around the localized area. The AsyncBoxView
* may be continuously changing, but the visible area
* needs to remain fairly stable until the layout thread
* decides to publish an update to the parent.
* @since 1.3
*/
public class ChildLocator {
/** {@collect.stats}
* construct a child locator.
*/
public ChildLocator() {
lastAlloc = new Rectangle();
childAlloc = new Rectangle();
}
/** {@collect.stats}
* Notification that a child changed. This can effect
* whether or not new offset calculations are needed.
* This is called by a ChildState object that has
* changed it's major span. This can therefore be
* called by multiple threads.
*/
public synchronized void childChanged(ChildState cs) {
if (lastValidOffset == null) {
lastValidOffset = cs;
} else if (cs.getChildView().getStartOffset() <
lastValidOffset.getChildView().getStartOffset()) {
lastValidOffset = cs;
}
}
/** {@collect.stats}
* Paint the children that intersect the clip area.
*/
public synchronized void paintChildren(Graphics g) {
Rectangle clip = g.getClipBounds();
float targetOffset = (axis == X_AXIS) ?
clip.x - lastAlloc.x : clip.y - lastAlloc.y;
int index = getViewIndexAtVisualOffset(targetOffset);
int n = getViewCount();
float offs = getChildState(index).getMajorOffset();
for (int i = index; i < n; i++) {
ChildState cs = getChildState(i);
cs.setMajorOffset(offs);
Shape ca = getChildAllocation(i);
if (intersectsClip(ca, clip)) {
synchronized (cs) {
View v = cs.getChildView();
v.paint(g, ca);
}
} else {
// done painting intersection
break;
}
offs += cs.getMajorSpan();
}
}
/** {@collect.stats}
* Fetch the allocation to use for a child view.
* This will update the offsets for all children
* not yet updated before the given index.
*/
public synchronized Shape getChildAllocation(int index, Shape a) {
if (a == null) {
return null;
}
setAllocation(a);
ChildState cs = getChildState(index);
if (lastValidOffset == null) {
lastValidOffset = getChildState(0);
}
if (cs.getChildView().getStartOffset() >
lastValidOffset.getChildView().getStartOffset()) {
// offsets need to be updated
updateChildOffsetsToIndex(index);
}
Shape ca = getChildAllocation(index);
return ca;
}
/** {@collect.stats}
* Fetches the child view index at the given point.
* This is called by the various View methods that
* need to calculate which child to forward a message
* to. This should be called by a block synchronized
* on this object, and would typically be followed
* with one or more calls to getChildAllocation that
* should also be in the synchronized block.
*
* @param x the X coordinate >= 0
* @param y the Y coordinate >= 0
* @param a the allocation to the View
* @return the nearest child index
*/
public int getViewIndexAtPoint(float x, float y, Shape a) {
setAllocation(a);
float targetOffset = (axis == X_AXIS) ? x - lastAlloc.x : y - lastAlloc.y;
int index = getViewIndexAtVisualOffset(targetOffset);
return index;
}
/** {@collect.stats}
* Fetch the allocation to use for a child view.
* <em>This does not update the offsets in the ChildState
* records.</em>
*/
protected Shape getChildAllocation(int index) {
ChildState cs = getChildState(index);
if (! cs.isLayoutValid()) {
cs.run();
}
if (axis == X_AXIS) {
childAlloc.x = lastAlloc.x + (int) cs.getMajorOffset();
childAlloc.y = lastAlloc.y + (int) cs.getMinorOffset();
childAlloc.width = (int) cs.getMajorSpan();
childAlloc.height = (int) cs.getMinorSpan();
} else {
childAlloc.y = lastAlloc.y + (int) cs.getMajorOffset();
childAlloc.x = lastAlloc.x + (int) cs.getMinorOffset();
childAlloc.height = (int) cs.getMajorSpan();
childAlloc.width = (int) cs.getMinorSpan();
}
childAlloc.x += (int)getLeftInset();
childAlloc.y += (int)getRightInset();
return childAlloc;
}
/** {@collect.stats}
* Copy the currently allocated shape into the Rectangle
* used to store the current allocation. This would be
* a floating point rectangle in a Java2D-specific implmentation.
*/
protected void setAllocation(Shape a) {
if (a instanceof Rectangle) {
lastAlloc.setBounds((Rectangle) a);
} else {
lastAlloc.setBounds(a.getBounds());
}
setSize(lastAlloc.width, lastAlloc.height);
}
/** {@collect.stats}
* Locate the view responsible for an offset into the box
* along the major axis. Make sure that offsets are set
* on the ChildState objects up to the given target span
* past the desired offset.
*
* @return index of the view representing the given visual
* location (targetOffset), or -1 if no view represents
* that location
*/
protected int getViewIndexAtVisualOffset(float targetOffset) {
int n = getViewCount();
if (n > 0) {
boolean lastValid = (lastValidOffset != null);
if (lastValidOffset == null) {
lastValidOffset = getChildState(0);
}
if (targetOffset > majorSpan) {
// should only get here on the first time display.
if (!lastValid) {
return 0;
}
int pos = lastValidOffset.getChildView().getStartOffset();
int index = getViewIndex(pos, Position.Bias.Forward);
return index;
} else if (targetOffset > lastValidOffset.getMajorOffset()) {
// roll offset calculations forward
return updateChildOffsets(targetOffset);
} else {
// no changes prior to the needed offset
// this should be a binary search
float offs = 0f;
for (int i = 0; i < n; i++) {
ChildState cs = getChildState(i);
float nextOffs = offs + cs.getMajorSpan();
if (targetOffset < nextOffs) {
return i;
}
offs = nextOffs;
}
}
}
return n - 1;
}
/** {@collect.stats}
* Move the location of the last offset calculation forward
* to the desired offset.
*/
int updateChildOffsets(float targetOffset) {
int n = getViewCount();
int targetIndex = n - 1;;
int pos = lastValidOffset.getChildView().getStartOffset();
int startIndex = getViewIndex(pos, Position.Bias.Forward);
float start = lastValidOffset.getMajorOffset();
float lastOffset = start;
for (int i = startIndex; i < n; i++) {
ChildState cs = getChildState(i);
cs.setMajorOffset(lastOffset);
lastOffset += cs.getMajorSpan();
if (targetOffset < lastOffset) {
targetIndex = i;
lastValidOffset = cs;
break;
}
}
return targetIndex;
}
/** {@collect.stats}
* Move the location of the last offset calculation forward
* to the desired index.
*/
void updateChildOffsetsToIndex(int index) {
int pos = lastValidOffset.getChildView().getStartOffset();
int startIndex = getViewIndex(pos, Position.Bias.Forward);
float lastOffset = lastValidOffset.getMajorOffset();
for (int i = startIndex; i <= index; i++) {
ChildState cs = getChildState(i);
cs.setMajorOffset(lastOffset);
lastOffset += cs.getMajorSpan();
}
}
boolean intersectsClip(Shape childAlloc, Rectangle clip) {
Rectangle cs = (childAlloc instanceof Rectangle) ?
(Rectangle) childAlloc : childAlloc.getBounds();
if (cs.intersects(clip)) {
// Make sure that lastAlloc also contains childAlloc,
// this will be false if haven't yet flushed changes.
return lastAlloc.intersects(cs);
}
return false;
}
/** {@collect.stats}
* The location of the last offset calculation
* that is valid.
*/
protected ChildState lastValidOffset;
/** {@collect.stats}
* The last seen allocation (for repainting when changes
* are flushed upward).
*/
protected Rectangle lastAlloc;
/** {@collect.stats}
* A shape to use for the child allocation to avoid
* creating a lot of garbage.
*/
protected Rectangle childAlloc;
}
/** {@collect.stats}
* A record representing the layout state of a
* child view. It is runnable as a task on another
* thread. All access to the child view that is
* based upon a read-lock on the model should synchronize
* on this object (i.e. The layout thread and the GUI
* thread can both have a read lock on the model at the
* same time and are not protected from each other).
* Access to a child view hierarchy is serialized via
* synchronization on the ChildState instance.
* @since 1.3
*/
public class ChildState implements Runnable {
/** {@collect.stats}
* Construct a child status. This needs to start
* out as fairly large so we don't falsely begin with
* the idea that all of the children are visible.
* @since 1.4
*/
public ChildState(View v) {
child = v;
minorValid = false;
majorValid = false;
childSizeValid = false;
child.setParent(AsyncBoxView.this);
}
/** {@collect.stats}
* Fetch the child view this record represents
*/
public View getChildView() {
return child;
}
/** {@collect.stats}
* Update the child state. This should be
* called by the thread that desires to spend
* time updating the child state (intended to
* be the layout thread).
* <p>
* This aquires a read lock on the associated
* document for the duration of the update to
* ensure the model is not changed while it is
* operating. The first thing to do would be
* to see if any work actually needs to be done.
* The following could have conceivably happened
* while the state was waiting to be updated:
* <ol>
* <li>The child may have been removed from the
* view hierarchy.
* <li>The child may have been updated by a
* higher priority operation (i.e. the child
* may have become visible).
* </ol>
*/
public void run () {
AbstractDocument doc = (AbstractDocument) getDocument();
try {
doc.readLock();
if (minorValid && majorValid && childSizeValid) {
// nothing to do
return;
}
if (child.getParent() == AsyncBoxView.this) {
// this may overwrite anothers threads cached
// value for actively changing... but that just
// means it won't use the cache if there is an
// overwrite.
synchronized(AsyncBoxView.this) {
changing = this;
}
updateChild();
synchronized(AsyncBoxView.this) {
changing = null;
}
// setting the child size on the minor axis
// may have caused it to change it's preference
// along the major axis.
updateChild();
}
} finally {
doc.readUnlock();
}
}
void updateChild() {
boolean minorUpdated = false;
synchronized(this) {
if (! minorValid) {
int minorAxis = getMinorAxis();
min = child.getMinimumSpan(minorAxis);
pref = child.getPreferredSpan(minorAxis);
max = child.getMaximumSpan(minorAxis);
minorValid = true;
minorUpdated = true;
}
}
if (minorUpdated) {
minorRequirementChange(this);
}
boolean majorUpdated = false;
float delta = 0.0f;
synchronized(this) {
if (! majorValid) {
float old = span;
span = child.getPreferredSpan(axis);
delta = span - old;
majorValid = true;
majorUpdated = true;
}
}
if (majorUpdated) {
majorRequirementChange(this, delta);
locator.childChanged(this);
}
synchronized(this) {
if (! childSizeValid) {
float w;
float h;
if (axis == X_AXIS) {
w = span;
h = getMinorSpan();
} else {
w = getMinorSpan();
h = span;
}
childSizeValid = true;
child.setSize(w, h);
}
}
}
/** {@collect.stats}
* What is the span along the minor axis.
*/
public float getMinorSpan() {
if (max < minorSpan) {
return max;
}
// make it the target width, or as small as it can get.
return Math.max(min, minorSpan);
}
/** {@collect.stats}
* What is the offset along the minor axis
*/
public float getMinorOffset() {
if (max < minorSpan) {
// can't make the child this wide, align it
float align = child.getAlignment(getMinorAxis());
return ((minorSpan - max) * align);
}
return 0f;
}
/** {@collect.stats}
* What is the span along the major axis.
*/
public float getMajorSpan() {
return span;
}
/** {@collect.stats}
* Get the offset along the major axis
*/
public float getMajorOffset() {
return offset;
}
/** {@collect.stats}
* This method should only be called by the ChildLocator,
* it is simply a convenient place to hold the cached
* location.
*/
public void setMajorOffset(float offs) {
offset = offs;
}
/** {@collect.stats}
* Mark preferences changed for this child.
*
* @param width true if the width preference has changed
* @param height true if the height preference has changed
* @see javax.swing.JComponent#revalidate
*/
public void preferenceChanged(boolean width, boolean height) {
if (axis == X_AXIS) {
if (width) {
majorValid = false;
}
if (height) {
minorValid = false;
}
} else {
if (width) {
minorValid = false;
}
if (height) {
majorValid = false;
}
}
childSizeValid = false;
}
/** {@collect.stats}
* Has the child view been laid out.
*/
public boolean isLayoutValid() {
return (minorValid && majorValid && childSizeValid);
}
// minor axis
private float min;
private float pref;
private float max;
private float align;
private boolean minorValid;
// major axis
private float span;
private float offset;
private boolean majorValid;
private View child;
private boolean childSizeValid;
}
/** {@collect.stats}
* Task to flush requirement changes upward
*/
class FlushTask implements Runnable {
public void run() {
flushRequirementChanges();
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text;
import java.awt.Container;
/** {@collect.stats}
* A factory to create a view of some portion of document subject.
* This is intended to enable customization of how views get
* mapped over a document model.
*
* @author Timothy Prinzing
*/
public interface ViewFactory {
/** {@collect.stats}
* Creates a view from the given structural element of a
* document.
*
* @param elem the piece of the document to build a view of
* @return the view
* @see View
*/
public View create(Element elem);
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.EventListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.event.*;
import javax.accessibility.*;
/** {@collect.stats}
* An implementation of an item in a menu. A menu item is essentially a button
* sitting in a list. When the user selects the "button", the action
* associated with the menu item is performed. A <code>JMenuItem</code>
* contained in a <code>JPopupMenu</code> performs exactly that function.
* <p>
* Menu items can be configured, and to some degree controlled, by
* <code><a href="Action.html">Action</a></code>s. Using an
* <code>Action</code> with a menu item has many benefits beyond directly
* configuring a menu item. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details, and you can find more information in <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html">How
* to Use Actions</a>, a section in <em>The Java Tutorial</em>.
* <p>
* For further documentation and for examples, see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html">How to Use Menus</a>
* in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: An item which can be selected in a menu.
*
* @author Georges Saab
* @author David Karlton
* @see JPopupMenu
* @see JMenu
* @see JCheckBoxMenuItem
* @see JRadioButtonMenuItem
*/
public class JMenuItem extends AbstractButton implements Accessible,MenuElement {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "MenuItemUI";
/* diagnostic aids -- should be false for production builds. */
private static final boolean TRACE = false; // trace creates and disposes
private static final boolean VERBOSE = false; // show reuse hits/misses
private static final boolean DEBUG = false; // show bad params, misc.
private boolean isMouseDragged = false;
/** {@collect.stats}
* Creates a <code>JMenuItem</code> with no set text or icon.
*/
public JMenuItem() {
this(null, (Icon)null);
}
/** {@collect.stats}
* Creates a <code>JMenuItem</code> with the specified icon.
*
* @param icon the icon of the <code>JMenuItem</code>
*/
public JMenuItem(Icon icon) {
this(null, icon);
}
/** {@collect.stats}
* Creates a <code>JMenuItem</code> with the specified text.
*
* @param text the text of the <code>JMenuItem</code>
*/
public JMenuItem(String text) {
this(text, (Icon)null);
}
/** {@collect.stats}
* Creates a menu item whose properties are taken from the
* specified <code>Action</code>.
*
* @param a the action of the <code>JMenuItem</code>
* @since 1.3
*/
public JMenuItem(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a <code>JMenuItem</code> with the specified text and icon.
*
* @param text the text of the <code>JMenuItem</code>
* @param icon the icon of the <code>JMenuItem</code>
*/
public JMenuItem(String text, Icon icon) {
setModel(new DefaultButtonModel());
init(text, icon);
initFocusability();
}
/** {@collect.stats}
* Creates a <code>JMenuItem</code> with the specified text and
* keyboard mnemonic.
*
* @param text the text of the <code>JMenuItem</code>
* @param mnemonic the keyboard mnemonic for the <code>JMenuItem</code>
*/
public JMenuItem(String text, int mnemonic) {
setModel(new DefaultButtonModel());
init(text, null);
setMnemonic(mnemonic);
initFocusability();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setModel(ButtonModel newModel) {
super.setModel(newModel);
if(newModel instanceof DefaultButtonModel) {
((DefaultButtonModel)newModel).setMenuItem(true);
}
}
/** {@collect.stats}
* Inititalizes the focusability of the the <code>JMenuItem</code>.
* <code>JMenuItem</code>'s are focusable, but subclasses may
* want to be, this provides them the opportunity to override this
* and invoke something else, or nothing at all. Refer to
* {@link javax.swing.JMenu#initFocusability} for the motivation of
* this.
*/
void initFocusability() {
setFocusable(false);
}
/** {@collect.stats}
* Initializes the menu item with the specified text and icon.
*
* @param text the text of the <code>JMenuItem</code>
* @param icon the icon of the <code>JMenuItem</code>
*/
protected void init(String text, Icon icon) {
if(text != null) {
setText(text);
}
if(icon != null) {
setIcon(icon);
}
// Listen for Focus events
addFocusListener(new MenuItemFocusListener());
setUIProperty("borderPainted", Boolean.FALSE);
setFocusPainted(false);
setHorizontalTextPosition(JButton.TRAILING);
setHorizontalAlignment(JButton.LEADING);
updateUI();
}
private static class MenuItemFocusListener implements FocusListener,
Serializable {
public void focusGained(FocusEvent event) {}
public void focusLost(FocusEvent event) {
// When focus is lost, repaint if
// the focus information is painted
JMenuItem mi = (JMenuItem)event.getSource();
if(mi.isFocusPainted()) {
mi.repaint();
}
}
}
/** {@collect.stats}
* Sets the look and feel object that renders this component.
*
* @param ui the <code>JMenuItemUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(MenuItemUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property with a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((MenuItemUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the suffix used to construct the name of the L&F class used to
* render this component.
*
* @return the string "MenuItemUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Identifies the menu item as "armed". If the mouse button is
* released while it is over this item, the menu's action event
* will fire. If the mouse button is released elsewhere, the
* event will not fire and the menu item will be disarmed.
*
* @param b true to arm the menu item so it can be selected
* @beaninfo
* description: Mouse release will fire an action event
* hidden: true
*/
public void setArmed(boolean b) {
ButtonModel model = (ButtonModel) getModel();
boolean oldValue = model.isArmed();
if(model.isArmed() != b) {
model.setArmed(b);
}
}
/** {@collect.stats}
* Returns whether the menu item is "armed".
*
* @return true if the menu item is armed, and it can be selected
* @see #setArmed
*/
public boolean isArmed() {
ButtonModel model = (ButtonModel) getModel();
return model.isArmed();
}
/** {@collect.stats}
* Enables or disables the menu item.
*
* @param b true to enable the item
* @beaninfo
* description: Does the component react to user interaction
* bound: true
* preferred: true
*/
public void setEnabled(boolean b) {
// Make sure we aren't armed!
if (!b && !UIManager.getBoolean("MenuItem.disabledAreNavigable")) {
setArmed(false);
}
super.setEnabled(b);
}
/** {@collect.stats}
* Returns true since <code>Menu</code>s, by definition,
* should always be on top of all other windows. If the menu is
* in an internal frame false is returned due to the rollover effect
* for windows laf where the menu is not always on top.
*/
// package private
boolean alwaysOnTop() {
// Fix for bug #4482165
if (SwingUtilities.getAncestorOfClass(JInternalFrame.class, this) !=
null) {
return false;
}
return true;
}
/* The keystroke which acts as the menu item's accelerator
*/
private KeyStroke accelerator;
/** {@collect.stats}
* Sets the key combination which invokes the menu item's
* action listeners without navigating the menu hierarchy. It is the
* UI's responsibility to install the correct action. Note that
* when the keyboard accelerator is typed, it will work whether or
* not the menu is currently displayed.
*
* @param keyStroke the <code>KeyStroke</code> which will
* serve as an accelerator
* @beaninfo
* description: The keystroke combination which will invoke the
* JMenuItem's actionlisteners without navigating the
* menu hierarchy
* bound: true
* preferred: true
*/
public void setAccelerator(KeyStroke keyStroke) {
KeyStroke oldAccelerator = accelerator;
this.accelerator = keyStroke;
repaint();
revalidate();
firePropertyChange("accelerator", oldAccelerator, accelerator);
}
/** {@collect.stats}
* Returns the <code>KeyStroke</code> which serves as an accelerator
* for the menu item.
* @return a <code>KeyStroke</code> object identifying the
* accelerator key
*/
public KeyStroke getAccelerator() {
return this.accelerator;
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.3
*/
protected void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
configureAcceleratorFromAction(a);
}
void setIconFromAction(Action a) {
Icon icon = null;
if (a != null) {
icon = (Icon)a.getValue(Action.SMALL_ICON);
}
setIcon(icon);
}
void largeIconChanged(Action a) {
}
void smallIconChanged(Action a) {
setIconFromAction(a);
}
void configureAcceleratorFromAction(Action a) {
KeyStroke ks = (a==null) ? null :
(KeyStroke)a.getValue(Action.ACCELERATOR_KEY);
setAccelerator(ks);
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
protected void actionPropertyChanged(Action action, String propertyName) {
if (propertyName == Action.ACCELERATOR_KEY) {
configureAcceleratorFromAction(action);
}
else {
super.actionPropertyChanged(action, propertyName);
}
}
/** {@collect.stats}
* Processes a mouse event forwarded from the
* <code>MenuSelectionManager</code> and changes the menu
* selection, if necessary, by using the
* <code>MenuSelectionManager</code>'s API.
* <p>
* Note: you do not have to forward the event to sub-components.
* This is done automatically by the <code>MenuSelectionManager</code>.
*
* @param e a <code>MouseEvent</code>
* @param path the <code>MenuElement</code> path array
* @param manager the <code>MenuSelectionManager</code>
*/
public void processMouseEvent(MouseEvent e,MenuElement path[],MenuSelectionManager manager) {
processMenuDragMouseEvent(
new MenuDragMouseEvent(e.getComponent(), e.getID(),
e.getWhen(),
e.getModifiers(), e.getX(), e.getY(),
e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(),
path, manager));
}
/** {@collect.stats}
* Processes a key event forwarded from the
* <code>MenuSelectionManager</code> and changes the menu selection,
* if necessary, by using <code>MenuSelectionManager</code>'s API.
* <p>
* Note: you do not have to forward the event to sub-components.
* This is done automatically by the <code>MenuSelectionManager</code>.
*
* @param e a <code>KeyEvent</code>
* @param path the <code>MenuElement</code> path array
* @param manager the <code>MenuSelectionManager</code>
*/
public void processKeyEvent(KeyEvent e,MenuElement path[],MenuSelectionManager manager) {
if (DEBUG) {
System.out.println("in JMenuItem.processKeyEvent/3 for " + getText() +
" " + KeyStroke.getKeyStrokeForEvent(e));
}
MenuKeyEvent mke = new MenuKeyEvent(e.getComponent(), e.getID(),
e.getWhen(), e.getModifiers(),
e.getKeyCode(), e.getKeyChar(),
path, manager);
processMenuKeyEvent(mke);
if (mke.isConsumed()) {
e.consume();
}
}
/** {@collect.stats}
* Handles mouse drag in a menu.
*
* @param e a <code>MenuDragMouseEvent</code> object
*/
public void processMenuDragMouseEvent(MenuDragMouseEvent e) {
switch (e.getID()) {
case MouseEvent.MOUSE_ENTERED:
isMouseDragged = false; fireMenuDragMouseEntered(e); break;
case MouseEvent.MOUSE_EXITED:
isMouseDragged = false; fireMenuDragMouseExited(e); break;
case MouseEvent.MOUSE_DRAGGED:
isMouseDragged = true; fireMenuDragMouseDragged(e); break;
case MouseEvent.MOUSE_RELEASED:
if(isMouseDragged) fireMenuDragMouseReleased(e); break;
default:
break;
}
}
/** {@collect.stats}
* Handles a keystroke in a menu.
*
* @param e a <code>MenuKeyEvent</code> object
*/
public void processMenuKeyEvent(MenuKeyEvent e) {
if (DEBUG) {
System.out.println("in JMenuItem.processMenuKeyEvent for " + getText()+
" " + KeyStroke.getKeyStrokeForEvent(e));
}
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
fireMenuKeyPressed(e); break;
case KeyEvent.KEY_RELEASED:
fireMenuKeyReleased(e); break;
case KeyEvent.KEY_TYPED:
fireMenuKeyTyped(e); break;
default:
break;
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuMouseDragEvent</code>
* @see EventListenerList
*/
protected void fireMenuDragMouseEntered(MenuDragMouseEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuDragMouseListener.class) {
// Lazily create the event:
((MenuDragMouseListener)listeners[i+1]).menuDragMouseEntered(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuDragMouseEvent</code>
* @see EventListenerList
*/
protected void fireMenuDragMouseExited(MenuDragMouseEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuDragMouseListener.class) {
// Lazily create the event:
((MenuDragMouseListener)listeners[i+1]).menuDragMouseExited(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuDragMouseEvent</code>
* @see EventListenerList
*/
protected void fireMenuDragMouseDragged(MenuDragMouseEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuDragMouseListener.class) {
// Lazily create the event:
((MenuDragMouseListener)listeners[i+1]).menuDragMouseDragged(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuDragMouseEvent</code>
* @see EventListenerList
*/
protected void fireMenuDragMouseReleased(MenuDragMouseEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuDragMouseListener.class) {
// Lazily create the event:
((MenuDragMouseListener)listeners[i+1]).menuDragMouseReleased(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
protected void fireMenuKeyPressed(MenuKeyEvent event) {
if (DEBUG) {
System.out.println("in JMenuItem.fireMenuKeyPressed for " + getText()+
" " + KeyStroke.getKeyStrokeForEvent(event));
}
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
// Lazily create the event:
((MenuKeyListener)listeners[i+1]).menuKeyPressed(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
protected void fireMenuKeyReleased(MenuKeyEvent event) {
if (DEBUG) {
System.out.println("in JMenuItem.fireMenuKeyReleased for " + getText()+
" " + KeyStroke.getKeyStrokeForEvent(event));
}
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
// Lazily create the event:
((MenuKeyListener)listeners[i+1]).menuKeyReleased(event);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param event a <code>MenuKeyEvent</code>
* @see EventListenerList
*/
protected void fireMenuKeyTyped(MenuKeyEvent event) {
if (DEBUG) {
System.out.println("in JMenuItem.fireMenuKeyTyped for " + getText()+
" " + KeyStroke.getKeyStrokeForEvent(event));
}
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==MenuKeyListener.class) {
// Lazily create the event:
((MenuKeyListener)listeners[i+1]).menuKeyTyped(event);
}
}
}
/** {@collect.stats}
* Called by the <code>MenuSelectionManager</code> when the
* <code>MenuElement</code> is selected or unselected.
*
* @param isIncluded true if this menu item is on the part of the menu
* path that changed, false if this menu is part of the
* a menu path that changed, but this particular part of
* that path is still the same
* @see MenuSelectionManager#setSelectedPath(MenuElement[])
*/
public void menuSelectionChanged(boolean isIncluded) {
setArmed(isIncluded);
}
/** {@collect.stats}
* This method returns an array containing the sub-menu
* components for this menu component.
*
* @return an array of <code>MenuElement</code>s
*/
public MenuElement[] getSubElements() {
return new MenuElement[0];
}
/** {@collect.stats}
* Returns the <code>java.awt.Component</code> used to paint
* this object. The returned component will be used to convert
* events and detect if an event is inside a menu component.
*
* @return the <code>Component</code> that paints this menu item
*/
public Component getComponent() {
return this;
}
/** {@collect.stats}
* Adds a <code>MenuDragMouseListener</code> to the menu item.
*
* @param l the <code>MenuDragMouseListener</code> to be added
*/
public void addMenuDragMouseListener(MenuDragMouseListener l) {
listenerList.add(MenuDragMouseListener.class, l);
}
/** {@collect.stats}
* Removes a <code>MenuDragMouseListener</code> from the menu item.
*
* @param l the <code>MenuDragMouseListener</code> to be removed
*/
public void removeMenuDragMouseListener(MenuDragMouseListener l) {
listenerList.remove(MenuDragMouseListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>MenuDragMouseListener</code>s added
* to this JMenuItem with addMenuDragMouseListener().
*
* @return all of the <code>MenuDragMouseListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public MenuDragMouseListener[] getMenuDragMouseListeners() {
return (MenuDragMouseListener[])listenerList.getListeners(
MenuDragMouseListener.class);
}
/** {@collect.stats}
* Adds a <code>MenuKeyListener</code> to the menu item.
*
* @param l the <code>MenuKeyListener</code> to be added
*/
public void addMenuKeyListener(MenuKeyListener l) {
listenerList.add(MenuKeyListener.class, l);
}
/** {@collect.stats}
* Removes a <code>MenuKeyListener</code> from the menu item.
*
* @param l the <code>MenuKeyListener</code> to be removed
*/
public void removeMenuKeyListener(MenuKeyListener l) {
listenerList.remove(MenuKeyListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>MenuKeyListener</code>s added
* to this JMenuItem with addMenuKeyListener().
*
* @return all of the <code>MenuKeyListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public MenuKeyListener[] getMenuKeyListeners() {
return (MenuKeyListener[])listenerList.getListeners(
MenuKeyListener.class);
}
/** {@collect.stats}
* See JComponent.readObject() for information about serialization
* in Swing.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
if (getUIClassID().equals(uiClassID)) {
updateUI();
}
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JMenuItem</code>.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JMenuItem</code>
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Returns the <code>AccessibleContext</code> associated with this
* <code>JMenuItem</code>. For <code>JMenuItem</code>s,
* the <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJMenuItem</code>.
* A new AccessibleJMenuItme instance is created if necessary.
*
* @return an <code>AccessibleJMenuItem</code> that serves as the
* <code>AccessibleContext</code> of this <code>JMenuItem</code>
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJMenuItem();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JMenuItem</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu item user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJMenuItem extends AccessibleAbstractButton implements ChangeListener {
private boolean isArmed = false;
private boolean hasFocus = false;
private boolean isPressed = false;
private boolean isSelected = false;
AccessibleJMenuItem() {
super();
JMenuItem.this.addChangeListener(this);
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU_ITEM;
}
private void fireAccessibilityFocusedEvent(JMenuItem toCheck) {
MenuElement [] path =
MenuSelectionManager.defaultManager().getSelectedPath();
if (path.length > 0) {
Object menuItem = path[path.length - 1];
if (toCheck == menuItem) {
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
}
}
}
/** {@collect.stats}
* Supports the change listener interface and fires property changes.
*/
public void stateChanged(ChangeEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
if (JMenuItem.this.getModel().isArmed()) {
if (!isArmed) {
isArmed = true;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.ARMED);
// Fix for 4848220 moved here to avoid major memory leak
// Here we will fire the event in case of JMenuItem
// See bug 4910323 for details [zav]
fireAccessibilityFocusedEvent(JMenuItem.this);
}
} else {
if (isArmed) {
isArmed = false;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.ARMED, null);
}
}
if (JMenuItem.this.isFocusOwner()) {
if (!hasFocus) {
hasFocus = true;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
}
} else {
if (hasFocus) {
hasFocus = false;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.FOCUSED, null);
}
}
if (JMenuItem.this.getModel().isPressed()) {
if (!isPressed) {
isPressed = true;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.PRESSED);
}
} else {
if (isPressed) {
isPressed = false;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.PRESSED, null);
}
}
if (JMenuItem.this.getModel().isSelected()) {
if (!isSelected) {
isSelected = true;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.CHECKED);
// Fix for 4848220 moved here to avoid major memory leak
// Here we will fire the event in case of JMenu
// See bug 4910323 for details [zav]
fireAccessibilityFocusedEvent(JMenuItem.this);
}
} else {
if (isSelected) {
isSelected = false;
firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.CHECKED, null);
}
}
}
} // inner class AccessibleJMenuItem
}
|
Java
|
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
/*
* Private storage mechanism for Action key-value pairs.
* In most cases this will be an array of alternating
* key-value pairs. As it grows larger it is scaled
* up to a Hashtable.
* <p>
* This does no synchronization, if you need thread safety synchronize on
* another object before calling this.
*
* @author Georges Saab
* @author Scott Violet
*/
class ArrayTable implements Cloneable {
// Our field for storage
private Object table = null;
private static final int ARRAY_BOUNDARY = 8;
/** {@collect.stats}
* Writes the passed in ArrayTable to the passed in ObjectOutputStream.
* The data is saved as an integer indicating how many key/value
* pairs are being archived, followed by the the key/value pairs. If
* <code>table</code> is null, 0 will be written to <code>s</code>.
* <p>
* This is a convenience method that ActionMap/InputMap and
* AbstractAction use to avoid having the same code in each class.
*/
static void writeArrayTable(ObjectOutputStream s, ArrayTable table) throws IOException {
Object keys[];
if (table == null || (keys = table.getKeys(null)) == null) {
s.writeInt(0);
}
else {
// Determine how many keys have Serializable values, when
// done all non-null values in keys identify the Serializable
// values.
int validCount = 0;
for (int counter = 0; counter < keys.length; counter++) {
Object key = keys[counter];
/* include in Serialization when both keys and values are Serializable */
if ( (key instanceof Serializable
&& table.get(key) instanceof Serializable)
||
/* include these only so that we get the appropriate exception below */
(key instanceof ClientPropertyKey
&& ((ClientPropertyKey)key).getReportValueNotSerializable())) {
validCount++;
} else {
keys[counter] = null;
}
}
// Write ou the Serializable key/value pairs.
s.writeInt(validCount);
if (validCount > 0) {
for (int counter = 0; counter < keys.length; counter++) {
if (keys[counter] != null) {
s.writeObject(keys[counter]);
s.writeObject(table.get(keys[counter]));
if (--validCount == 0) {
break;
}
}
}
}
}
}
/*
* Put the key-value pair into storage
*/
public void put(Object key, Object value){
if (table==null) {
table = new Object[] {key, value};
} else {
int size = size();
if (size < ARRAY_BOUNDARY) { // We are an array
if (containsKey(key)) {
Object[] tmp = (Object[])table;
for (int i = 0; i<tmp.length-1; i+=2) {
if (tmp[i].equals(key)) {
tmp[i+1]=value;
break;
}
}
} else {
Object[] array = (Object[])table;
int i = array.length;
Object[] tmp = new Object[i+2];
System.arraycopy(array, 0, tmp, 0, i);
tmp[i] = key;
tmp[i+1] = value;
table = tmp;
}
} else { // We are a hashtable
if ((size==ARRAY_BOUNDARY) && isArray()) {
grow();
}
((Hashtable)table).put(key, value);
}
}
}
/*
* Gets the value for key
*/
public Object get(Object key) {
Object value = null;
if (table !=null) {
if (isArray()) {
Object[] array = (Object[])table;
for (int i = 0; i<array.length-1; i+=2) {
if (array[i].equals(key)) {
value = array[i+1];
break;
}
}
} else {
value = ((Hashtable)table).get(key);
}
}
return value;
}
/*
* Returns the number of pairs in storage
*/
public int size() {
int size;
if (table==null)
return 0;
if (isArray()) {
size = ((Object[])table).length/2;
} else {
size = ((Hashtable)table).size();
}
return size;
}
/*
* Returns true if we have a value for the key
*/
public boolean containsKey(Object key) {
boolean contains = false;
if (table !=null) {
if (isArray()) {
Object[] array = (Object[])table;
for (int i = 0; i<array.length-1; i+=2) {
if (array[i].equals(key)) {
contains = true;
break;
}
}
} else {
contains = ((Hashtable)table).containsKey(key);
}
}
return contains;
}
/*
* Removes the key and its value
* Returns the value for the pair removed
*/
public Object remove(Object key){
Object value = null;
if (key==null) {
return null;
}
if (table !=null) {
if (isArray()){
// Is key on the list?
int index = -1;
Object[] array = (Object[])table;
for (int i = array.length-2; i>=0; i-=2) {
if (array[i].equals(key)) {
index = i;
value = array[i+1];
break;
}
}
// If so, remove it
if (index != -1) {
Object[] tmp = new Object[array.length-2];
// Copy the list up to index
System.arraycopy(array, 0, tmp, 0, index);
// Copy from two past the index, up to
// the end of tmp (which is two elements
// shorter than the old list)
if (index < tmp.length)
System.arraycopy(array, index+2, tmp, index,
tmp.length - index);
// set the listener array to the new array or null
table = (tmp.length == 0) ? null : tmp;
}
} else {
value = ((Hashtable)table).remove(key);
}
if (size()==ARRAY_BOUNDARY - 1 && !isArray()) {
shrink();
}
}
return value;
}
/** {@collect.stats}
* Removes all the mappings.
*/
public void clear() {
table = null;
}
/*
* Returns a clone of the <code>ArrayTable</code>.
*/
public Object clone() {
ArrayTable newArrayTable = new ArrayTable();
if (isArray()) {
Object[] array = (Object[])table;
for (int i = 0 ;i < array.length-1 ; i+=2) {
newArrayTable.put(array[i], array[i+1]);
}
} else {
Hashtable tmp = (Hashtable)table;
Enumeration keys = tmp.keys();
while (keys.hasMoreElements()) {
Object o = keys.nextElement();
newArrayTable.put(o,tmp.get(o));
}
}
return newArrayTable;
}
/** {@collect.stats}
* Returns the keys of the table, or <code>null</code> if there
* are currently no bindings.
* @param keys array of keys
* @return an array of bindings
*/
public Object[] getKeys(Object[] keys) {
if (table == null) {
return null;
}
if (isArray()) {
Object[] array = (Object[])table;
if (keys == null) {
keys = new Object[array.length / 2];
}
for (int i = 0, index = 0 ;i < array.length-1 ; i+=2,
index++) {
keys[index] = array[i];
}
} else {
Hashtable tmp = (Hashtable)table;
Enumeration enum_ = tmp.keys();
int counter = tmp.size();
if (keys == null) {
keys = new Object[counter];
}
while (counter > 0) {
keys[--counter] = enum_.nextElement();
}
}
return keys;
}
/*
* Returns true if the current storage mechanism is
* an array of alternating key-value pairs.
*/
private boolean isArray(){
return (table instanceof Object[]);
}
/*
* Grows the storage from an array to a hashtable.
*/
private void grow() {
Object[] array = (Object[])table;
Hashtable tmp = new Hashtable(array.length/2);
for (int i = 0; i<array.length; i+=2) {
tmp.put(array[i], array[i+1]);
}
table = tmp;
}
/*
* Shrinks the storage from a hashtable to an array.
*/
private void shrink() {
Hashtable tmp = (Hashtable)table;
Object[] array = new Object[tmp.size()*2];
Enumeration keys = tmp.keys();
int j = 0;
while (keys.hasMoreElements()) {
Object o = keys.nextElement();
array[j] = o;
array[j+1] = tmp.get(o);
j+=2;
}
table = array;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.util.Comparator;
/** {@collect.stats}
* This class has been obsoleted by the 1.4 focus APIs. While client code may
* still use this class, developers are strongly encouraged to use
* <code>java.awt.KeyboardFocusManager</code> and
* <code>java.awt.DefaultKeyboardFocusManager</code> instead.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>, and the
* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* for more information.
*
* @author Arnaud Weber
* @author David Mendenhall
*/
public class DefaultFocusManager extends FocusManager {
final FocusTraversalPolicy gluePolicy =
new LegacyGlueFocusTraversalPolicy(this);
private final FocusTraversalPolicy layoutPolicy =
new LegacyLayoutFocusTraversalPolicy(this);
private final LayoutComparator comparator =
new LayoutComparator();
public DefaultFocusManager() {
setDefaultFocusTraversalPolicy(gluePolicy);
}
public Component getComponentAfter(Container aContainer,
Component aComponent)
{
Container root = (aContainer.isFocusCycleRoot())
? aContainer
: aContainer.getFocusCycleRootAncestor();
// Support for mixed 1.4/pre-1.4 focus APIs. If a particular root's
// traversal policy is non-legacy, then honor it.
if (root != null) {
FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
if (policy != gluePolicy) {
return policy.getComponentAfter(root, aComponent);
}
comparator.setComponentOrientation(root.getComponentOrientation());
return layoutPolicy.getComponentAfter(root, aComponent);
}
return null;
}
public Component getComponentBefore(Container aContainer,
Component aComponent)
{
Container root = (aContainer.isFocusCycleRoot())
? aContainer
: aContainer.getFocusCycleRootAncestor();
// Support for mixed 1.4/pre-1.4 focus APIs. If a particular root's
// traversal policy is non-legacy, then honor it.
if (root != null) {
FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
if (policy != gluePolicy) {
return policy.getComponentBefore(root, aComponent);
}
comparator.setComponentOrientation(root.getComponentOrientation());
return layoutPolicy.getComponentBefore(root, aComponent);
}
return null;
}
public Component getFirstComponent(Container aContainer) {
Container root = (aContainer.isFocusCycleRoot())
? aContainer
: aContainer.getFocusCycleRootAncestor();
// Support for mixed 1.4/pre-1.4 focus APIs. If a particular root's
// traversal policy is non-legacy, then honor it.
if (root != null) {
FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
if (policy != gluePolicy) {
return policy.getFirstComponent(root);
}
comparator.setComponentOrientation(root.getComponentOrientation());
return layoutPolicy.getFirstComponent(root);
}
return null;
}
public Component getLastComponent(Container aContainer) {
Container root = (aContainer.isFocusCycleRoot())
? aContainer
: aContainer.getFocusCycleRootAncestor();
// Support for mixed 1.4/pre-1.4 focus APIs. If a particular root's
// traversal policy is non-legacy, then honor it.
if (root != null) {
FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
if (policy != gluePolicy) {
return policy.getLastComponent(root);
}
comparator.setComponentOrientation(root.getComponentOrientation());
return layoutPolicy.getLastComponent(root);
}
return null;
}
public boolean compareTabOrder(Component a, Component b) {
return (comparator.compare(a, b) < 0);
}
}
final class LegacyLayoutFocusTraversalPolicy
extends LayoutFocusTraversalPolicy
{
LegacyLayoutFocusTraversalPolicy(DefaultFocusManager defaultFocusManager) {
super(new CompareTabOrderComparator(defaultFocusManager));
}
}
final class CompareTabOrderComparator implements Comparator {
private final DefaultFocusManager defaultFocusManager;
CompareTabOrderComparator(DefaultFocusManager defaultFocusManager) {
this.defaultFocusManager = defaultFocusManager;
}
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
return (defaultFocusManager.compareTabOrder((Component)o1,
(Component)o2)) ? -1 : 1;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
/** {@collect.stats}
* This interface represents the current state of the
* selection for any of the components that display a
* list of values with stable indices. The selection is
* modeled as a set of intervals, each interval represents
* a contiguous range of selected list elements.
* The methods for modifying the set of selected intervals
* all take a pair of indices, index0 and index1, that represent
* a closed interval, i.e. the interval includes both index0 and
* index1.
*
* @author Hans Muller
* @author Philip Milne
* @see DefaultListSelectionModel
*/
public interface ListSelectionModel
{
/** {@collect.stats}
* A value for the selectionMode property: select one list index
* at a time.
*
* @see #setSelectionMode
*/
int SINGLE_SELECTION = 0;
/** {@collect.stats}
* A value for the selectionMode property: select one contiguous
* range of indices at a time.
*
* @see #setSelectionMode
*/
int SINGLE_INTERVAL_SELECTION = 1;
/** {@collect.stats}
* A value for the selectionMode property: select one or more
* contiguous ranges of indices at a time.
*
* @see #setSelectionMode
*/
int MULTIPLE_INTERVAL_SELECTION = 2;
/** {@collect.stats}
* Changes the selection to be between {@code index0} and {@code index1}
* inclusive. {@code index0} doesn't have to be less than or equal to
* {@code index1}.
* <p>
* In {@code SINGLE_SELECTION} selection mode, only the second index
* is used.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @see #addListSelectionListener
*/
void setSelectionInterval(int index0, int index1);
/** {@collect.stats}
* Changes the selection to be the set union of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* In {@code SINGLE_SELECTION} selection mode, this is equivalent
* to calling {@code setSelectionInterval}, and only the second index
* is used. In {@code SINGLE_INTERVAL_SELECTION} selection mode, this
* method behaves like {@code setSelectionInterval}, unless the given
* interval is immediately adjacent to or overlaps the existing selection,
* and can therefore be used to grow the selection.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @see #addListSelectionListener
* @see #setSelectionInterval
*/
void addSelectionInterval(int index0, int index1);
/** {@collect.stats}
* Changes the selection to be the set difference of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* In {@code SINGLE_INTERVAL_SELECTION} selection mode, if the removal
* would produce two disjoint selections, the removal is extended through
* the greater end of the selection. For example, if the selection is
* {@code 0-10} and you supply indices {@code 5,6} (in any order) the
* resulting selection is {@code 0-4}.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @see #addListSelectionListener
*/
void removeSelectionInterval(int index0, int index1);
/** {@collect.stats}
* Returns the first selected index or -1 if the selection is empty.
*/
int getMinSelectionIndex();
/** {@collect.stats}
* Returns the last selected index or -1 if the selection is empty.
*/
int getMaxSelectionIndex();
/** {@collect.stats}
* Returns true if the specified index is selected.
*/
boolean isSelectedIndex(int index);
/** {@collect.stats}
* Return the first index argument from the most recent call to
* setSelectionInterval(), addSelectionInterval() or removeSelectionInterval().
* The most recent index0 is considered the "anchor" and the most recent
* index1 is considered the "lead". Some interfaces display these
* indices specially, e.g. Windows95 displays the lead index with a
* dotted yellow outline.
*
* @see #getLeadSelectionIndex
* @see #setSelectionInterval
* @see #addSelectionInterval
*/
int getAnchorSelectionIndex();
/** {@collect.stats}
* Set the anchor selection index.
*
* @see #getAnchorSelectionIndex
*/
void setAnchorSelectionIndex(int index);
/** {@collect.stats}
* Return the second index argument from the most recent call to
* setSelectionInterval(), addSelectionInterval() or removeSelectionInterval().
*
* @see #getAnchorSelectionIndex
* @see #setSelectionInterval
* @see #addSelectionInterval
*/
int getLeadSelectionIndex();
/** {@collect.stats}
* Set the lead selection index.
*
* @see #getLeadSelectionIndex
*/
void setLeadSelectionIndex(int index);
/** {@collect.stats}
* Change the selection to the empty set. If this represents
* a change to the current selection then notify each ListSelectionListener.
*
* @see #addListSelectionListener
*/
void clearSelection();
/** {@collect.stats}
* Returns true if no indices are selected.
*/
boolean isSelectionEmpty();
/** {@collect.stats}
* Insert length indices beginning before/after index. This is typically
* called to sync the selection model with a corresponding change
* in the data model.
*/
void insertIndexInterval(int index, int length, boolean before);
/** {@collect.stats}
* Remove the indices in the interval index0,index1 (inclusive) from
* the selection model. This is typically called to sync the selection
* model width a corresponding change in the data model.
*/
void removeIndexInterval(int index0, int index1);
/** {@collect.stats}
* Sets the {@code valueIsAdjusting} property, which indicates whether
* or not upcoming selection changes should be considered part of a single
* change. The value of this property is used to initialize the
* {@code valueIsAdjusting} property of the {@code ListSelectionEvent}s that
* are generated.
* <p>
* For example, if the selection is being updated in response to a user
* drag, this property can be set to {@code true} when the drag is initiated
* and set to {@code false} when the drag is finished. During the drag,
* listeners receive events with a {@code valueIsAdjusting} property
* set to {@code true}. At the end of the drag, when the change is
* finalized, listeners receive an event with the value set to {@code false}.
* Listeners can use this pattern if they wish to update only when a change
* has been finalized.
* <p>
* Setting this property to {@code true} begins a series of changes that
* is to be considered part of a single change. When the property is changed
* back to {@code false}, an event is sent out characterizing the entire
* selection change (if there was one), with the event's
* {@code valueIsAdjusting} property set to {@code false}.
*
* @param valueIsAdjusting the new value of the property
* @see #getValueIsAdjusting
* @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
*/
void setValueIsAdjusting(boolean valueIsAdjusting);
/** {@collect.stats}
* Returns {@code true} if the selection is undergoing a series of changes.
*
* @return true if the selection is undergoing a series of changes
* @see #setValueIsAdjusting
*/
boolean getValueIsAdjusting();
/** {@collect.stats}
* Sets the selection mode. The following list describes the accepted
* selection modes:
* <ul>
* <li>{@code ListSelectionModel.SINGLE_SELECTION} -
* Only one list index can be selected at a time. In this mode,
* {@code setSelectionInterval} and {@code addSelectionInterval} are
* equivalent, both replacing the current selection with the index
* represented by the second argument (the "lead").
* <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
* Only one contiguous interval can be selected at a time.
* In this mode, {@code addSelectionInterval} behaves like
* {@code setSelectionInterval} (replacing the current selection),
* unless the given interval is immediately adjacent to or overlaps
* the existing selection, and can therefore be used to grow it.
* <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
* In this mode, there's no restriction on what can be selected.
* </ul>
*
* @see #getSelectionMode
* @throws IllegalArgumentException if the selection mode isn't
* one of those allowed
*/
void setSelectionMode(int selectionMode);
/** {@collect.stats}
* Returns the current selection mode.
*
* @return the current selection mode
* @see #setSelectionMode
*/
int getSelectionMode();
/** {@collect.stats}
* Add a listener to the list that's notified each time a change
* to the selection occurs.
*
* @param x the ListSelectionListener
* @see #removeListSelectionListener
* @see #setSelectionInterval
* @see #addSelectionInterval
* @see #removeSelectionInterval
* @see #clearSelection
* @see #insertIndexInterval
* @see #removeIndexInterval
*/
void addListSelectionListener(ListSelectionListener x);
/** {@collect.stats}
* Remove a listener from the list that's notified each time a
* change to the selection occurs.
*
* @param x the ListSelectionListener
* @see #addListSelectionListener
*/
void removeListSelectionListener(ListSelectionListener x);
}
|
Java
|
/*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import javax.accessibility.*;
/** {@collect.stats}
* An extended version of <code>java.awt.Frame</code> that adds support for
* the JFC/Swing component architecture.
* You can find task-oriented documentation about using <code>JFrame</code>
* in <em>The Java Tutorial</em>, in the section
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html">How to Make Frames</a>.
*
* <p>
* The <code>JFrame</code> class is slightly incompatible with <code>Frame</code>.
* Like all other JFC/Swing top-level containers,
* a <code>JFrame</code> contains a <code>JRootPane</code> as its only child.
* The <b>content pane</b> provided by the root pane should,
* as a rule, contain
* all the non-menu components displayed by the <code>JFrame</code>.
* This is different from the AWT <code>Frame</code> case.
* As a conveniance <code>add</code> and its variants, <code>remove</code> and
* <code>setLayout</code> have been overridden to forward to the
* <code>contentPane</code> as necessary. This means you can write:
* <pre>
* frame.add(child);
* </pre>
* And the child will be added to the contentPane.
* The content pane will
* always be non-null. Attempting to set it to null will cause the JFrame
* to throw an exception. The default content pane will have a BorderLayout
* manager set on it.
* Refer to {@link javax.swing.RootPaneContainer}
* for details on adding, removing and setting the <code>LayoutManager</code>
* of a <code>JFrame</code>.
* <p>
* Unlike a <code>Frame</code>, a <code>JFrame</code> has some notion of how to
* respond when the user attempts to close the window. The default behavior
* is to simply hide the JFrame when the user closes the window. To change the
* default behavior, you invoke the method
* {@link #setDefaultCloseOperation}.
* To make the <code>JFrame</code> behave the same as a <code>Frame</code>
* instance, use
* <code>setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)</code>.
* <p>
* For more information on content panes
* and other features that root panes provide,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html">Using Top-Level Containers</a> in <em>The Java Tutorial</em>.
* <p>
* In a multi-screen environment, you can create a <code>JFrame</code>
* on a different screen device. See {@link java.awt.Frame} for more
* information.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JRootPane
* @see #setDefaultCloseOperation
* @see java.awt.event.WindowListener#windowClosing
* @see javax.swing.RootPaneContainer
*
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getContentPane
* description: A toplevel window which can be minimized to an icon.
*
* @author Jeff Dinkins
* @author Georges Saab
* @author David Kloba
*/
public class JFrame extends Frame implements WindowConstants,
Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
/** {@collect.stats}
* The exit application default window close operation. If a window
* has this set as the close operation and is closed in an applet,
* a <code>SecurityException</code> may be thrown.
* It is recommended you only use this in an application.
* <p>
* @since 1.3
*/
public static final int EXIT_ON_CLOSE = 3;
/** {@collect.stats}
* Key into the AppContext, used to check if should provide decorations
* by default.
*/
private static final Object defaultLookAndFeelDecoratedKey = new Object(); // JFrame.defaultLookAndFeelDecorated
private int defaultCloseOperation = HIDE_ON_CLOSE;
/** {@collect.stats}
* The <code>TransferHandler</code> for this frame.
*/
private TransferHandler transferHandler;
/** {@collect.stats}
* The <code>JRootPane</code> instance that manages the
* <code>contentPane</code>
* and optional <code>menuBar</code> for this frame, as well as the
* <code>glassPane</code>.
*
* @see JRootPane
* @see RootPaneContainer
*/
protected JRootPane rootPane;
/** {@collect.stats}
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>JFrame</code> is constructed.
*
* @see #isRootPaneCheckingEnabled
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean rootPaneCheckingEnabled = false;
/** {@collect.stats}
* Constructs a new frame that is initially invisible.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see Component#setSize
* @see Component#setVisible
* @see JComponent#getDefaultLocale
*/
public JFrame() throws HeadlessException {
super();
frameInit();
}
/** {@collect.stats}
* Creates a <code>Frame</code> in the specified
* <code>GraphicsConfiguration</code> of
* a screen device and a blank title.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param gc the <code>GraphicsConfiguration</code> that is used
* to construct the new <code>Frame</code>;
* if <code>gc</code> is <code>null</code>, the system
* default <code>GraphicsConfiguration</code> is assumed
* @exception IllegalArgumentException if <code>gc</code> is not from
* a screen device. This exception is always thrown when
* GraphicsEnvironment.isHeadless() returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
* @since 1.3
*/
public JFrame(GraphicsConfiguration gc) {
super(gc);
frameInit();
}
/** {@collect.stats}
* Creates a new, initially invisible <code>Frame</code> with the
* specified title.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param title the title for the frame
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see Component#setSize
* @see Component#setVisible
* @see JComponent#getDefaultLocale
*/
public JFrame(String title) throws HeadlessException {
super(title);
frameInit();
}
/** {@collect.stats}
* Creates a <code>JFrame</code> with the specified title and the
* specified <code>GraphicsConfiguration</code> of a screen device.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @param title the title to be displayed in the
* frame's border. A <code>null</code> value is treated as
* an empty string, "".
* @param gc the <code>GraphicsConfiguration</code> that is used
* to construct the new <code>JFrame</code> with;
* if <code>gc</code> is <code>null</code>, the system
* default <code>GraphicsConfiguration</code> is assumed
* @exception IllegalArgumentException if <code>gc</code> is not from
* a screen device. This exception is always thrown when
* GraphicsEnvironment.isHeadless() returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
* @since 1.3
*/
public JFrame(String title, GraphicsConfiguration gc) {
super(title, gc);
frameInit();
}
/** {@collect.stats} Called by the constructors to init the <code>JFrame</code> properly. */
protected void frameInit() {
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
setLocale( JComponent.getDefaultLocale() );
setRootPane(createRootPane());
setBackground(UIManager.getColor("control"));
setRootPaneCheckingEnabled(true);
if (JFrame.isDefaultLookAndFeelDecorated()) {
boolean supportsWindowDecorations =
UIManager.getLookAndFeel().getSupportsWindowDecorations();
if (supportsWindowDecorations) {
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
}
}
sun.awt.SunToolkit.checkAndSetPolicy(this, true);
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>rootPane</code>.
*/
protected JRootPane createRootPane() {
JRootPane rp = new JRootPane();
// NOTE: this uses setOpaque vs LookAndFeel.installProperty as there
// is NO reason for the RootPane not to be opaque. For painting to
// work the contentPane must be opaque, therefor the RootPane can
// also be opaque.
rp.setOpaque(true);
return rp;
}
/** {@collect.stats}
* Processes window events occurring on this component.
* Hides the window or disposes of it, as specified by the setting
* of the <code>defaultCloseOperation</code> property.
*
* @param e the window event
* @see #setDefaultCloseOperation
* @see java.awt.Window#processWindowEvent
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
switch(defaultCloseOperation) {
case HIDE_ON_CLOSE:
setVisible(false);
break;
case DISPOSE_ON_CLOSE:
dispose();
break;
case DO_NOTHING_ON_CLOSE:
default:
break;
case EXIT_ON_CLOSE:
// This needs to match the checkExit call in
// setDefaultCloseOperation
System.exit(0);
break;
}
}
}
// public void setMenuBar(MenuBar menu) {
// throw new IllegalComponentStateException("Please use setJMenuBar() with JFrame.");
// }
/** {@collect.stats}
* Sets the operation that will happen by default when
* the user initiates a "close" on this frame.
* You must specify one of the following choices:
* <p>
* <ul>
* <li><code>DO_NOTHING_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Don't do anything; require the
* program to handle the operation in the <code>windowClosing</code>
* method of a registered <code>WindowListener</code> object.
*
* <li><code>HIDE_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Automatically hide the frame after
* invoking any registered <code>WindowListener</code>
* objects.
*
* <li><code>DISPOSE_ON_CLOSE</code>
* (defined in <code>WindowConstants</code>):
* Automatically hide and dispose the
* frame after invoking any registered <code>WindowListener</code>
* objects.
*
* <li><code>EXIT_ON_CLOSE</code>
* (defined in <code>JFrame</code>):
* Exit the application using the <code>System</code>
* <code>exit</code> method. Use this only in applications.
* </ul>
* <p>
* The value is set to <code>HIDE_ON_CLOSE</code> by default. Changes
* to the value of this property cause the firing of a property
* change event, with property name "defaultCloseOperation".
* <p>
* <b>Note</b>: When the last displayable window within the
* Java virtual machine (VM) is disposed of, the VM may
* terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html">
* AWT Threading Issues</a> for more information.
*
* @param operation the operation which should be performed when the
* user closes the frame
* @exception IllegalArgumentException if defaultCloseOperation value
* isn't one of the above valid values
* @see #addWindowListener
* @see #getDefaultCloseOperation
* @see WindowConstants
* @throws SecurityException
* if <code>EXIT_ON_CLOSE</code> has been specified and the
* <code>SecurityManager</code> will
* not allow the caller to invoke <code>System.exit</code>
* @see java.lang.Runtime#exit(int)
*
* @beaninfo
* preferred: true
* bound: true
* enum: DO_NOTHING_ON_CLOSE WindowConstants.DO_NOTHING_ON_CLOSE
* HIDE_ON_CLOSE WindowConstants.HIDE_ON_CLOSE
* DISPOSE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE
* EXIT_ON_CLOSE WindowConstants.EXIT_ON_CLOSE
* description: The frame's default close operation.
*/
public void setDefaultCloseOperation(int operation) {
if (operation != DO_NOTHING_ON_CLOSE &&
operation != HIDE_ON_CLOSE &&
operation != DISPOSE_ON_CLOSE &&
operation != EXIT_ON_CLOSE) {
throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE");
}
if (this.defaultCloseOperation != operation) {
if (operation == EXIT_ON_CLOSE) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkExit(0);
}
}
int oldValue = this.defaultCloseOperation;
this.defaultCloseOperation = operation;
firePropertyChange("defaultCloseOperation", oldValue, operation);
}
}
/** {@collect.stats}
* Returns the operation that occurs when the user
* initiates a "close" on this frame.
*
* @return an integer indicating the window-close operation
* @see #setDefaultCloseOperation
*/
public int getDefaultCloseOperation() {
return defaultCloseOperation;
}
/** {@collect.stats}
* Sets the {@code transferHandler} property, which is a mechanism to
* support transfer of data into this component. Use {@code null}
* if the component does not support data transfer operations.
* <p>
* If the system property {@code suppressSwingDropSupport} is {@code false}
* (the default) and the current drop target on this component is either
* {@code null} or not a user-set drop target, this method will change the
* drop target as follows: If {@code newHandler} is {@code null} it will
* clear the drop target. If not {@code null} it will install a new
* {@code DropTarget}.
* <p>
* Note: When used with {@code JFrame}, {@code TransferHandler} only
* provides data import capability, as the data export related methods
* are currently typed to {@code JComponent}.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>, a section in
* <em>The Java Tutorial</em>, for more information.
*
* @param newHandler the new {@code TransferHandler}
*
* @see TransferHandler
* @see #getTransferHandler
* @see java.awt.Component#setDropTarget
* @since 1.6
*
* @beaninfo
* bound: true
* hidden: true
* description: Mechanism for transfer of data into the component
*/
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = transferHandler;
transferHandler = newHandler;
SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/** {@collect.stats}
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.6
*/
public TransferHandler getTransferHandler() {
return transferHandler;
}
/** {@collect.stats}
* Just calls <code>paint(g)</code>. This method was overridden to
* prevent an unnecessary call to clear the background.
*
* @param g the Graphics context in which to paint
*/
public void update(Graphics g) {
paint(g);
}
/** {@collect.stats}
* Sets the menubar for this frame.
* @param menubar the menubar being placed in the frame
*
* @see #getJMenuBar
*
* @beaninfo
* hidden: true
* description: The menubar for accessing pulldown menus from this frame.
*/
public void setJMenuBar(JMenuBar menubar) {
getRootPane().setMenuBar(menubar);
}
/** {@collect.stats}
* Returns the menubar set on this frame.
* @return the menubar for this frame
*
* @see #setJMenuBar
*/
public JMenuBar getJMenuBar() {
return getRootPane().getMenuBar();
}
/** {@collect.stats}
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @return true if <code>add</code> and <code>setLayout</code>
* are fowarded; false otherwise
*
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/** {@collect.stats}
* Sets whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @param enabled true if <code>add</code> and <code>setLayout</code>
* are forwarded, false if they should operate directly on the
* <code>JFrame</code>.
*
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
* @beaninfo
* hidden: true
* description: Whether the add and setLayout methods are forwarded
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/** {@collect.stats}
* Adds the specified child <code>Component</code>.
* This method is overridden to conditionally forward calls to the
* <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for
* details.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
*
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected void addImpl(Component comp, Object constraints, int index)
{
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/** {@collect.stats}
* Removes the specified component from the container. If
* <code>comp</code> is not the <code>rootPane</code>, this will forward
* the call to the <code>contentPane</code>. This will do nothing if
* <code>comp</code> is not a child of the <code>JFrame</code> or
* <code>contentPane</code>.
*
* @param comp the component to be removed
* @throws NullPointerException if <code>comp</code> is null
* @see #add
* @see javax.swing.RootPaneContainer
*/
public void remove(Component comp) {
if (comp == rootPane) {
super.remove(comp);
} else {
getContentPane().remove(comp);
}
}
/** {@collect.stats}
* Sets the <code>LayoutManager</code>.
* Overridden to conditionally forward the call to the
* <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for
* more information.
*
* @param manager the <code>LayoutManager</code>
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
public void setLayout(LayoutManager manager) {
if(isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
/** {@collect.stats}
* Returns the <code>rootPane</code> object for this frame.
* @return the <code>rootPane</code> property
*
* @see #setRootPane
* @see RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/** {@collect.stats}
* Sets the <code>rootPane</code> property.
* This method is called by the constructor.
* @param root the <code>rootPane</code> object for this frame
*
* @see #getRootPane
*
* @beaninfo
* hidden: true
* description: the RootPane object for this frame.
*/
protected void setRootPane(JRootPane root)
{
if(rootPane != null) {
remove(rootPane);
}
rootPane = root;
if(rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void setIconImage(Image image) {
super.setIconImage(image);
}
/** {@collect.stats}
* Returns the <code>contentPane</code> object for this frame.
* @return the <code>contentPane</code> property
*
* @see #setContentPane
* @see RootPaneContainer#getContentPane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/** {@collect.stats}
* Sets the <code>contentPane</code> property.
* This method is called by the constructor.
* <p>
* Swing's painting architecture requires an opaque <code>JComponent</code>
* in the containment hiearchy. This is typically provided by the
* content pane. If you replace the content pane it is recommended you
* replace it with an opaque <code>JComponent</code>.
*
* @param contentPane the <code>contentPane</code> object for this frame
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see #getContentPane
* @see RootPaneContainer#setContentPane
* @see JRootPane
*
* @beaninfo
* hidden: true
* description: The client area of the frame where child
* components are normally inserted.
*/
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
/** {@collect.stats}
* Returns the <code>layeredPane</code> object for this frame.
* @return the <code>layeredPane</code> property
*
* @see #setLayeredPane
* @see RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/** {@collect.stats}
* Sets the <code>layeredPane</code> property.
* This method is called by the constructor.
* @param layeredPane the <code>layeredPane</code> object for this frame
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is <code>null</code>
* @see #getLayeredPane
* @see RootPaneContainer#setLayeredPane
*
* @beaninfo
* hidden: true
* description: The pane that holds the various frame layers.
*/
public void setLayeredPane(JLayeredPane layeredPane) {
getRootPane().setLayeredPane(layeredPane);
}
/** {@collect.stats}
* Returns the <code>glassPane</code> object for this frame.
* @return the <code>glassPane</code> property
*
* @see #setGlassPane
* @see RootPaneContainer#getGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/** {@collect.stats}
* Sets the <code>glassPane</code> property.
* This method is called by the constructor.
* @param glassPane the <code>glassPane</code> object for this frame
*
* @see #getGlassPane
* @see RootPaneContainer#setGlassPane
*
* @beaninfo
* hidden: true
* description: A transparent pane used for menu rendering.
*/
public void setGlassPane(Component glassPane) {
getRootPane().setGlassPane(glassPane);
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.6
*/
public Graphics getGraphics() {
JComponent.getGraphicsInvoked(this);
return super.getGraphics();
}
/** {@collect.stats}
* Repaints the specified rectangle of this component within
* <code>time</code> milliseconds. Refer to <code>RepaintManager</code>
* for details on how the repaint is handled.
*
* @param time maximum time in milliseconds before update
* @param x the <i>x</i> coordinate
* @param y the <i>y</i> coordinate
* @param width the width
* @param height the height
* @see RepaintManager
* @since 1.6
*/
public void repaint(long time, int x, int y, int width, int height) {
if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) {
RepaintManager.currentManager(this).addDirtyRegion(
this, x, y, width, height);
}
else {
super.repaint(time, x, y, width, height);
}
}
/** {@collect.stats}
* Provides a hint as to whether or not newly created <code>JFrame</code>s
* should have their Window decorations (such as borders, widgets to
* close the window, title...) provided by the current look
* and feel. If <code>defaultLookAndFeelDecorated</code> is true,
* the current <code>LookAndFeel</code> supports providing window
* decorations, and the current window manager supports undecorated
* windows, then newly created <code>JFrame</code>s will have their
* Window decorations provided by the current <code>LookAndFeel</code>.
* Otherwise, newly created <code>JFrame</code>s will have their
* Window decorations provided by the current window manager.
* <p>
* You can get the same effect on a single JFrame by doing the following:
* <pre>
* JFrame frame = new JFrame();
* frame.setUndecorated(true);
* frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
* </pre>
*
* @param defaultLookAndFeelDecorated A hint as to whether or not current
* look and feel should provide window decorations
* @see javax.swing.LookAndFeel#getSupportsWindowDecorations
* @since 1.4
*/
public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) {
if (defaultLookAndFeelDecorated) {
SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE);
} else {
SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE);
}
}
/** {@collect.stats}
* Returns true if newly created <code>JFrame</code>s should have their
* Window decorations provided by the current look and feel. This is only
* a hint, as certain look and feels may not support this feature.
*
* @return true if look and feel should provide Window decorations.
* @since 1.4
*/
public static boolean isDefaultLookAndFeelDecorated() {
Boolean defaultLookAndFeelDecorated =
(Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey);
if (defaultLookAndFeelDecorated == null) {
defaultLookAndFeelDecorated = Boolean.FALSE;
}
return defaultLookAndFeelDecorated.booleanValue();
}
/** {@collect.stats}
* Returns a string representation of this <code>JFrame</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JFrame</code>
*/
protected String paramString() {
String defaultCloseOperationString;
if (defaultCloseOperation == HIDE_ON_CLOSE) {
defaultCloseOperationString = "HIDE_ON_CLOSE";
} else if (defaultCloseOperation == DISPOSE_ON_CLOSE) {
defaultCloseOperationString = "DISPOSE_ON_CLOSE";
} else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) {
defaultCloseOperationString = "DO_NOTHING_ON_CLOSE";
} else if (defaultCloseOperation == 3) {
defaultCloseOperationString = "EXIT_ON_CLOSE";
} else defaultCloseOperationString = "";
String rootPaneString = (rootPane != null ?
rootPane.toString() : "");
String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
"true" : "false");
return super.paramString() +
",defaultCloseOperation=" + defaultCloseOperationString +
",rootPane=" + rootPaneString +
",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats} The accessible context property. */
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JFrame.
* For JFrames, the AccessibleContext takes the form of an
* AccessibleJFrame.
* A new AccessibleJFrame instance is created if necessary.
*
* @return an AccessibleJFrame that serves as the
* AccessibleContext of this JFrame
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJFrame();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JFrame</code> class. It provides an implementation of the
* Java Accessibility API appropriate to frame user-interface
* elements.
*/
protected class AccessibleJFrame extends AccessibleAWTFrame {
// AccessibleContext methods
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else {
if (getTitle() == null) {
return super.getAccessibleName();
} else {
return getTitle();
}
}
}
/** {@collect.stats}
* Get the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (isResizable()) {
states.add(AccessibleState.RESIZABLE);
}
if (getFocusOwner() != null) {
states.add(AccessibleState.ACTIVE);
}
// FIXME: [[[WDW - should also return ICONIFIED and ICONIFIABLE
// if we can ever figure these out]]]
return states;
}
} // inner class AccessibleJFrame
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.awt.Color;
import java.awt.Font;
import java.util.*;
import java.beans.*;
/** {@collect.stats}
* A component that lets the user graphically select a value by sliding
* a knob within a bounded interval.
* <p>
* The slider can show both
* major tick marks, and minor tick marks between the major ones. The number of
* values between the tick marks is controlled with
* <code>setMajorTickSpacing</code> and <code>setMinorTickSpacing</code>.
* Painting of tick marks is controlled by {@code setPaintTicks}.
* <p>
* Sliders can also print text labels at regular intervals (or at
* arbitrary locations) along the slider track. Painting of labels is
* controlled by {@code setLabelTable} and {@code setPaintLabels}.
* <p>
* For further information and examples see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/slider.html">How to Use Sliders</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A component that supports selecting a integer value from a range.
*
* @author David Kloba
*/
public class JSlider extends JComponent implements SwingConstants, Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "SliderUI";
private boolean paintTicks = false;
private boolean paintTrack = true;
private boolean paintLabels = false;
private boolean isInverted = false;
/** {@collect.stats}
* The data model that handles the numeric maximum value,
* minimum value, and current-position value for the slider.
*/
protected BoundedRangeModel sliderModel;
/** {@collect.stats}
* The number of values between the major tick marks -- the
* larger marks that break up the minor tick marks.
*/
protected int majorTickSpacing;
/** {@collect.stats}
* The number of values between the minor tick marks -- the
* smaller marks that occur between the major tick marks.
* @see #setMinorTickSpacing
*/
protected int minorTickSpacing;
/** {@collect.stats}
* If true, the knob (and the data value it represents)
* resolve to the closest tick mark next to where the user
* positioned the knob. The default is false.
* @see #setSnapToTicks
*/
protected boolean snapToTicks = false;
/** {@collect.stats}
* If true, the knob (and the data value it represents)
* resolve to the closest slider value next to where the user
* positioned the knob.
*/
boolean snapToValue = true;
/** {@collect.stats}
* Whether the slider is horizontal or vertical
* The default is horizontal.
*
* @see #setOrientation
*/
protected int orientation;
/** {@collect.stats}
* {@code Dictionary} of what labels to draw at which values
*/
private Dictionary labelTable;
/** {@collect.stats}
* The changeListener (no suffix) is the listener we add to the
* slider's model. This listener is initialized to the
* {@code ChangeListener} returned from {@code createChangeListener},
* which by default just forwards events
* to {@code ChangeListener}s (if any) added directly to the slider.
*
* @see #addChangeListener
* @see #createChangeListener
*/
protected ChangeListener changeListener = createChangeListener();
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per slider instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this". The event is lazily
* created the first time that an event notification is fired.
*
* @see #fireStateChanged
*/
protected transient ChangeEvent changeEvent = null;
private void checkOrientation(int orientation) {
switch (orientation) {
case VERTICAL:
case HORIZONTAL:
break;
default:
throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
}
}
/** {@collect.stats}
* Creates a horizontal slider with the range 0 to 100 and
* an initial value of 50.
*/
public JSlider() {
this(HORIZONTAL, 0, 100, 50);
}
/** {@collect.stats}
* Creates a slider using the specified orientation with the
* range {@code 0} to {@code 100} and an initial value of {@code 50}.
* The orientation can be
* either <code>SwingConstants.VERTICAL</code> or
* <code>SwingConstants.HORIZONTAL</code>.
*
* @param orientation the orientation of the slider
* @throws IllegalArgumentException if orientation is not one of {@code VERTICAL}, {@code HORIZONTAL}
* @see #setOrientation
*/
public JSlider(int orientation) {
this(orientation, 0, 100, 50);
}
/** {@collect.stats}
* Creates a horizontal slider using the specified min and max
* with an initial value equal to the average of the min plus max.
* <p>
* The <code>BoundedRangeModel</code> that holds the slider's data
* handles any issues that may arise from improperly setting the
* minimum and maximum values on the slider. See the
* {@code BoundedRangeModel} documentation for details.
*
* @param min the minimum value of the slider
* @param max the maximum value of the slider
*
* @see BoundedRangeModel
* @see #setMinimum
* @see #setMaximum
*/
public JSlider(int min, int max) {
this(HORIZONTAL, min, max, (min + max) / 2);
}
/** {@collect.stats}
* Creates a horizontal slider using the specified min, max and value.
* <p>
* The <code>BoundedRangeModel</code> that holds the slider's data
* handles any issues that may arise from improperly setting the
* minimum, initial, and maximum values on the slider. See the
* {@code BoundedRangeModel} documentation for details.
*
* @param min the minimum value of the slider
* @param max the maximum value of the slider
* @param value the initial value of the slider
*
* @see BoundedRangeModel
* @see #setMinimum
* @see #setMaximum
* @see #setValue
*/
public JSlider(int min, int max, int value) {
this(HORIZONTAL, min, max, value);
}
/** {@collect.stats}
* Creates a slider with the specified orientation and the
* specified minimum, maximum, and initial values.
* The orientation can be
* either <code>SwingConstants.VERTICAL</code> or
* <code>SwingConstants.HORIZONTAL</code>.
* <p>
* The <code>BoundedRangeModel</code> that holds the slider's data
* handles any issues that may arise from improperly setting the
* minimum, initial, and maximum values on the slider. See the
* {@code BoundedRangeModel} documentation for details.
*
* @param orientation the orientation of the slider
* @param min the minimum value of the slider
* @param max the maximum value of the slider
* @param value the initial value of the slider
*
* @throws IllegalArgumentException if orientation is not one of {@code VERTICAL}, {@code HORIZONTAL}
*
* @see BoundedRangeModel
* @see #setOrientation
* @see #setMinimum
* @see #setMaximum
* @see #setValue
*/
public JSlider(int orientation, int min, int max, int value)
{
checkOrientation(orientation);
this.orientation = orientation;
sliderModel = new DefaultBoundedRangeModel(value, 0, min, max);
sliderModel.addChangeListener(changeListener);
updateUI();
}
/** {@collect.stats}
* Creates a horizontal slider using the specified
* BoundedRangeModel.
*/
public JSlider(BoundedRangeModel brm)
{
this.orientation = JSlider.HORIZONTAL;
setModel(brm);
sliderModel.addChangeListener(changeListener);
updateUI();
}
/** {@collect.stats}
* Gets the UI object which implements the L&F for this component.
*
* @return the SliderUI object that implements the Slider L&F
*/
public SliderUI getUI() {
return(SliderUI)ui;
}
/** {@collect.stats}
* Sets the UI object which implements the L&F for this component.
*
* @param ui the SliderUI L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the slider's LookAndFeel.
*/
public void setUI(SliderUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((SliderUI)UIManager.getUI(this));
// The labels preferred size may be derived from the font
// of the slider, so we must update the UI of the slider first, then
// that of labels. This way when setSize is called the right
// font is used.
updateLabelUIs();
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return "SliderUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* We pass Change events along to the listeners with the
* the slider (instead of the model itself) as the event source.
*/
private class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
fireStateChanged();
}
}
/** {@collect.stats}
* Subclasses that want to handle {@code ChangeEvent}s
* from the model differently
* can override this to return
* an instance of a custom <code>ChangeListener</code> implementation.
* The default {@code ChangeListener} simply calls the
* {@code fireStateChanged} method to forward {@code ChangeEvent}s
* to the {@code ChangeListener}s that have been added directly to the
* slider.
* @see #changeListener
* @see #fireStateChanged
* @see javax.swing.event.ChangeListener
* @see javax.swing.BoundedRangeModel
*/
protected ChangeListener createChangeListener() {
return new ModelListener();
}
/** {@collect.stats}
* Adds a ChangeListener to the slider.
*
* @param l the ChangeListener to add
* @see #fireStateChanged
* @see #removeChangeListener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a ChangeListener from the slider.
*
* @param l the ChangeListener to remove
* @see #fireStateChanged
* @see #addChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this JSlider with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Send a {@code ChangeEvent}, whose source is this {@code JSlider}, to
* all {@code ChangeListener}s that have registered interest in
* {@code ChangeEvent}s.
* This method is called each time a {@code ChangeEvent} is received from
* the model.
* <p>
* The event instance is created if necessary, and stored in
* {@code changeEvent}.
*
* @see #addChangeListener
* @see EventListenerList
*/
protected void fireStateChanged() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i]==ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns the {@code BoundedRangeModel} that handles the slider's three
* fundamental properties: minimum, maximum, value.
*
* @return the data model for this component
* @see #setModel
* @see BoundedRangeModel
*/
public BoundedRangeModel getModel() {
return sliderModel;
}
/** {@collect.stats}
* Sets the {@code BoundedRangeModel} that handles the slider's three
* fundamental properties: minimum, maximum, value.
*<p>
* Attempts to pass a {@code null} model to this method result in
* undefined behavior, and, most likely, exceptions.
*
* @param newModel the new, {@code non-null} <code>BoundedRangeModel</code> to use
*
* @see #getModel
* @see BoundedRangeModel
* @beaninfo
* bound: true
* description: The sliders BoundedRangeModel.
*/
public void setModel(BoundedRangeModel newModel)
{
BoundedRangeModel oldModel = getModel();
if (oldModel != null) {
oldModel.removeChangeListener(changeListener);
}
sliderModel = newModel;
if (newModel != null) {
newModel.addChangeListener(changeListener);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
(oldModel == null
? null : new Integer(oldModel.getValue())),
(newModel == null
? null : new Integer(newModel.getValue())));
}
}
firePropertyChange("model", oldModel, sliderModel);
}
/** {@collect.stats}
* Returns the slider's current value
* from the {@code BoundedRangeModel}.
*
* @return the current value of the slider
* @see #setValue
* @see BoundedRangeModel#getValue
*/
public int getValue() {
return getModel().getValue();
}
/** {@collect.stats}
* Sets the slider's current value to {@code n}. This method
* forwards the new value to the model.
* <p>
* The data model (an instance of {@code BoundedRangeModel})
* handles any mathematical
* issues arising from assigning faulty values. See the
* {@code BoundedRangeModel} documentation for details.
* <p>
* If the new value is different from the previous value,
* all change listeners are notified.
*
* @param n the new value
* @see #getValue
* @see #addChangeListener
* @see BoundedRangeModel#setValue
* @beaninfo
* preferred: true
* description: The sliders current value.
*/
public void setValue(int n) {
BoundedRangeModel m = getModel();
int oldValue = m.getValue();
if (oldValue == n) {
return;
}
m.setValue(n);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(oldValue),
new Integer(m.getValue()));
}
}
/** {@collect.stats}
* Returns the minimum value supported by the slider
* from the <code>BoundedRangeModel</code>.
*
* @return the value of the model's minimum property
* @see #setMinimum
* @see BoundedRangeModel#getMinimum
*/
public int getMinimum() {
return getModel().getMinimum();
}
/** {@collect.stats}
* Sets the slider's minimum value to {@code minimum}. This method
* forwards the new minimum value to the model.
* <p>
* The data model (an instance of {@code BoundedRangeModel})
* handles any mathematical
* issues arising from assigning faulty values. See the
* {@code BoundedRangeModel} documentation for details.
* <p>
* If the new minimum value is different from the previous minimum value,
* all change listeners are notified.
*
* @param minimum the new minimum
* @see #getMinimum
* @see #addChangeListener
* @see BoundedRangeModel#setMinimum
* @beaninfo
* bound: true
* preferred: true
* description: The sliders minimum value.
*/
public void setMinimum(int minimum) {
int oldMin = getModel().getMinimum();
getModel().setMinimum(minimum);
firePropertyChange( "minimum", new Integer( oldMin ), new Integer( minimum ) );
}
/** {@collect.stats}
* Returns the maximum value supported by the slider
* from the <code>BoundedRangeModel</code>.
*
* @return the value of the model's maximum property
* @see #setMaximum
* @see BoundedRangeModel#getMaximum
*/
public int getMaximum() {
return getModel().getMaximum();
}
/** {@collect.stats}
* Sets the slider's maximum value to {@code maximum}. This method
* forwards the new maximum value to the model.
* <p>
* The data model (an instance of {@code BoundedRangeModel})
* handles any mathematical
* issues arising from assigning faulty values. See the
* {@code BoundedRangeModel} documentation for details.
* <p>
* If the new maximum value is different from the previous maximum value,
* all change listeners are notified.
*
* @param maximum the new maximum
* @see #getMaximum
* @see #addChangeListener
* @see BoundedRangeModel#setMaximum
* @beaninfo
* bound: true
* preferred: true
* description: The sliders maximum value.
*/
public void setMaximum(int maximum) {
int oldMax = getModel().getMaximum();
getModel().setMaximum(maximum);
firePropertyChange( "maximum", new Integer( oldMax ), new Integer( maximum ) );
}
/** {@collect.stats}
* Returns the {@code valueIsAdjusting} property from the model. For
* details on how this is used, see the {@code setValueIsAdjusting}
* documentation.
*
* @return the value of the model's {@code valueIsAdjusting} property
* @see #setValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return getModel().getValueIsAdjusting();
}
/** {@collect.stats}
* Sets the model's {@code valueIsAdjusting} property. Slider look and
* feel implementations should set this property to {@code true} when
* a knob drag begins, and to {@code false} when the drag ends. The
* slider model will not generate {@code ChangeEvent}s while
* {@code valueIsAdjusting} is {@code true}.
*
* @param b the new value for the {@code valueIsAdjusting} property
* @see #getValueIsAdjusting
* @see BoundedRangeModel#setValueIsAdjusting
* @beaninfo
* expert: true
* description: True if the slider knob is being dragged.
*/
public void setValueIsAdjusting(boolean b) {
BoundedRangeModel m = getModel();
boolean oldValue = m.getValueIsAdjusting();
m.setValueIsAdjusting(b);
if ((oldValue != b) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldValue) ? AccessibleState.BUSY : null),
((b) ? AccessibleState.BUSY : null));
}
}
/** {@collect.stats}
* Returns the "extent" from the <code>BoundedRangeModel</code>.
* This respresents the range of values "covered" by the knob.
*
* @return an int representing the extent
* @see #setExtent
* @see BoundedRangeModel#getExtent
*/
public int getExtent() {
return getModel().getExtent();
}
/** {@collect.stats}
* Sets the size of the range "covered" by the knob. Most look
* and feel implementations will change the value by this amount
* if the user clicks on either side of the knob. This method just
* forwards the new extent value to the model.
* <p>
* The data model (an instance of {@code BoundedRangeModel})
* handles any mathematical
* issues arising from assigning faulty values. See the
* {@code BoundedRangeModel} documentation for details.
* <p>
* If the new extent value is different from the previous extent value,
* all change listeners are notified.
*
* @param extent the new extent
* @see #getExtent
* @see BoundedRangeModel#setExtent
* @beaninfo
* expert: true
* description: Size of the range covered by the knob.
*/
public void setExtent(int extent) {
getModel().setExtent(extent);
}
/** {@collect.stats}
* Return this slider's vertical or horizontal orientation.
* @return {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}
* @see #setOrientation
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* Set the slider's orientation to either {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}.
*
* @param orientation {@code HORIZONTAL} or {@code VERTICAL}
* @throws IllegalArgumentException if orientation is not one of {@code VERTICAL}, {@code HORIZONTAL}
* @see #getOrientation
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: Set the scrollbars orientation to either VERTICAL or HORIZONTAL.
* enum: VERTICAL JSlider.VERTICAL
* HORIZONTAL JSlider.HORIZONTAL
*
*/
public void setOrientation(int orientation)
{
checkOrientation(orientation);
int oldValue = this.orientation;
this.orientation = orientation;
firePropertyChange("orientation", oldValue, orientation);
if ((oldValue != orientation) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldValue == VERTICAL)
? AccessibleState.VERTICAL : AccessibleState.HORIZONTAL),
((orientation == VERTICAL)
? AccessibleState.VERTICAL : AccessibleState.HORIZONTAL));
}
if (orientation != oldValue) {
revalidate();
}
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.6
*/
public void setFont(Font font) {
super.setFont(font);
updateLabelSizes();
}
/** {@collect.stats}
* Returns the dictionary of what labels to draw at which values.
*
* @return the <code>Dictionary</code> containing labels and
* where to draw them
*/
public Dictionary getLabelTable() {
/*
if ( labelTable == null && getMajorTickSpacing() > 0 ) {
setLabelTable( createStandardLabels( getMajorTickSpacing() ) );
}
*/
return labelTable;
}
/** {@collect.stats}
* Used to specify what label will be drawn at any given value.
* The key-value pairs are of this format:
* <code>{ Integer value, java.swing.JComponent label }</code>.
* <p>
* An easy way to generate a standard table of value labels is by using the
* {@code createStandardLabels} method.
* <p>
* Once the labels have been set, this method calls {@link #updateLabelUIs}.
* Note that the labels are only painted if the {@code paintLabels}
* property is {@code true}.
*
* @param labels new {@code Dictionary} of labels, or {@code null} to
* remove all labels
* @see #createStandardLabels(int)
* @see #getLabelTable
* @see #setPaintLabels
* @beaninfo
* hidden: true
* bound: true
* attribute: visualUpdate true
* description: Specifies what labels will be drawn for any given value.
*/
public void setLabelTable( Dictionary labels ) {
Dictionary oldTable = labelTable;
labelTable = labels;
updateLabelUIs();
firePropertyChange("labelTable", oldTable, labelTable );
if (labels != oldTable) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Updates the UIs for the labels in the label table by calling
* {@code updateUI} on each label. The UIs are updated from
* the current look and feel. The labels are also set to their
* preferred size.
*
* @see #setLabelTable
* @see JComponent#updateUI
*/
protected void updateLabelUIs() {
if ( getLabelTable() == null ) {
return;
}
Enumeration labels = getLabelTable().keys();
while ( labels.hasMoreElements() ) {
Object value = getLabelTable().get( labels.nextElement() );
if ( value instanceof JComponent ) {
JComponent component = (JComponent)value;
component.updateUI();
component.setSize( component.getPreferredSize() );
}
}
}
private void updateLabelSizes() {
Dictionary labelTable = getLabelTable();
if (labelTable != null) {
Enumeration labels = labelTable.elements();
while (labels.hasMoreElements()) {
Object value = labels.nextElement();
if (value instanceof JComponent) {
JComponent component = (JComponent)value;
component.setSize(component.getPreferredSize());
}
}
}
}
/** {@collect.stats}
* Creates a {@code Hashtable} of numerical text labels, starting at the
* slider minimum, and using the increment specified.
* For example, if you call <code>createStandardLabels( 10 )</code>
* and the slider minimum is zero,
* then labels will be created for the values 0, 10, 20, 30, and so on.
* <p>
* For the labels to be drawn on the slider, the returned {@code Hashtable}
* must be passed into {@code setLabelTable}, and {@code setPaintLabels}
* must be set to {@code true}.
* <p>
* For further details on the makeup of the returned {@code Hashtable}, see
* the {@code setLabelTable} documentation.
*
* @param increment distance between labels in the generated hashtable
* @return a new {@code Hashtable} of labels
* @see #setLabelTable
* @see #setPaintLabels
* @throws IllegalArgumentException if {@code increment} is less than or
* equal to zero
*/
public Hashtable createStandardLabels( int increment ) {
return createStandardLabels( increment, getMinimum() );
}
/** {@collect.stats}
* Creates a {@code Hashtable} of numerical text labels, starting at the
* starting point specified, and using the increment specified.
* For example, if you call
* <code>createStandardLabels( 10, 2 )</code>,
* then labels will be created for the values 2, 12, 22, 32, and so on.
* <p>
* For the labels to be drawn on the slider, the returned {@code Hashtable}
* must be passed into {@code setLabelTable}, and {@code setPaintLabels}
* must be set to {@code true}.
* <p>
* For further details on the makeup of the returned {@code Hashtable}, see
* the {@code setLabelTable} documentation.
*
* @param increment distance between labels in the generated hashtable
* @param start value at which the labels will begin
* @return a new {@code Hashtable} of labels
* @see #setLabelTable
* @see #setPaintLabels
* @exception IllegalArgumentException if {@code start} is
* out of range, or if {@code increment} is less than or equal
* to zero
*/
public Hashtable createStandardLabels( int increment, int start ) {
if ( start > getMaximum() || start < getMinimum() ) {
throw new IllegalArgumentException( "Slider label start point out of range." );
}
if ( increment <= 0 ) {
throw new IllegalArgumentException( "Label incremement must be > 0" );
}
class SmartHashtable extends Hashtable implements PropertyChangeListener {
int increment = 0;
int start = 0;
boolean startAtMin = false;
class LabelUIResource extends JLabel implements UIResource {
public LabelUIResource( String text, int alignment ) {
super( text, alignment );
setName("Slider.label");
}
public Font getFont() {
Font font = super.getFont();
if (font != null && !(font instanceof UIResource)) {
return font;
}
return JSlider.this.getFont();
}
public Color getForeground() {
Color fg = super.getForeground();
if (fg != null && !(fg instanceof UIResource)) {
return fg;
}
if (!(JSlider.this.getForeground() instanceof UIResource)) {
return JSlider.this.getForeground();
}
return fg;
}
}
public SmartHashtable( int increment, int start ) {
super();
this.increment = increment;
this.start = start;
startAtMin = start == getMinimum();
createLabels();
}
public void propertyChange( PropertyChangeEvent e ) {
if ( e.getPropertyName().equals( "minimum" ) && startAtMin ) {
start = getMinimum();
}
if ( e.getPropertyName().equals( "minimum" ) ||
e.getPropertyName().equals( "maximum" ) ) {
Enumeration keys = getLabelTable().keys();
Object key = null;
Hashtable hashtable = new Hashtable();
// Save the labels that were added by the developer
while ( keys.hasMoreElements() ) {
key = keys.nextElement();
Object value = getLabelTable().get( key );
if ( !(value instanceof LabelUIResource) ) {
hashtable.put( key, value );
}
}
clear();
createLabels();
// Add the saved labels
keys = hashtable.keys();
while ( keys.hasMoreElements() ) {
key = keys.nextElement();
put( key, hashtable.get( key ) );
}
((JSlider)e.getSource()).setLabelTable( this );
}
}
void createLabels() {
for ( int labelIndex = start; labelIndex <= getMaximum(); labelIndex += increment ) {
put( new Integer( labelIndex ), new LabelUIResource( ""+labelIndex, JLabel.CENTER ) );
}
}
}
SmartHashtable table = new SmartHashtable( increment, start );
if ( getLabelTable() != null && (getLabelTable() instanceof PropertyChangeListener) ) {
removePropertyChangeListener( (PropertyChangeListener)getLabelTable() );
}
addPropertyChangeListener( table );
return table;
}
/** {@collect.stats}
* Returns true if the value-range shown for the slider is reversed,
*
* @return true if the slider values are reversed from their normal order
* @see #setInverted
*/
public boolean getInverted() {
return isInverted;
}
/** {@collect.stats}
* Specify true to reverse the value-range shown for the slider and false to
* put the value range in the normal order. The order depends on the
* slider's <code>ComponentOrientation</code> property. Normal (non-inverted)
* horizontal sliders with a <code>ComponentOrientation</code> value of
* <code>LEFT_TO_RIGHT</code> have their maximum on the right.
* Normal horizontal sliders with a <code>ComponentOrientation</code> value of
* <code>RIGHT_TO_LEFT</code> have their maximum on the left. Normal vertical
* sliders have their maximum on the top. These labels are reversed when the
* slider is inverted.
* <p>
* By default, the value of this property is {@code false}.
*
* @param b true to reverse the slider values from their normal order
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true reverses the slider values from their normal order
*
*/
public void setInverted( boolean b ) {
boolean oldValue = isInverted;
isInverted = b;
firePropertyChange("inverted", oldValue, isInverted);
if (b != oldValue) {
repaint();
}
}
/** {@collect.stats}
* This method returns the major tick spacing. The number that is returned
* represents the distance, measured in values, between each major tick mark.
* If you have a slider with a range from 0 to 50 and the major tick spacing
* is set to 10, you will get major ticks next to the following values:
* 0, 10, 20, 30, 40, 50.
*
* @return the number of values between major ticks
* @see #setMajorTickSpacing
*/
public int getMajorTickSpacing() {
return majorTickSpacing;
}
/** {@collect.stats}
* This method sets the major tick spacing. The number that is passed in
* represents the distance, measured in values, between each major tick mark.
* If you have a slider with a range from 0 to 50 and the major tick spacing
* is set to 10, you will get major ticks next to the following values:
* 0, 10, 20, 30, 40, 50.
* <p>
* In order for major ticks to be painted, {@code setPaintTicks} must be
* set to {@code true}.
* <p>
* This method will also set up a label table for you.
* If there is not already a label table, and the major tick spacing is
* {@code > 0}, and {@code getPaintLabels} returns
* {@code true}, a standard label table will be generated (by calling
* {@code createStandardLabels}) with labels at the major tick marks.
* For the example above, you would get text labels: "0",
* "10", "20", "30", "40", "50".
* The label table is then set on the slider by calling
* {@code setLabelTable}.
*
* @param n new value for the {@code majorTickSpacing} property
* @see #getMajorTickSpacing
* @see #setPaintTicks
* @see #setLabelTable
* @see #createStandardLabels(int)
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Sets the number of values between major tick marks.
*
*/
public void setMajorTickSpacing(int n) {
int oldValue = majorTickSpacing;
majorTickSpacing = n;
if ( labelTable == null && getMajorTickSpacing() > 0 && getPaintLabels() ) {
setLabelTable( createStandardLabels( getMajorTickSpacing() ) );
}
firePropertyChange("majorTickSpacing", oldValue, majorTickSpacing);
if (majorTickSpacing != oldValue && getPaintTicks()) {
repaint();
}
}
/** {@collect.stats}
* This method returns the minor tick spacing. The number that is returned
* represents the distance, measured in values, between each minor tick mark.
* If you have a slider with a range from 0 to 50 and the minor tick spacing
* is set to 10, you will get minor ticks next to the following values:
* 0, 10, 20, 30, 40, 50.
*
* @return the number of values between minor ticks
* @see #getMinorTickSpacing
*/
public int getMinorTickSpacing() {
return minorTickSpacing;
}
/** {@collect.stats}
* This method sets the minor tick spacing. The number that is passed in
* represents the distance, measured in values, between each minor tick mark.
* If you have a slider with a range from 0 to 50 and the minor tick spacing
* is set to 10, you will get minor ticks next to the following values:
* 0, 10, 20, 30, 40, 50.
* <p>
* In order for minor ticks to be painted, {@code setPaintTicks} must be
* set to {@code true}.
*
* @param n new value for the {@code minorTickSpacing} property
* @see #getMinorTickSpacing
* @see #setPaintTicks
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Sets the number of values between minor tick marks.
*/
public void setMinorTickSpacing(int n) {
int oldValue = minorTickSpacing;
minorTickSpacing = n;
firePropertyChange("minorTickSpacing", oldValue, minorTickSpacing);
if (minorTickSpacing != oldValue && getPaintTicks()) {
repaint();
}
}
/** {@collect.stats}
* Returns true if the knob (and the data value it represents)
* resolve to the closest tick mark next to where the user
* positioned the knob.
*
* @return true if the value snaps to the nearest tick mark, else false
* @see #setSnapToTicks
*/
public boolean getSnapToTicks() {
return snapToTicks;
}
/** {@collect.stats}
* Returns true if the knob (and the data value it represents)
* resolve to the closest slider value next to where the user
* positioned the knob.
*
* @return true if the value snaps to the nearest slider value, else false
* @see #setSnapToValue
*/
boolean getSnapToValue() {
return snapToValue;
}
/** {@collect.stats}
* Specifying true makes the knob (and the data value it represents)
* resolve to the closest tick mark next to where the user
* positioned the knob.
* By default, this property is {@code false}.
*
* @param b true to snap the knob to the nearest tick mark
* @see #getSnapToTicks
* @beaninfo
* bound: true
* description: If true snap the knob to the nearest tick mark.
*/
public void setSnapToTicks(boolean b) {
boolean oldValue = snapToTicks;
snapToTicks = b;
firePropertyChange("snapToTicks", oldValue, snapToTicks);
}
/** {@collect.stats}
* Specifying true makes the knob (and the data value it represents)
* resolve to the closest slider value next to where the user
* positioned the knob. If the {@code snapToTicks} property has also been
* set to {@code true}, the snap-to-ticks behavior will prevail.
* By default, the snapToValue property is {@code true}.
*
* @param b true to snap the knob to the nearest slider value
* @see #getSnapToValue
* @see #setSnapToTicks
* @beaninfo
* bound: true
* description: If true snap the knob to the nearest slider value.
*/
void setSnapToValue(boolean b) {
boolean oldValue = snapToValue;
snapToValue = b;
firePropertyChange("snapToValue", oldValue, snapToValue);
}
/** {@collect.stats}
* Tells if tick marks are to be painted.
* @return true if tick marks are painted, else false
* @see #setPaintTicks
*/
public boolean getPaintTicks() {
return paintTicks;
}
/** {@collect.stats}
* Determines whether tick marks are painted on the slider.
* By default, this property is {@code false}.
*
* @param b whether or not tick marks should be painted
* @see #getPaintTicks
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true tick marks are painted on the slider.
*/
public void setPaintTicks(boolean b) {
boolean oldValue = paintTicks;
paintTicks = b;
firePropertyChange("paintTicks", oldValue, paintTicks);
if (paintTicks != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Tells if the track (area the slider slides in) is to be painted.
* @return true if track is painted, else false
* @see #setPaintTrack
*/
public boolean getPaintTrack() {
return paintTrack;
}
/** {@collect.stats}
* Determines whether the track is painted on the slider.
* By default, this property is {@code true}.
*
* @param b whether or not to paint the slider track
* @see #getPaintTrack
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true, the track is painted on the slider.
*/
public void setPaintTrack(boolean b) {
boolean oldValue = paintTrack;
paintTrack = b;
firePropertyChange("paintTrack", oldValue, paintTrack);
if (paintTrack != oldValue) {
repaint();
}
}
/** {@collect.stats}
* Tells if labels are to be painted.
* @return true if labels are painted, else false
* @see #setPaintLabels
*/
public boolean getPaintLabels() {
return paintLabels;
}
/** {@collect.stats}
* Determines whether labels are painted on the slider.
* <p>
* This method will also set up a label table for you.
* If there is not already a label table, and the major tick spacing is
* {@code > 0},
* a standard label table will be generated (by calling
* {@code createStandardLabels}) with labels at the major tick marks.
* The label table is then set on the slider by calling
* {@code setLabelTable}.
* <p>
* By default, this property is {@code false}.
*
* @param b whether or not to paint labels
* @see #getPaintLabels
* @see #getLabelTable
* @see #createStandardLabels(int)
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true labels are painted on the slider.
*/
public void setPaintLabels(boolean b) {
boolean oldValue = paintLabels;
paintLabels = b;
if ( labelTable == null && getMajorTickSpacing() > 0 ) {
setLabelTable( createStandardLabels( getMajorTickSpacing() ) );
}
firePropertyChange("paintLabels", oldValue, paintLabels);
if (paintLabels != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this JSlider. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JSlider.
*/
protected String paramString() {
String paintTicksString = (paintTicks ?
"true" : "false");
String paintTrackString = (paintTrack ?
"true" : "false");
String paintLabelsString = (paintLabels ?
"true" : "false");
String isInvertedString = (isInverted ?
"true" : "false");
String snapToTicksString = (snapToTicks ?
"true" : "false");
String snapToValueString = (snapToValue ?
"true" : "false");
String orientationString = (orientation == HORIZONTAL ?
"HORIZONTAL" : "VERTICAL");
return super.paramString() +
",isInverted=" + isInvertedString +
",majorTickSpacing=" + majorTickSpacing +
",minorTickSpacing=" + minorTickSpacing +
",orientation=" + orientationString +
",paintLabels=" + paintLabelsString +
",paintTicks=" + paintTicksString +
",paintTrack=" + paintTrackString +
",snapToTicks=" + snapToTicksString +
",snapToValue=" + snapToValueString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JSlider.
* For sliders, the AccessibleContext takes the form of an
* AccessibleJSlider.
* A new AccessibleJSlider instance is created if necessary.
*
* @return an AccessibleJSlider that serves as the
* AccessibleContext of this JSlider
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJSlider();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JSlider</code> class. It provides an implementation of the
* Java Accessibility API appropriate to slider user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJSlider extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getValueIsAdjusting()) {
states.add(AccessibleState.BUSY);
}
if (getOrientation() == VERTICAL) {
states.add(AccessibleState.VERTICAL);
}
else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SLIDER;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Get the accessible value of this object.
*
* @return The current value of this object.
*/
public Number getCurrentAccessibleValue() {
return new Integer(getValue());
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
setValue(n.intValue());
return true;
}
/** {@collect.stats}
* Get the minimum accessible value of this object.
*
* @return The minimum value of this object.
*/
public Number getMinimumAccessibleValue() {
return new Integer(getMinimum());
}
/** {@collect.stats}
* Get the maximum accessible value of this object.
*
* @return The maximum value of this object.
*/
public Number getMaximumAccessibleValue() {
// TIGER - 4422362
BoundedRangeModel model = JSlider.this.getModel();
return new Integer(model.getMaximum() - model.getExtent());
}
} // AccessibleJSlider
}
|
Java
|
/*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.beans.*;
import java.lang.reflect.*;
import java.io.*;
import java.util.TooManyListenersException;
import javax.swing.plaf.UIResource;
import javax.swing.event.*;
import javax.swing.text.JTextComponent;
import sun.reflect.misc.MethodUtil;
import sun.swing.SwingUtilities2;
import sun.awt.AppContext;
import sun.swing.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.AccessControlContext;
import java.security.ProtectionDomain;
import sun.misc.SharedSecrets;
import sun.misc.JavaSecurityAccess;
import sun.awt.AWTAccessor;
/** {@collect.stats}
* This class is used to handle the transfer of a <code>Transferable</code>
* to and from Swing components. The <code>Transferable</code> is used to
* represent data that is exchanged via a cut, copy, or paste
* to/from a clipboard. It is also used in drag-and-drop operations
* to represent a drag from a component, and a drop to a component.
* Swing provides functionality that automatically supports cut, copy,
* and paste keyboard bindings that use the functionality provided by
* an implementation of this class. Swing also provides functionality
* that automatically supports drag and drop that uses the functionality
* provided by an implementation of this class. The Swing developer can
* concentrate on specifying the semantics of a transfer primarily by setting
* the <code>transferHandler</code> property on a Swing component.
* <p>
* This class is implemented to provide a default behavior of transferring
* a component property simply by specifying the name of the property in
* the constructor. For example, to transfer the foreground color from
* one component to another either via the clipboard or a drag and drop operation
* a <code>TransferHandler</code> can be constructed with the string "foreground". The
* built in support will use the color returned by <code>getForeground</code> as the source
* of the transfer, and <code>setForeground</code> for the target of a transfer.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>,
* a section in <em>The Java Tutorial</em>, for more information.
*
*
* @author Timothy Prinzing
* @author Shannon Hickey
* @since 1.4
*/
@SuppressWarnings("serial")
public class TransferHandler implements Serializable {
/** {@collect.stats}
* An <code>int</code> representing no transfer action.
*/
public static final int NONE = DnDConstants.ACTION_NONE;
/** {@collect.stats}
* An <code>int</code> representing a "copy" transfer action.
* This value is used when data is copied to a clipboard
* or copied elsewhere in a drag and drop operation.
*/
public static final int COPY = DnDConstants.ACTION_COPY;
/** {@collect.stats}
* An <code>int</code> representing a "move" transfer action.
* This value is used when data is moved to a clipboard (i.e. a cut)
* or moved elsewhere in a drag and drop operation.
*/
public static final int MOVE = DnDConstants.ACTION_MOVE;
/** {@collect.stats}
* An <code>int</code> representing a source action capability of either
* "copy" or "move".
*/
public static final int COPY_OR_MOVE = DnDConstants.ACTION_COPY_OR_MOVE;
/** {@collect.stats}
* An <code>int</code> representing a "link" transfer action.
* This value is used to specify that data should be linked in a drag
* and drop operation.
*
* @see java.awt.dnd.DnDConstants#ACTION_LINK
* @since 1.6
*/
public static final int LINK = DnDConstants.ACTION_LINK;
/** {@collect.stats}
* An interface to tag things with a {@code getTransferHandler} method.
*/
interface HasGetTransferHandler {
/** {@collect.stats} Returns the {@code TransferHandler}.
*
* @return The {@code TransferHandler} or {@code null}
*/
public TransferHandler getTransferHandler();
}
/** {@collect.stats}
* Represents a location where dropped data should be inserted.
* This is a base class that only encapsulates a point.
* Components supporting drop may provide subclasses of this
* containing more information.
* <p>
* Developers typically shouldn't create instances of, or extend, this
* class. Instead, these are something provided by the DnD
* implementation by <code>TransferSupport</code> instances and by
* components with a <code>getDropLocation()</code> method.
*
* @see javax.swing.TransferHandler.TransferSupport#getDropLocation
* @since 1.6
*/
public static class DropLocation {
private final Point dropPoint;
/** {@collect.stats}
* Constructs a drop location for the given point.
*
* @param dropPoint the drop point, representing the mouse's
* current location within the component.
* @throws IllegalArgumentException if the point
* is <code>null</code>
*/
protected DropLocation(Point dropPoint) {
if (dropPoint == null) {
throw new IllegalArgumentException("Point cannot be null");
}
this.dropPoint = new Point(dropPoint);
}
/** {@collect.stats}
* Returns the drop point, representing the mouse's
* current location within the component.
*
* @return the drop point.
*/
public final Point getDropPoint() {
return new Point(dropPoint);
}
/** {@collect.stats}
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName() + "[dropPoint=" + dropPoint + "]";
}
};
/** {@collect.stats}
* This class encapsulates all relevant details of a clipboard
* or drag and drop transfer, and also allows for customizing
* aspects of the drag and drop experience.
* <p>
* The main purpose of this class is to provide the information
* needed by a developer to determine the suitability of a
* transfer or to import the data contained within. But it also
* doubles as a controller for customizing properties during drag
* and drop, such as whether or not to show the drop location,
* and which drop action to use.
* <p>
* Developers typically need not create instances of this
* class. Instead, they are something provided by the DnD
* implementation to certain methods in <code>TransferHandler</code>.
*
* @see #canImport(TransferHandler.TransferSupport)
* @see #importData(TransferHandler.TransferSupport)
* @since 1.6
*/
public final static class TransferSupport {
private boolean isDrop;
private Component component;
private boolean showDropLocationIsSet;
private boolean showDropLocation;
private int dropAction = -1;
/** {@collect.stats}
* The source is a {@code DropTargetDragEvent} or
* {@code DropTargetDropEvent} for drops,
* and a {@code Transferable} otherwise
*/
private Object source;
private DropLocation dropLocation;
/** {@collect.stats}
* Create a <code>TransferSupport</code> with <code>isDrop()</code>
* <code>true</code> for the given component, event, and index.
*
* @param component the target component
* @param event a <code>DropTargetEvent</code>
*/
private TransferSupport(Component component,
DropTargetEvent event) {
isDrop = true;
setDNDVariables(component, event);
}
/** {@collect.stats}
* Create a <code>TransferSupport</code> with <code>isDrop()</code>
* <code>false</code> for the given component and
* <code>Transferable</code>.
*
* @param component the target component
* @param transferable the transferable
* @throws NullPointerException if either parameter
* is <code>null</code>
*/
public TransferSupport(Component component, Transferable transferable) {
if (component == null) {
throw new NullPointerException("component is null");
}
if (transferable == null) {
throw new NullPointerException("transferable is null");
}
isDrop = false;
this.component = component;
this.source = transferable;
}
/** {@collect.stats}
* Allows for a single instance to be reused during DnD.
*
* @param component the target component
* @param event a <code>DropTargetEvent</code>
*/
private void setDNDVariables(Component component,
DropTargetEvent event) {
assert isDrop;
this.component = component;
this.source = event;
dropLocation = null;
dropAction = -1;
showDropLocationIsSet = false;
if (source == null) {
return;
}
assert source instanceof DropTargetDragEvent ||
source instanceof DropTargetDropEvent;
Point p = source instanceof DropTargetDragEvent
? ((DropTargetDragEvent)source).getLocation()
: ((DropTargetDropEvent)source).getLocation();
if (component instanceof JTextComponent) {
try {
AccessibleMethod method
= new AccessibleMethod(JTextComponent.class,
"dropLocationForPoint",
Point.class);
dropLocation =
(DropLocation)method.invokeNoChecked(component, p);
} catch (NoSuchMethodException e) {
throw new AssertionError(
"Couldn't locate method JTextComponent.dropLocationForPoint");
}
} else if (component instanceof JComponent) {
dropLocation = ((JComponent)component).dropLocationForPoint(p);
}
/*
* The drop location may be null at this point if the component
* doesn't return custom drop locations. In this case, a point-only
* drop location will be created lazily when requested.
*/
}
/** {@collect.stats}
* Returns whether or not this <code>TransferSupport</code>
* represents a drop operation.
*
* @return <code>true</code> if this is a drop operation,
* <code>false</code> otherwise.
*/
public boolean isDrop() {
return isDrop;
}
/** {@collect.stats}
* Returns the target component of this transfer.
*
* @return the target component
*/
public Component getComponent() {
return component;
}
/** {@collect.stats}
* Checks that this is a drop and throws an
* {@code IllegalStateException} if it isn't.
*
* @throws IllegalStateException if {@code isDrop} is false.
*/
private void assureIsDrop() {
if (!isDrop) {
throw new IllegalStateException("Not a drop");
}
}
/** {@collect.stats}
* Returns the current (non-{@code null}) drop location for the component,
* when this {@code TransferSupport} represents a drop.
* <p>
* Note: For components with built-in drop support, this location
* will be a subclass of {@code DropLocation} of the same type
* returned by that component's {@code getDropLocation} method.
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @return the drop location
* @throws IllegalStateException if this is not a drop
* @see #isDrop
*/
public DropLocation getDropLocation() {
assureIsDrop();
if (dropLocation == null) {
/*
* component didn't give us a custom drop location,
* so lazily create a point-only location
*/
Point p = source instanceof DropTargetDragEvent
? ((DropTargetDragEvent)source).getLocation()
: ((DropTargetDropEvent)source).getLocation();
dropLocation = new DropLocation(p);
}
return dropLocation;
}
/** {@collect.stats}
* Sets whether or not the drop location should be visually indicated
* for the transfer - which must represent a drop. This is applicable to
* those components that automatically
* show the drop location when appropriate during a drag and drop
* operation). By default, the drop location is shown only when the
* {@code TransferHandler} has said it can accept the import represented
* by this {@code TransferSupport}. With this method you can force the
* drop location to always be shown, or always not be shown.
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @param showDropLocation whether or not to indicate the drop location
* @throws IllegalStateException if this is not a drop
* @see #isDrop
*/
public void setShowDropLocation(boolean showDropLocation) {
assureIsDrop();
this.showDropLocation = showDropLocation;
this.showDropLocationIsSet = true;
}
/** {@collect.stats}
* Sets the drop action for the transfer - which must represent a drop
* - to the given action,
* instead of the default user drop action. The action must be
* supported by the source's drop actions, and must be one
* of {@code COPY}, {@code MOVE} or {@code LINK}.
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @param dropAction the drop action
* @throws IllegalStateException if this is not a drop
* @throws IllegalArgumentException if an invalid action is specified
* @see #getDropAction
* @see #getUserDropAction
* @see #getSourceDropActions
* @see #isDrop
*/
public void setDropAction(int dropAction) {
assureIsDrop();
int action = dropAction & getSourceDropActions();
if (!(action == COPY || action == MOVE || action == LINK)) {
throw new IllegalArgumentException("unsupported drop action: " + dropAction);
}
this.dropAction = dropAction;
}
/** {@collect.stats}
* Returns the action chosen for the drop, when this
* {@code TransferSupport} represents a drop.
* <p>
* Unless explicitly chosen by way of {@code setDropAction},
* this returns the user drop action provided by
* {@code getUserDropAction}.
* <p>
* You may wish to query this in {@code TransferHandler}'s
* {@code importData} method to customize processing based
* on the action.
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @return the action chosen for the drop
* @throws IllegalStateException if this is not a drop
* @see #setDropAction
* @see #getUserDropAction
* @see #isDrop
*/
public int getDropAction() {
return dropAction == -1 ? getUserDropAction() : dropAction;
}
/** {@collect.stats}
* Returns the user drop action for the drop, when this
* {@code TransferSupport} represents a drop.
* <p>
* The user drop action is chosen for a drop as described in the
* documentation for {@link java.awt.dnd.DropTargetDragEvent} and
* {@link java.awt.dnd.DropTargetDropEvent}. A different action
* may be chosen as the drop action by way of the {@code setDropAction}
* method.
* <p>
* You may wish to query this in {@code TransferHandler}'s
* {@code canImport} method when determining the suitability of a
* drop or when deciding on a drop action to explicitly choose.
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @return the user drop action
* @throws IllegalStateException if this is not a drop
* @see #setDropAction
* @see #getDropAction
* @see #isDrop
*/
public int getUserDropAction() {
assureIsDrop();
return (source instanceof DropTargetDragEvent)
? ((DropTargetDragEvent)source).getDropAction()
: ((DropTargetDropEvent)source).getDropAction();
}
/** {@collect.stats}
* Returns the drag source's supported drop actions, when this
* {@code TransferSupport} represents a drop.
* <p>
* The source actions represent the set of actions supported by the
* source of this transfer, and are represented as some bitwise-OR
* combination of {@code COPY}, {@code MOVE} and {@code LINK}.
* You may wish to query this in {@code TransferHandler}'s
* {@code canImport} method when determining the suitability of a drop
* or when deciding on a drop action to explicitly choose. To determine
* if a particular action is supported by the source, bitwise-AND
* the action with the source drop actions, and then compare the result
* against the original action. For example:
* <pre>
* boolean copySupported = (COPY & getSourceDropActions()) == COPY;
* </pre>
* <p>
* This method is only for use with drag and drop transfers.
* Calling it when {@code isDrop()} is {@code false} results
* in an {@code IllegalStateException}.
*
* @return the drag source's supported drop actions
* @throws IllegalStateException if this is not a drop
* @see #isDrop
*/
public int getSourceDropActions() {
assureIsDrop();
return (source instanceof DropTargetDragEvent)
? ((DropTargetDragEvent)source).getSourceActions()
: ((DropTargetDropEvent)source).getSourceActions();
}
/** {@collect.stats}
* Returns the data flavors for this transfer.
*
* @return the data flavors for this transfer
*/
public DataFlavor[] getDataFlavors() {
if (isDrop) {
if (source instanceof DropTargetDragEvent) {
return ((DropTargetDragEvent)source).getCurrentDataFlavors();
} else {
return ((DropTargetDropEvent)source).getCurrentDataFlavors();
}
}
return ((Transferable)source).getTransferDataFlavors();
}
/** {@collect.stats}
* Returns whether or not the given data flavor is supported.
*
* @param df the <code>DataFlavor</code> to test
* @return whether or not the given flavor is supported.
*/
public boolean isDataFlavorSupported(DataFlavor df) {
if (isDrop) {
if (source instanceof DropTargetDragEvent) {
return ((DropTargetDragEvent)source).isDataFlavorSupported(df);
} else {
return ((DropTargetDropEvent)source).isDataFlavorSupported(df);
}
}
return ((Transferable)source).isDataFlavorSupported(df);
}
/** {@collect.stats}
* Returns the <code>Transferable</code> associated with this transfer.
* <p>
* Note: Unless it is necessary to fetch the <code>Transferable</code>
* directly, use one of the other methods on this class to inquire about
* the transfer. This may perform better than fetching the
* <code>Transferable</code> and asking it directly.
*
* @return the <code>Transferable</code> associated with this transfer
*/
public Transferable getTransferable() {
if (isDrop) {
if (source instanceof DropTargetDragEvent) {
return ((DropTargetDragEvent)source).getTransferable();
} else {
return ((DropTargetDropEvent)source).getTransferable();
}
}
return (Transferable)source;
}
}
/** {@collect.stats}
* Returns an {@code Action} that performs cut operations to the
* clipboard. When performed, this action operates on the {@code JComponent}
* source of the {@code ActionEvent} by invoking {@code exportToClipboard},
* with a {@code MOVE} action, on the component's {@code TransferHandler}.
*
* @return an {@code Action} for performing cuts to the clipboard
*/
public static Action getCutAction() {
return cutAction;
}
/** {@collect.stats}
* Returns an {@code Action} that performs copy operations to the
* clipboard. When performed, this action operates on the {@code JComponent}
* source of the {@code ActionEvent} by invoking {@code exportToClipboard},
* with a {@code COPY} action, on the component's {@code TransferHandler}.
*
* @return an {@code Action} for performing copies to the clipboard
*/
public static Action getCopyAction() {
return copyAction;
}
/** {@collect.stats}
* Returns an {@code Action} that performs paste operations from the
* clipboard. When performed, this action operates on the {@code JComponent}
* source of the {@code ActionEvent} by invoking {@code importData},
* with the clipboard contents, on the component's {@code TransferHandler}.
*
* @return an {@code Action} for performing pastes from the clipboard
*/
public static Action getPasteAction() {
return pasteAction;
}
/** {@collect.stats}
* Constructs a transfer handler that can transfer a Java Bean property
* from one component to another via the clipboard or a drag and drop
* operation.
*
* @param property the name of the property to transfer; this can
* be <code>null</code> if there is no property associated with the transfer
* handler (a subclass that performs some other kind of transfer, for example)
*/
public TransferHandler(String property) {
propertyName = property;
}
/** {@collect.stats}
* Convenience constructor for subclasses.
*/
protected TransferHandler() {
this(null);
}
/** {@collect.stats}
* Causes the Swing drag support to be initiated. This is called by
* the various UI implementations in the <code>javax.swing.plaf.basic</code>
* package if the dragEnabled property is set on the component.
* This can be called by custom UI
* implementations to use the Swing drag support. This method can also be called
* by a Swing extension written as a subclass of <code>JComponent</code>
* to take advantage of the Swing drag support.
* <p>
* The transfer <em>will not necessarily</em> have been completed at the
* return of this call (i.e. the call does not block waiting for the drop).
* The transfer will take place through the Swing implementation of the
* <code>java.awt.dnd</code> mechanism, requiring no further effort
* from the developer. The <code>exportDone</code> method will be called
* when the transfer has completed.
*
* @param comp the component holding the data to be transferred;
* provided to enable sharing of <code>TransferHandler</code>s
* @param e the event that triggered the transfer
* @param action the transfer action initially requested;
* either {@code COPY}, {@code MOVE} or {@code LINK};
* the DnD system may change the action used during the
* course of the drag operation
*/
public void exportAsDrag(JComponent comp, InputEvent e, int action) {
int srcActions = getSourceActions(comp);
// only mouse events supported for drag operations
if (!(e instanceof MouseEvent)
// only support known actions
|| !(action == COPY || action == MOVE || action == LINK)
// only support valid source actions
|| (srcActions & action) == 0) {
action = NONE;
}
if (action != NONE && !GraphicsEnvironment.isHeadless()) {
if (recognizer == null) {
recognizer = new SwingDragGestureRecognizer(new DragHandler());
}
recognizer.gestured(comp, (MouseEvent)e, srcActions, action);
} else {
exportDone(comp, null, NONE);
}
}
/** {@collect.stats}
* Causes a transfer from the given component to the
* given clipboard. This method is called by the default cut and
* copy actions registered in a component's action map.
* <p>
* The transfer will take place using the <code>java.awt.datatransfer</code>
* mechanism, requiring no further effort from the developer. Any data
* transfer <em>will</em> be complete and the <code>exportDone</code>
* method will be called with the action that occurred, before this method
* returns. Should the clipboard be unavailable when attempting to place
* data on it, the <code>IllegalStateException</code> thrown by
* {@link Clipboard#setContents(Transferable, ClipboardOwner)} will
* be propogated through this method. However,
* <code>exportDone</code> will first be called with an action
* of <code>NONE</code> for consistency.
*
* @param comp the component holding the data to be transferred;
* provided to enable sharing of <code>TransferHandler</code>s
* @param clip the clipboard to transfer the data into
* @param action the transfer action requested; this should
* be a value of either <code>COPY</code> or <code>MOVE</code>;
* the operation performed is the intersection of the transfer
* capabilities given by getSourceActions and the requested action;
* the intersection may result in an action of <code>NONE</code>
* if the requested action isn't supported
* @throws IllegalStateException if the clipboard is currently unavailable
* @see Clipboard#setContents(Transferable, ClipboardOwner)
*/
public void exportToClipboard(JComponent comp, Clipboard clip, int action)
throws IllegalStateException {
if ((action == COPY || action == MOVE)
&& (getSourceActions(comp) & action) != 0) {
Transferable t = createTransferable(comp);
if (t != null) {
try {
clip.setContents(t, null);
exportDone(comp, t, action);
return;
} catch (IllegalStateException ise) {
exportDone(comp, t, NONE);
throw ise;
}
}
}
exportDone(comp, null, NONE);
}
/** {@collect.stats}
* Causes a transfer to occur from a clipboard or a drag and
* drop operation. The <code>Transferable</code> to be
* imported and the component to transfer to are contained
* within the <code>TransferSupport</code>.
* <p>
* While the drag and drop implementation calls {@code canImport}
* to determine the suitability of a transfer before calling this
* method, the implementation of paste does not. As such, it cannot
* be assumed that the transfer is acceptable upon a call to
* this method for paste. It is recommended that {@code canImport} be
* explicitly called to cover this case.
* <p>
* Note: The <code>TransferSupport</code> object passed to this method
* is only valid for the duration of the method call. It is undefined
* what values it may contain after this method returns.
*
* @param support the object containing the details of
* the transfer, not <code>null</code>.
* @return true if the data was inserted into the component,
* false otherwise
* @throws NullPointerException if <code>support</code> is {@code null}
* @see #canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public boolean importData(TransferSupport support) {
return support.getComponent() instanceof JComponent
? importData((JComponent)support.getComponent(), support.getTransferable())
: false;
}
/** {@collect.stats}
* Causes a transfer to a component from a clipboard or a
* DND drop operation. The <code>Transferable</code> represents
* the data to be imported into the component.
* <p>
* Note: Swing now calls the newer version of <code>importData</code>
* that takes a <code>TransferSupport</code>, which in turn calls this
* method (if the component in the {@code TransferSupport} is a
* {@code JComponent}). Developers are encouraged to call and override the
* newer version as it provides more information (and is the only
* version that supports use with a {@code TransferHandler} set directly
* on a {@code JFrame} or other non-{@code JComponent}).
*
* @param comp the component to receive the transfer;
* provided to enable sharing of <code>TransferHandler</code>s
* @param t the data to import
* @return true if the data was inserted into the component, false otherwise
* @see #importData(TransferHandler.TransferSupport)
*/
public boolean importData(JComponent comp, Transferable t) {
PropertyDescriptor prop = getPropertyDescriptor(comp);
if (prop != null) {
Method writer = prop.getWriteMethod();
if (writer == null) {
// read-only property. ignore
return false;
}
Class<?>[] params = writer.getParameterTypes();
if (params.length != 1) {
// zero or more than one argument, ignore
return false;
}
DataFlavor flavor = getPropertyDataFlavor(params[0], t.getTransferDataFlavors());
if (flavor != null) {
try {
Object value = t.getTransferData(flavor);
Object[] args = { value };
MethodUtil.invoke(writer, comp, args);
return true;
} catch (Exception ex) {
System.err.println("Invocation failed");
// invocation code
}
}
}
return false;
}
/** {@collect.stats}
* This method is called repeatedly during a drag and drop operation
* to allow the developer to configure properties of, and to return
* the acceptability of transfers; with a return value of {@code true}
* indicating that the transfer represented by the given
* {@code TransferSupport} (which contains all of the details of the
* transfer) is acceptable at the current time, and a value of {@code false}
* rejecting the transfer.
* <p>
* For those components that automatically display a drop location during
* drag and drop, accepting the transfer, by default, tells them to show
* the drop location. This can be changed by calling
* {@code setShowDropLocation} on the {@code TransferSupport}.
* <p>
* By default, when the transfer is accepted, the chosen drop action is that
* picked by the user via their drag gesture. The developer can override
* this and choose a different action, from the supported source
* actions, by calling {@code setDropAction} on the {@code TransferSupport}.
* <p>
* On every call to {@code canImport}, the {@code TransferSupport} contains
* fresh state. As such, any properties set on it must be set on every
* call. Upon a drop, {@code canImport} is called one final time before
* calling into {@code importData}. Any state set on the
* {@code TransferSupport} during that last call will be available in
* {@code importData}.
* <p>
* This method is not called internally in response to paste operations.
* As such, it is recommended that implementations of {@code importData}
* explicitly call this method for such cases and that this method
* be prepared to return the suitability of paste operations as well.
* <p>
* Note: The <code>TransferSupport</code> object passed to this method
* is only valid for the duration of the method call. It is undefined
* what values it may contain after this method returns.
*
* @param support the object containing the details of
* the transfer, not <code>null</code>.
* @return <code>true</code> if the import can happen,
* <code>false</code> otherwise
* @throws NullPointerException if <code>support</code> is {@code null}
* @see #importData(TransferHandler.TransferSupport)
* @see javax.swing.TransferHandler.TransferSupport#setShowDropLocation
* @see javax.swing.TransferHandler.TransferSupport#setDropAction
* @since 1.6
*/
public boolean canImport(TransferSupport support) {
return support.getComponent() instanceof JComponent
? canImport((JComponent)support.getComponent(), support.getDataFlavors())
: false;
}
/** {@collect.stats}
* Indicates whether a component will accept an import of the given
* set of data flavors prior to actually attempting to import it.
* <p>
* Note: Swing now calls the newer version of <code>canImport</code>
* that takes a <code>TransferSupport</code>, which in turn calls this
* method (only if the component in the {@code TransferSupport} is a
* {@code JComponent}). Developers are encouraged to call and override the
* newer version as it provides more information (and is the only
* version that supports use with a {@code TransferHandler} set directly
* on a {@code JFrame} or other non-{@code JComponent}).
*
* @param comp the component to receive the transfer;
* provided to enable sharing of <code>TransferHandler</code>s
* @param transferFlavors the data formats available
* @return true if the data can be inserted into the component, false otherwise
* @see #canImport(TransferHandler.TransferSupport)
*/
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
PropertyDescriptor prop = getPropertyDescriptor(comp);
if (prop != null) {
Method writer = prop.getWriteMethod();
if (writer == null) {
// read-only property. ignore
return false;
}
Class<?>[] params = writer.getParameterTypes();
if (params.length != 1) {
// zero or more than one argument, ignore
return false;
}
DataFlavor flavor = getPropertyDataFlavor(params[0], transferFlavors);
if (flavor != null) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns the type of transfer actions supported by the source;
* any bitwise-OR combination of {@code COPY}, {@code MOVE}
* and {@code LINK}.
* <p>
* Some models are not mutable, so a transfer operation of {@code MOVE}
* should not be advertised in that case. Returning {@code NONE}
* disables transfers from the component.
*
* @param c the component holding the data to be transferred;
* provided to enable sharing of <code>TransferHandler</code>s
* @return {@code COPY} if the transfer property can be found,
* otherwise returns <code>NONE</code>
*/
public int getSourceActions(JComponent c) {
PropertyDescriptor prop = getPropertyDescriptor(c);
if (prop != null) {
return COPY;
}
return NONE;
}
/** {@collect.stats}
* Returns an object that establishes the look of a transfer. This is
* useful for both providing feedback while performing a drag operation and for
* representing the transfer in a clipboard implementation that has a visual
* appearance. The implementation of the <code>Icon</code> interface should
* not alter the graphics clip or alpha level.
* The icon implementation need not be rectangular or paint all of the
* bounding rectangle and logic that calls the icons paint method should
* not assume the all bits are painted. <code>null</code> is a valid return value
* for this method and indicates there is no visual representation provided.
* In that case, the calling logic is free to represent the
* transferable however it wants.
* <p>
* The default Swing logic will not do an alpha blended drag animation if
* the return is <code>null</code>.
*
* @param t the data to be transferred; this value is expected to have been
* created by the <code>createTransferable</code> method
* @return <code>null</code>, indicating
* there is no default visual representation
*/
public Icon getVisualRepresentation(Transferable t) {
return null;
}
/** {@collect.stats}
* Creates a <code>Transferable</code> to use as the source for
* a data transfer. Returns the representation of the data to
* be transferred, or <code>null</code> if the component's
* property is <code>null</code>
*
* @param c the component holding the data to be transferred;
* provided to enable sharing of <code>TransferHandler</code>s
* @return the representation of the data to be transferred, or
* <code>null</code> if the property associated with <code>c</code>
* is <code>null</code>
*
*/
protected Transferable createTransferable(JComponent c) {
PropertyDescriptor property = getPropertyDescriptor(c);
if (property != null) {
return new PropertyTransferable(property, c);
}
return null;
}
/** {@collect.stats}
* Invoked after data has been exported. This method should remove
* the data that was transferred if the action was <code>MOVE</code>.
* <p>
* This method is implemented to do nothing since <code>MOVE</code>
* is not a supported action of this implementation
* (<code>getSourceActions</code> does not include <code>MOVE</code>).
*
* @param source the component that was the source of the data
* @param data The data that was transferred or possibly null
* if the action is <code>NONE</code>.
* @param action the actual action that was performed
*/
protected void exportDone(JComponent source, Transferable data, int action) {
}
/** {@collect.stats}
* Fetches the property descriptor for the property assigned to this transfer
* handler on the given component (transfer handler may be shared). This
* returns <code>null</code> if the property descriptor can't be found
* or there is an error attempting to fetch the property descriptor.
*/
private PropertyDescriptor getPropertyDescriptor(JComponent comp) {
if (propertyName == null) {
return null;
}
Class<?> k = comp.getClass();
BeanInfo bi;
try {
bi = Introspector.getBeanInfo(k);
} catch (IntrospectionException ex) {
return null;
}
PropertyDescriptor props[] = bi.getPropertyDescriptors();
for (int i=0; i < props.length; i++) {
if (propertyName.equals(props[i].getName())) {
Method reader = props[i].getReadMethod();
if (reader != null) {
Class<?>[] params = reader.getParameterTypes();
if (params == null || params.length == 0) {
// found the desired descriptor
return props[i];
}
}
}
}
return null;
}
/** {@collect.stats}
* Fetches the data flavor from the array of possible flavors that
* has data of the type represented by property type. Null is
* returned if there is no match.
*/
private DataFlavor getPropertyDataFlavor(Class<?> k, DataFlavor[] flavors) {
for(int i = 0; i < flavors.length; i++) {
DataFlavor flavor = flavors[i];
if ("application".equals(flavor.getPrimaryType()) &&
"x-java-jvm-local-objectref".equals(flavor.getSubType()) &&
k.isAssignableFrom(flavor.getRepresentationClass())) {
return flavor;
}
}
return null;
}
private String propertyName;
private static SwingDragGestureRecognizer recognizer = null;
private static DropTargetListener getDropTargetListener() {
synchronized(DropHandler.class) {
DropHandler handler =
(DropHandler)AppContext.getAppContext().get(DropHandler.class);
if (handler == null) {
handler = new DropHandler();
AppContext.getAppContext().put(DropHandler.class, handler);
}
return handler;
}
}
static class PropertyTransferable implements Transferable {
PropertyTransferable(PropertyDescriptor p, JComponent c) {
property = p;
component = c;
}
// --- Transferable methods ----------------------------------------------
/** {@collect.stats}
* Returns an array of <code>DataFlavor</code> objects indicating the flavors the data
* can be provided in. The array should be ordered according to preference
* for providing the data (from most richly descriptive to least descriptive).
* @return an array of data flavors in which this data can be transferred
*/
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] flavors = new DataFlavor[1];
Class<?> propertyType = property.getPropertyType();
String mimeType = DataFlavor.javaJVMLocalObjectMimeType + ";class=" + propertyType.getName();
try {
flavors[0] = new DataFlavor(mimeType);
} catch (ClassNotFoundException cnfe) {
flavors = new DataFlavor[0];
}
return flavors;
}
/** {@collect.stats}
* Returns whether the specified data flavor is supported for
* this object.
* @param flavor the requested flavor for the data
* @return true if this <code>DataFlavor</code> is supported,
* otherwise false
*/
public boolean isDataFlavorSupported(DataFlavor flavor) {
Class<?> propertyType = property.getPropertyType();
if ("application".equals(flavor.getPrimaryType()) &&
"x-java-jvm-local-objectref".equals(flavor.getSubType()) &&
flavor.getRepresentationClass().isAssignableFrom(propertyType)) {
return true;
}
return false;
}
/** {@collect.stats}
* Returns an object which represents the data to be transferred. The class
* of the object returned is defined by the representation class of the flavor.
*
* @param flavor the requested flavor for the data
* @see DataFlavor#getRepresentationClass
* @exception IOException if the data is no longer available
* in the requested flavor.
* @exception UnsupportedFlavorException if the requested data flavor is
* not supported.
*/
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (! isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
Method reader = property.getReadMethod();
Object value = null;
try {
value = MethodUtil.invoke(reader, component, (Object[])null);
} catch (Exception ex) {
throw new IOException("Property read failed: " + property.getName());
}
return value;
}
JComponent component;
PropertyDescriptor property;
}
/** {@collect.stats}
* This is the default drop target for drag and drop operations if
* one isn't provided by the developer. <code>DropTarget</code>
* only supports one <code>DropTargetListener</code> and doesn't
* function properly if it isn't set.
* This class sets the one listener as the linkage of drop handling
* to the <code>TransferHandler</code>, and adds support for
* additional listeners which some of the <code>ComponentUI</code>
* implementations install to manipulate a drop insertion location.
*/
static class SwingDropTarget extends DropTarget implements UIResource {
SwingDropTarget(Component c) {
super(c, COPY_OR_MOVE | LINK, null);
try {
// addDropTargetListener is overridden
// we specifically need to add to the superclass
super.addDropTargetListener(getDropTargetListener());
} catch (TooManyListenersException tmle) {}
}
public void addDropTargetListener(DropTargetListener dtl) throws TooManyListenersException {
// Since the super class only supports one DropTargetListener,
// and we add one from the constructor, we always add to the
// extended list.
if (listenerList == null) {
listenerList = new EventListenerList();
}
listenerList.add(DropTargetListener.class, dtl);
}
public void removeDropTargetListener(DropTargetListener dtl) {
if (listenerList != null) {
listenerList.remove(DropTargetListener.class, dtl);
}
}
// --- DropTargetListener methods (multicast) --------------------------
public void dragEnter(DropTargetDragEvent e) {
super.dragEnter(e);
if (listenerList != null) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DropTargetListener.class) {
((DropTargetListener)listeners[i+1]).dragEnter(e);
}
}
}
}
public void dragOver(DropTargetDragEvent e) {
super.dragOver(e);
if (listenerList != null) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DropTargetListener.class) {
((DropTargetListener)listeners[i+1]).dragOver(e);
}
}
}
}
public void dragExit(DropTargetEvent e) {
super.dragExit(e);
if (listenerList != null) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DropTargetListener.class) {
((DropTargetListener)listeners[i+1]).dragExit(e);
}
}
}
}
public void drop(DropTargetDropEvent e) {
super.drop(e);
if (listenerList != null) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DropTargetListener.class) {
((DropTargetListener)listeners[i+1]).drop(e);
}
}
}
}
public void dropActionChanged(DropTargetDragEvent e) {
super.dropActionChanged(e);
if (listenerList != null) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DropTargetListener.class) {
((DropTargetListener)listeners[i+1]).dropActionChanged(e);
}
}
}
}
private EventListenerList listenerList;
}
private static class DropHandler implements DropTargetListener,
Serializable,
ActionListener {
private Timer timer;
private Point lastPosition;
private Rectangle outer = new Rectangle();
private Rectangle inner = new Rectangle();
private int hysteresis = 10;
private Component component;
private Object state;
private TransferSupport support =
new TransferSupport(null, (DropTargetEvent)null);
private static final int AUTOSCROLL_INSET = 10;
/** {@collect.stats}
* Update the geometry of the autoscroll region. The geometry is
* maintained as a pair of rectangles. The region can cause
* a scroll if the pointer sits inside it for the duration of the
* timer. The region that causes the timer countdown is the area
* between the two rectangles.
* <p>
* This is implemented to use the visible area of the component
* as the outer rectangle, and the insets are fixed at 10. Should
* the component be smaller than a total of 20 in any direction,
* autoscroll will not occur in that direction.
*/
private void updateAutoscrollRegion(JComponent c) {
// compute the outer
Rectangle visible = c.getVisibleRect();
outer.setBounds(visible.x, visible.y, visible.width, visible.height);
// compute the insets
Insets i = new Insets(0, 0, 0, 0);
if (c instanceof Scrollable) {
int minSize = 2 * AUTOSCROLL_INSET;
if (visible.width >= minSize) {
i.left = i.right = AUTOSCROLL_INSET;
}
if (visible.height >= minSize) {
i.top = i.bottom = AUTOSCROLL_INSET;
}
}
// set the inner from the insets
inner.setBounds(visible.x + i.left,
visible.y + i.top,
visible.width - (i.left + i.right),
visible.height - (i.top + i.bottom));
}
/** {@collect.stats}
* Perform an autoscroll operation. This is implemented to scroll by the
* unit increment of the Scrollable using scrollRectToVisible. If the
* cursor is in a corner of the autoscroll region, more than one axis will
* scroll.
*/
private void autoscroll(JComponent c, Point pos) {
if (c instanceof Scrollable) {
Scrollable s = (Scrollable) c;
if (pos.y < inner.y) {
// scroll upward
int dy = s.getScrollableUnitIncrement(outer, SwingConstants.VERTICAL, -1);
Rectangle r = new Rectangle(inner.x, outer.y - dy, inner.width, dy);
c.scrollRectToVisible(r);
} else if (pos.y > (inner.y + inner.height)) {
// scroll downard
int dy = s.getScrollableUnitIncrement(outer, SwingConstants.VERTICAL, 1);
Rectangle r = new Rectangle(inner.x, outer.y + outer.height, inner.width, dy);
c.scrollRectToVisible(r);
}
if (pos.x < inner.x) {
// scroll left
int dx = s.getScrollableUnitIncrement(outer, SwingConstants.HORIZONTAL, -1);
Rectangle r = new Rectangle(outer.x - dx, inner.y, dx, inner.height);
c.scrollRectToVisible(r);
} else if (pos.x > (inner.x + inner.width)) {
// scroll right
int dx = s.getScrollableUnitIncrement(outer, SwingConstants.HORIZONTAL, 1);
Rectangle r = new Rectangle(outer.x + outer.width, inner.y, dx, inner.height);
c.scrollRectToVisible(r);
}
}
}
/** {@collect.stats}
* Initializes the internal properties if they haven't been already
* inited. This is done lazily to avoid loading of desktop properties.
*/
private void initPropertiesIfNecessary() {
if (timer == null) {
Toolkit t = Toolkit.getDefaultToolkit();
Integer prop;
prop = (Integer)
t.getDesktopProperty("DnD.Autoscroll.interval");
timer = new Timer(prop == null ? 100 : prop.intValue(), this);
prop = (Integer)
t.getDesktopProperty("DnD.Autoscroll.initialDelay");
timer.setInitialDelay(prop == null ? 100 : prop.intValue());
prop = (Integer)
t.getDesktopProperty("DnD.Autoscroll.cursorHysteresis");
if (prop != null) {
hysteresis = prop.intValue();
}
}
}
/** {@collect.stats}
* The timer fired, perform autoscroll if the pointer is within the
* autoscroll region.
* <P>
* @param e the <code>ActionEvent</code>
*/
public void actionPerformed(ActionEvent e) {
updateAutoscrollRegion((JComponent)component);
if (outer.contains(lastPosition) && !inner.contains(lastPosition)) {
autoscroll((JComponent)component, lastPosition);
}
}
// --- DropTargetListener methods -----------------------------------
private void setComponentDropLocation(TransferSupport support,
boolean forDrop) {
DropLocation dropLocation = (support == null)
? null
: support.getDropLocation();
if (component instanceof JTextComponent) {
try {
AccessibleMethod method =
new AccessibleMethod(JTextComponent.class,
"setDropLocation",
DropLocation.class,
Object.class,
Boolean.TYPE);
state =
method.invokeNoChecked(component, dropLocation,
state, forDrop);
} catch (NoSuchMethodException e) {
throw new AssertionError(
"Couldn't locate method JTextComponet.setDropLocation");
}
} else if (component instanceof JComponent) {
state = ((JComponent)component).setDropLocation(dropLocation, state, forDrop);
}
}
private void handleDrag(DropTargetDragEvent e) {
TransferHandler importer =
((HasGetTransferHandler)component).getTransferHandler();
if (importer == null) {
e.rejectDrag();
setComponentDropLocation(null, false);
return;
}
support.setDNDVariables(component, e);
boolean canImport = importer.canImport(support);
if (canImport) {
e.acceptDrag(support.getDropAction());
} else {
e.rejectDrag();
}
boolean showLocation = support.showDropLocationIsSet ?
support.showDropLocation :
canImport;
setComponentDropLocation(showLocation ? support : null, false);
}
public void dragEnter(DropTargetDragEvent e) {
state = null;
component = e.getDropTargetContext().getComponent();
handleDrag(e);
if (component instanceof JComponent) {
lastPosition = e.getLocation();
updateAutoscrollRegion((JComponent)component);
initPropertiesIfNecessary();
}
}
public void dragOver(DropTargetDragEvent e) {
handleDrag(e);
if (!(component instanceof JComponent)) {
return;
}
Point p = e.getLocation();
if (Math.abs(p.x - lastPosition.x) > hysteresis
|| Math.abs(p.y - lastPosition.y) > hysteresis) {
// no autoscroll
if (timer.isRunning()) timer.stop();
} else {
if (!timer.isRunning()) timer.start();
}
lastPosition = p;
}
public void dragExit(DropTargetEvent e) {
cleanup(false);
}
public void drop(DropTargetDropEvent e) {
TransferHandler importer =
((HasGetTransferHandler)component).getTransferHandler();
if (importer == null) {
e.rejectDrop();
cleanup(false);
return;
}
support.setDNDVariables(component, e);
boolean canImport = importer.canImport(support);
if (canImport) {
e.acceptDrop(support.getDropAction());
boolean showLocation = support.showDropLocationIsSet ?
support.showDropLocation :
canImport;
setComponentDropLocation(showLocation ? support : null, false);
boolean success;
try {
success = importer.importData(support);
} catch (RuntimeException re) {
success = false;
}
e.dropComplete(success);
cleanup(success);
} else {
e.rejectDrop();
cleanup(false);
}
}
public void dropActionChanged(DropTargetDragEvent e) {
/*
* Work-around for Linux bug where dropActionChanged
* is called before dragEnter.
*/
if (component == null) {
return;
}
handleDrag(e);
}
private void cleanup(boolean forDrop) {
setComponentDropLocation(null, forDrop);
if (component instanceof JComponent) {
((JComponent)component).dndDone();
}
if (timer != null) {
timer.stop();
}
state = null;
component = null;
lastPosition = null;
}
}
/** {@collect.stats}
* This is the default drag handler for drag and drop operations that
* use the <code>TransferHandler</code>.
*/
private static class DragHandler implements DragGestureListener, DragSourceListener {
private boolean scrolls;
// --- DragGestureListener methods -----------------------------------
/** {@collect.stats}
* a Drag gesture has been recognized
*/
public void dragGestureRecognized(DragGestureEvent dge) {
JComponent c = (JComponent) dge.getComponent();
TransferHandler th = c.getTransferHandler();
Transferable t = th.createTransferable(c);
if (t != null) {
scrolls = c.getAutoscrolls();
c.setAutoscrolls(false);
try {
dge.startDrag(null, t, this);
return;
} catch (RuntimeException re) {
c.setAutoscrolls(scrolls);
}
}
th.exportDone(c, t, NONE);
}
// --- DragSourceListener methods -----------------------------------
/** {@collect.stats}
* as the hotspot enters a platform dependent drop site
*/
public void dragEnter(DragSourceDragEvent dsde) {
}
/** {@collect.stats}
* as the hotspot moves over a platform dependent drop site
*/
public void dragOver(DragSourceDragEvent dsde) {
}
/** {@collect.stats}
* as the hotspot exits a platform dependent drop site
*/
public void dragExit(DragSourceEvent dsde) {
}
/** {@collect.stats}
* as the operation completes
*/
public void dragDropEnd(DragSourceDropEvent dsde) {
DragSourceContext dsc = dsde.getDragSourceContext();
JComponent c = (JComponent)dsc.getComponent();
if (dsde.getDropSuccess()) {
c.getTransferHandler().exportDone(c, dsc.getTransferable(), dsde.getDropAction());
} else {
c.getTransferHandler().exportDone(c, dsc.getTransferable(), NONE);
}
c.setAutoscrolls(scrolls);
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
}
private static class SwingDragGestureRecognizer extends DragGestureRecognizer {
SwingDragGestureRecognizer(DragGestureListener dgl) {
super(DragSource.getDefaultDragSource(), null, NONE, dgl);
}
void gestured(JComponent c, MouseEvent e, int srcActions, int action) {
setComponent(c);
setSourceActions(srcActions);
appendEvent(e);
fireDragGestureRecognized(action, e.getPoint());
}
/** {@collect.stats}
* register this DragGestureRecognizer's Listeners with the Component
*/
protected void registerListeners() {
}
/** {@collect.stats}
* unregister this DragGestureRecognizer's Listeners with the Component
*
* subclasses must override this method
*/
protected void unregisterListeners() {
}
}
static final Action cutAction = new TransferAction("cut");
static final Action copyAction = new TransferAction("copy");
static final Action pasteAction = new TransferAction("paste");
static class TransferAction extends UIAction implements UIResource {
TransferAction(String name) {
super(name);
}
public boolean isEnabled(Object sender) {
if (sender instanceof JComponent
&& ((JComponent)sender).getTransferHandler() == null) {
return false;
}
return true;
}
private static final JavaSecurityAccess javaSecurityAccess =
SharedSecrets.getJavaSecurityAccess();
public void actionPerformed(final ActionEvent e) {
final Object src = e.getSource();
final PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
public Void run() {
actionPerformedImpl(e);
return null;
}
};
final AccessControlContext stack = AccessController.getContext();
final AccessControlContext srcAcc = AWTAccessor.getComponentAccessor().getAccessControlContext((Component)src);
final AccessControlContext eventAcc = AWTAccessor.getAWTEventAccessor().getAccessControlContext(e);
if (srcAcc == null) {
javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc);
} else {
javaSecurityAccess.doIntersectionPrivilege(
new PrivilegedAction<Void>() {
public Void run() {
javaSecurityAccess.doIntersectionPrivilege(action, eventAcc);
return null;
}
}, stack, srcAcc);
}
}
private void actionPerformedImpl(ActionEvent e) {
Object src = e.getSource();
if (src instanceof JComponent) {
JComponent c = (JComponent) src;
TransferHandler th = c.getTransferHandler();
Clipboard clipboard = getClipboard(c);
String name = (String) getValue(Action.NAME);
Transferable trans = null;
// any of these calls may throw IllegalStateException
try {
if ((clipboard != null) && (th != null) && (name != null)) {
if ("cut".equals(name)) {
th.exportToClipboard(c, clipboard, MOVE);
} else if ("copy".equals(name)) {
th.exportToClipboard(c, clipboard, COPY);
} else if ("paste".equals(name)) {
trans = clipboard.getContents(null);
}
}
} catch (IllegalStateException ise) {
// clipboard was unavailable
UIManager.getLookAndFeel().provideErrorFeedback(c);
return;
}
// this is a paste action, import data into the component
if (trans != null) {
th.importData(new TransferSupport(c, trans));
}
}
}
/** {@collect.stats}
* Returns the clipboard to use for cut/copy/paste.
*/
private Clipboard getClipboard(JComponent c) {
if (SwingUtilities2.canAccessSystemClipboard()) {
return c.getToolkit().getSystemClipboard();
}
Clipboard clipboard = (Clipboard)sun.awt.AppContext.getAppContext().
get(SandboxClipboardKey);
if (clipboard == null) {
clipboard = new Clipboard("Sandboxed Component Clipboard");
sun.awt.AppContext.getAppContext().put(SandboxClipboardKey,
clipboard);
}
return clipboard;
}
/** {@collect.stats}
* Key used in app context to lookup Clipboard to use if access to
* System clipboard is denied.
*/
private static Object SandboxClipboardKey = new Object();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
import java.awt.event.*;
import java.beans.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Hashtable;
/** {@collect.stats}
* <code>JToolBar</code> provides a component that is useful for
* displaying commonly used <code>Action</code>s or controls.
* For examples and information on using tool bars see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/toolbar.html">How to Use Tool Bars</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
* With most look and feels,
* the user can drag out a tool bar into a separate window
* (unless the <code>floatable</code> property is set to <code>false</code>).
* For drag-out to work correctly, it is recommended that you add
* <code>JToolBar</code> instances to one of the four "sides" of a
* container whose layout manager is a <code>BorderLayout</code>,
* and do not add children to any of the other four "sides".
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer true
* description: A component which displays commonly used controls or Actions.
*
* @author Georges Saab
* @author Jeff Shapiro
* @see Action
*/
public class JToolBar extends JComponent implements SwingConstants, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ToolBarUI";
private boolean paintBorder = true;
private Insets margin = null;
private boolean floatable = true;
private int orientation = HORIZONTAL;
/** {@collect.stats}
* Creates a new tool bar; orientation defaults to <code>HORIZONTAL</code>.
*/
public JToolBar()
{
this( HORIZONTAL );
}
/** {@collect.stats}
* Creates a new tool bar with the specified <code>orientation</code>.
* The <code>orientation</code> must be either <code>HORIZONTAL</code>
* or <code>VERTICAL</code>.
*
* @param orientation the orientation desired
*/
public JToolBar( int orientation )
{
this(null, orientation);
}
/** {@collect.stats}
* Creates a new tool bar with the specified <code>name</code>. The
* name is used as the title of the undocked tool bar. The default
* orientation is <code>HORIZONTAL</code>.
*
* @param name the name of the tool bar
* @since 1.3
*/
public JToolBar( String name ) {
this(name, HORIZONTAL);
}
/** {@collect.stats}
* Creates a new tool bar with a specified <code>name</code> and
* <code>orientation</code>.
* All other constructors call this constructor.
* If <code>orientation</code> is an invalid value, an exception will
* be thrown.
*
* @param name the name of the tool bar
* @param orientation the initial orientation -- it must be
* either <code>HORIZONTAL</code> or <code>VERTICAL</code>
* @exception IllegalArgumentException if orientation is neither
* <code>HORIZONTAL</code> nor <code>VERTICAL</code>
* @since 1.3
*/
public JToolBar( String name , int orientation) {
setName(name);
checkOrientation( orientation );
this.orientation = orientation;
DefaultToolBarLayout layout = new DefaultToolBarLayout( orientation );
setLayout( layout );
addPropertyChangeListener( layout );
updateUI();
}
/** {@collect.stats}
* Returns the tool bar's current UI.
* @see #setUI
*/
public ToolBarUI getUI() {
return (ToolBarUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>ToolBarUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(ToolBarUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Notification from the <code>UIFactory</code> that the L&F has changed.
* Called to replace the UI with the latest version from the
* <code>UIFactory</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ToolBarUI)UIManager.getUI(this));
// GTKLookAndFeel installs a different LayoutManager, and sets it
// to null after changing the look and feel, so, install the default
// if the LayoutManager is null.
if (getLayout() == null) {
setLayout(new DefaultToolBarLayout(getOrientation()));
}
invalidate();
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "ToolBarUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the index of the specified component.
* (Note: Separators occupy index positions.)
*
* @param c the <code>Component</code> to find
* @return an integer indicating the component's position,
* where 0 is first
*/
public int getComponentIndex(Component c) {
int ncomponents = this.getComponentCount();
Component[] component = this.getComponents();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = component[i];
if (comp == c)
return i;
}
return -1;
}
/** {@collect.stats}
* Returns the component at the specified index.
*
* @param i the component's position, where 0 is first
* @return the <code>Component</code> at that position,
* or <code>null</code> for an invalid index
*
*/
public Component getComponentAtIndex(int i) {
int ncomponents = this.getComponentCount();
if ( i >= 0 && i < ncomponents) {
Component[] component = this.getComponents();
return component[i];
}
return null;
}
/** {@collect.stats}
* Sets the margin between the tool bar's border and
* its buttons. Setting to <code>null</code> causes the tool bar to
* use the default margins. The tool bar's default <code>Border</code>
* object uses this value to create the proper margin.
* However, if a non-default border is set on the tool bar,
* it is that <code>Border</code> object's responsibility to create the
* appropriate margin space (otherwise this property will
* effectively be ignored).
*
* @param m an <code>Insets</code> object that defines the space
* between the border and the buttons
* @see Insets
* @beaninfo
* description: The margin between the tool bar's border and contents
* bound: true
* expert: true
*/
public void setMargin(Insets m)
{
Insets old = margin;
margin = m;
firePropertyChange("margin", old, m);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the margin between the tool bar's border and
* its buttons.
*
* @return an <code>Insets</code> object containing the margin values
* @see Insets
*/
public Insets getMargin()
{
if(margin == null) {
return new Insets(0,0,0,0);
} else {
return margin;
}
}
/** {@collect.stats}
* Gets the <code>borderPainted</code> property.
*
* @return the value of the <code>borderPainted</code> property
* @see #setBorderPainted
*/
public boolean isBorderPainted()
{
return paintBorder;
}
/** {@collect.stats}
* Sets the <code>borderPainted</code> property, which is
* <code>true</code> if the border should be painted.
* The default value for this property is <code>true</code>.
* Some look and feels might not implement painted borders;
* they will ignore this property.
*
* @param b if true, the border is painted
* @see #isBorderPainted
* @beaninfo
* description: Does the tool bar paint its borders?
* bound: true
* expert: true
*/
public void setBorderPainted(boolean b)
{
if ( paintBorder != b )
{
boolean old = paintBorder;
paintBorder = b;
firePropertyChange("borderPainted", old, b);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Paints the tool bar's border if the <code>borderPainted</code> property
* is <code>true</code>.
*
* @param g the <code>Graphics</code> context in which the painting
* is done
* @see JComponent#paint
* @see JComponent#setBorder
*/
protected void paintBorder(Graphics g)
{
if (isBorderPainted())
{
super.paintBorder(g);
}
}
/** {@collect.stats}
* Gets the <code>floatable</code> property.
*
* @return the value of the <code>floatable</code> property
*
* @see #setFloatable
*/
public boolean isFloatable()
{
return floatable;
}
/** {@collect.stats}
* Sets the <code>floatable</code> property,
* which must be <code>true</code> for the user to move the tool bar.
* Typically, a floatable tool bar can be
* dragged into a different position within the same container
* or out into its own window.
* The default value of this property is <code>true</code>.
* Some look and feels might not implement floatable tool bars;
* they will ignore this property.
*
* @param b if <code>true</code>, the tool bar can be moved;
* <code>false</code> otherwise
* @see #isFloatable
* @beaninfo
* description: Can the tool bar be made to float by the user?
* bound: true
* preferred: true
*/
public void setFloatable( boolean b )
{
if ( floatable != b )
{
boolean old = floatable;
floatable = b;
firePropertyChange("floatable", old, b);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the current orientation of the tool bar. The value is either
* <code>HORIZONTAL</code> or <code>VERTICAL</code>.
*
* @return an integer representing the current orientation -- either
* <code>HORIZONTAL</code> or <code>VERTICAL</code>
* @see #setOrientation
*/
public int getOrientation()
{
return this.orientation;
}
/** {@collect.stats}
* Sets the orientation of the tool bar. The orientation must have
* either the value <code>HORIZONTAL</code> or <code>VERTICAL</code>.
* If <code>orientation</code> is
* an invalid value, an exception will be thrown.
*
* @param o the new orientation -- either <code>HORIZONTAL</code> or
* <code>VERTICAL</code>
* @exception IllegalArgumentException if orientation is neither
* <code>HORIZONTAL</code> nor <code>VERTICAL</code>
* @see #getOrientation
* @beaninfo
* description: The current orientation of the tool bar
* bound: true
* preferred: true
* enum: HORIZONTAL SwingConstants.HORIZONTAL
* VERTICAL SwingConstants.VERTICAL
*/
public void setOrientation( int o )
{
checkOrientation( o );
if ( orientation != o )
{
int old = orientation;
orientation = o;
firePropertyChange("orientation", old, o);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the rollover state of this toolbar. If the rollover state is true
* then the border of the toolbar buttons will be drawn only when the
* mouse pointer hovers over them. The default value of this property
* is false.
* <p>
* The implementation of a look and feel may choose to ignore this
* property.
*
* @param rollover true for rollover toolbar buttons; otherwise false
* @since 1.4
* @beaninfo
* bound: true
* preferred: true
* attribute: visualUpdate true
* description: Will draw rollover button borders in the toolbar.
*/
public void setRollover(boolean rollover) {
putClientProperty("JToolBar.isRollover",
rollover ? Boolean.TRUE : Boolean.FALSE);
}
/** {@collect.stats}
* Returns the rollover state.
*
* @return true if rollover toolbar buttons are to be drawn; otherwise false
* @see #setRollover(boolean)
* @since 1.4
*/
public boolean isRollover() {
Boolean rollover = (Boolean)getClientProperty("JToolBar.isRollover");
if (rollover != null) {
return rollover.booleanValue();
}
return false;
}
private void checkOrientation( int orientation )
{
switch ( orientation )
{
case VERTICAL:
case HORIZONTAL:
break;
default:
throw new IllegalArgumentException( "orientation must be one of: VERTICAL, HORIZONTAL" );
}
}
/** {@collect.stats}
* Appends a separator of default size to the end of the tool bar.
* The default size is determined by the current look and feel.
*/
public void addSeparator()
{
addSeparator(null);
}
/** {@collect.stats}
* Appends a separator of a specified size to the end
* of the tool bar.
*
* @param size the <code>Dimension</code> of the separator
*/
public void addSeparator( Dimension size )
{
JToolBar.Separator s = new JToolBar.Separator( size );
add(s);
}
/** {@collect.stats}
* Adds a new <code>JButton</code> which dispatches the action.
*
* @param a the <code>Action</code> object to add as a new menu item
* @return the new button which dispatches the action
*/
public JButton add(Action a) {
JButton b = createActionComponent(a);
b.setAction(a);
add(b);
return b;
}
/** {@collect.stats}
* Factory method which creates the <code>JButton</code> for
* <code>Action</code>s added to the <code>JToolBar</code>.
* The default name is empty if a <code>null</code> action is passed.
*
* @param a the <code>Action</code> for the button to be added
* @return the newly created button
* @see Action
* @since 1.3
*/
protected JButton createActionComponent(Action a) {
JButton b = new JButton() {
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
PropertyChangeListener pcl = createActionChangeListener(this);
if (pcl==null) {
pcl = super.createActionPropertyChangeListener(a);
}
return pcl;
}
};
if (a != null && (a.getValue(Action.SMALL_ICON) != null ||
a.getValue(Action.LARGE_ICON_KEY) != null)) {
b.setHideActionText(true);
}
b.setHorizontalTextPosition(JButton.CENTER);
b.setVerticalTextPosition(JButton.BOTTOM);
return b;
}
/** {@collect.stats}
* Returns a properly configured <code>PropertyChangeListener</code>
* which updates the control as changes to the <code>Action</code> occur,
* or <code>null</code> if the default
* property change listener for the control is desired.
*
* @return <code>null</code>
*/
protected PropertyChangeListener createActionChangeListener(JButton b) {
return null;
}
/** {@collect.stats}
* If a <code>JButton</code> is being added, it is initially
* set to be disabled.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be enforced on the component
* @param index the index of the component
*
*/
protected void addImpl(Component comp, Object constraints, int index) {
if (comp instanceof Separator) {
if (getOrientation() == VERTICAL) {
( (Separator)comp ).setOrientation(JSeparator.HORIZONTAL);
} else {
( (Separator)comp ).setOrientation(JSeparator.VERTICAL);
}
}
super.addImpl(comp, constraints, index);
if (comp instanceof JButton) {
((JButton)comp).setDefaultCapable(false);
}
}
/** {@collect.stats}
* A toolbar-specific separator. An object with dimension but
* no contents used to divide buttons on a tool bar into groups.
*/
static public class Separator extends JSeparator
{
private Dimension separatorSize;
/** {@collect.stats}
* Creates a new toolbar separator with the default size
* as defined by the current look and feel.
*/
public Separator()
{
this( null ); // let the UI define the default size
}
/** {@collect.stats}
* Creates a new toolbar separator with the specified size.
*
* @param size the <code>Dimension</code> of the separator
*/
public Separator( Dimension size )
{
super( JSeparator.HORIZONTAL );
setSeparatorSize(size);
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "ToolBarSeparatorUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID()
{
return "ToolBarSeparatorUI";
}
/** {@collect.stats}
* Sets the size of the separator.
*
* @param size the new <code>Dimension</code> of the separator
*/
public void setSeparatorSize( Dimension size )
{
if (size != null) {
separatorSize = size;
} else {
super.updateUI();
}
this.invalidate();
}
/** {@collect.stats}
* Returns the size of the separator
*
* @return the <code>Dimension</code> object containing the separator's
* size (This is a reference, NOT a copy!)
*/
public Dimension getSeparatorSize()
{
return separatorSize;
}
/** {@collect.stats}
* Returns the minimum size for the separator.
*
* @return the <code>Dimension</code> object containing the separator's
* minimum size
*/
public Dimension getMinimumSize()
{
if (separatorSize != null) {
return separatorSize.getSize();
} else {
return super.getMinimumSize();
}
}
/** {@collect.stats}
* Returns the maximum size for the separator.
*
* @return the <code>Dimension</code> object containing the separator's
* maximum size
*/
public Dimension getMaximumSize()
{
if (separatorSize != null) {
return separatorSize.getSize();
} else {
return super.getMaximumSize();
}
}
/** {@collect.stats}
* Returns the preferred size for the separator.
*
* @return the <code>Dimension</code> object containing the separator's
* preferred size
*/
public Dimension getPreferredSize()
{
if (separatorSize != null) {
return separatorSize.getSize();
} else {
return super.getPreferredSize();
}
}
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JToolBar</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JToolBar</code>.
*/
protected String paramString() {
String paintBorderString = (paintBorder ?
"true" : "false");
String marginString = (margin != null ?
margin.toString() : "");
String floatableString = (floatable ?
"true" : "false");
String orientationString = (orientation == HORIZONTAL ?
"HORIZONTAL" : "VERTICAL");
return super.paramString() +
",floatable=" + floatableString +
",margin=" + marginString +
",orientation=" + orientationString +
",paintBorder=" + paintBorderString;
}
private class DefaultToolBarLayout
implements LayoutManager2, Serializable, PropertyChangeListener, UIResource {
BoxLayout lm;
DefaultToolBarLayout(int orientation) {
if (orientation == JToolBar.VERTICAL) {
lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS);
} else {
lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS);
}
}
public void addLayoutComponent(String name, Component comp) {
lm.addLayoutComponent(name, comp);
}
public void addLayoutComponent(Component comp, Object constraints) {
lm.addLayoutComponent(comp, constraints);
}
public void removeLayoutComponent(Component comp) {
lm.removeLayoutComponent(comp);
}
public Dimension preferredLayoutSize(Container target) {
return lm.preferredLayoutSize(target);
}
public Dimension minimumLayoutSize(Container target) {
return lm.minimumLayoutSize(target);
}
public Dimension maximumLayoutSize(Container target) {
return lm.maximumLayoutSize(target);
}
public void layoutContainer(Container target) {
lm.layoutContainer(target);
}
public float getLayoutAlignmentX(Container target) {
return lm.getLayoutAlignmentX(target);
}
public float getLayoutAlignmentY(Container target) {
return lm.getLayoutAlignmentY(target);
}
public void invalidateLayout(Container target) {
lm.invalidateLayout(target);
}
public void propertyChange(PropertyChangeEvent e) {
String name = e.getPropertyName();
if( name.equals("orientation") ) {
int o = ((Integer)e.getNewValue()).intValue();
if (o == JToolBar.VERTICAL)
lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS);
else {
lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS);
}
}
}
}
public void setLayout(LayoutManager mgr) {
LayoutManager oldMgr = getLayout();
if (oldMgr instanceof PropertyChangeListener) {
removePropertyChangeListener((PropertyChangeListener)oldMgr);
}
super.setLayout(mgr);
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JToolBar.
* For tool bars, the AccessibleContext takes the form of an
* AccessibleJToolBar.
* A new AccessibleJToolBar instance is created if necessary.
*
* @return an AccessibleJToolBar that serves as the
* AccessibleContext of this JToolBar
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJToolBar();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JToolBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to toolbar user-interface elements.
*/
protected class AccessibleJToolBar extends AccessibleJComponent {
/** {@collect.stats}
* Get the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
// FIXME: [[[WDW - need to add orientation from BoxLayout]]]
// FIXME: [[[WDW - need to do SELECTABLE if SelectionModel is added]]]
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TOOL_BAR;
}
} // inner class AccessibleJToolBar
}
|
Java
|
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.table.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.text.MessageFormat;
/** {@collect.stats}
* An implementation of <code>Printable</code> for printing
* <code>JTable</code>s.
* <p>
* This implementation spreads table rows naturally in sequence
* across multiple pages, fitting as many rows as possible per page.
* The distribution of columns, on the other hand, is controlled by a
* printing mode parameter passed to the constructor. When
* <code>JTable.PrintMode.NORMAL</code> is used, the implementation
* handles columns in a similar manner to how it handles rows, spreading them
* across multiple pages (in an order consistent with the table's
* <code>ComponentOrientation</code>).
* When <code>JTable.PrintMode.FIT_WIDTH</code> is given, the implementation
* scales the output smaller if necessary, to ensure that all columns fit on
* the page. (Note that width and height are scaled equally, ensuring that the
* aspect ratio remains the same).
* <p>
* The portion of table printed on each page is headed by the
* appropriate section of the table's <code>JTableHeader</code>.
* <p>
* Header and footer text can be added to the output by providing
* <code>MessageFormat</code> instances to the constructor. The
* printing code requests Strings from the formats by calling
* their <code>format</code> method with a single parameter:
* an <code>Object</code> array containing a single element of type
* <code>Integer</code>, representing the current page number.
* <p>
* There are certain circumstances where this <code>Printable</code>
* cannot fit items appropriately, resulting in clipped output.
* These are:
* <ul>
* <li>In any mode, when the header or footer text is too wide to
* fit completely in the printable area. The implementation
* prints as much of the text as possible starting from the beginning,
* as determined by the table's <code>ComponentOrientation</code>.
* <li>In any mode, when a row is too tall to fit in the
* printable area. The upper most portion of the row
* is printed and no lower border is shown.
* <li>In <code>JTable.PrintMode.NORMAL</code> when a column
* is too wide to fit in the printable area. The center of the
* column is printed and no left and right borders are shown.
* </ul>
* <p>
* It is entirely valid for a developer to wrap this <code>Printable</code>
* inside another in order to create complex reports and documents. They may
* even request that different pages be rendered into different sized
* printable areas. The implementation was designed to handle this by
* performing most of its calculations on the fly. However, providing different
* sizes works best when <code>JTable.PrintMode.FIT_WIDTH</code> is used, or
* when only the printable width is changed between pages. This is because when
* it is printing a set of rows in <code>JTable.PrintMode.NORMAL</code> and the
* implementation determines a need to distribute columns across pages,
* it assumes that all of those rows will fit on each subsequent page needed
* to fit the columns.
* <p>
* It is the responsibility of the developer to ensure that the table is not
* modified in any way after this <code>Printable</code> is created (invalid
* modifications include changes in: size, renderers, or underlying data).
* The behavior of this <code>Printable</code> is undefined if the table is
* changed at any time after creation.
*
* @author Shannon Hickey
*/
class TablePrintable implements Printable {
/** {@collect.stats} The table to print. */
private JTable table;
/** {@collect.stats} For quick reference to the table's header. */
private JTableHeader header;
/** {@collect.stats} For quick reference to the table's column model. */
private TableColumnModel colModel;
/** {@collect.stats} To save multiple calculations of total column width. */
private int totalColWidth;
/** {@collect.stats} The printing mode of this printable. */
private JTable.PrintMode printMode;
/** {@collect.stats} Provides the header text for the table. */
private MessageFormat headerFormat;
/** {@collect.stats} Provides the footer text for the table. */
private MessageFormat footerFormat;
/** {@collect.stats} The most recent page index asked to print. */
private int last = -1;
/** {@collect.stats} The next row to print. */
private int row = 0;
/** {@collect.stats} The next column to print. */
private int col = 0;
/** {@collect.stats} Used to store an area of the table to be printed. */
private final Rectangle clip = new Rectangle(0, 0, 0, 0);
/** {@collect.stats} Used to store an area of the table's header to be printed. */
private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
/** {@collect.stats} Saves the creation of multiple rectangles. */
private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
/** {@collect.stats} Vertical space to leave between table and header/footer text. */
private static final int H_F_SPACE = 8;
/** {@collect.stats} Font size for the header text. */
private static final float HEADER_FONT_SIZE = 18.0f;
/** {@collect.stats} Font size for the footer text. */
private static final float FOOTER_FONT_SIZE = 12.0f;
/** {@collect.stats} The font to use in rendering header text. */
private Font headerFont;
/** {@collect.stats} The font to use in rendering footer text. */
private Font footerFont;
/** {@collect.stats}
* Create a new <code>TablePrintable</code> for the given
* <code>JTable</code>. Header and footer text can be specified using the
* two <code>MessageFormat</code> parameters. When called upon to provide
* a String, each format is given the current page number.
*
* @param table the table to print
* @param printMode the printing mode for this printable
* @param headerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a header, or null for none
* @param footerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a footer, or null for none
* @throws IllegalArgumentException if passed an invalid print mode
*/
public TablePrintable(JTable table,
JTable.PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat) {
this.table = table;
header = table.getTableHeader();
colModel = table.getColumnModel();
totalColWidth = colModel.getTotalColumnWidth();
if (header != null) {
// the header clip height can be set once since it's unchanging
hclip.height = header.getHeight();
}
this.printMode = printMode;
this.headerFormat = headerFormat;
this.footerFormat = footerFormat;
// derive the header and footer font from the table's font
headerFont = table.getFont().deriveFont(Font.BOLD,
HEADER_FONT_SIZE);
footerFont = table.getFont().deriveFont(Font.PLAIN,
FOOTER_FONT_SIZE);
}
/** {@collect.stats}
* Prints the specified page of the table into the given {@link Graphics}
* context, in the specified format.
*
* @param graphics the context into which the page is drawn
* @param pageFormat the size and orientation of the page being drawn
* @param pageIndex the zero based index of the page to be drawn
* @return PAGE_EXISTS if the page is rendered successfully, or
* NO_SUCH_PAGE if a non-existent page index is specified
* @throws PrinterException if an error causes printing to be aborted
*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
// for easy access to these values
final int imgWidth = (int)pageFormat.getImageableWidth();
final int imgHeight = (int)pageFormat.getImageableHeight();
if (imgWidth <= 0) {
throw new PrinterException("Width of printable area is too small.");
}
// to pass the page number when formatting the header and footer text
Object[] pageNumber = new Object[]{new Integer(pageIndex + 1)};
// fetch the formatted header text, if any
String headerText = null;
if (headerFormat != null) {
headerText = headerFormat.format(pageNumber);
}
// fetch the formatted footer text, if any
String footerText = null;
if (footerFormat != null) {
footerText = footerFormat.format(pageNumber);
}
// to store the bounds of the header and footer text
Rectangle2D hRect = null;
Rectangle2D fRect = null;
// the amount of vertical space needed for the header and footer text
int headerTextSpace = 0;
int footerTextSpace = 0;
// the amount of vertical space available for printing the table
int availableSpace = imgHeight;
// if there's header text, find out how much space is needed for it
// and subtract that from the available space
if (headerText != null) {
graphics.setFont(headerFont);
hRect = graphics.getFontMetrics().getStringBounds(headerText,
graphics);
headerTextSpace = (int)Math.ceil(hRect.getHeight());
availableSpace -= headerTextSpace + H_F_SPACE;
}
// if there's footer text, find out how much space is needed for it
// and subtract that from the available space
if (footerText != null) {
graphics.setFont(footerFont);
fRect = graphics.getFontMetrics().getStringBounds(footerText,
graphics);
footerTextSpace = (int)Math.ceil(fRect.getHeight());
availableSpace -= footerTextSpace + H_F_SPACE;
}
if (availableSpace <= 0) {
throw new PrinterException("Height of printable area is too small.");
}
// depending on the print mode, we may need a scale factor to
// fit the table's entire width on the page
double sf = 1.0D;
if (printMode == JTable.PrintMode.FIT_WIDTH &&
totalColWidth > imgWidth) {
// if not, we would have thrown an acception previously
assert imgWidth > 0;
// it must be, according to the if-condition, since imgWidth > 0
assert totalColWidth > 1;
sf = (double)imgWidth / (double)totalColWidth;
}
// dictated by the previous two assertions
assert sf > 0;
// This is in a loop for two reasons:
// First, it allows us to catch up in case we're called starting
// with a non-zero pageIndex. Second, we know that we can be called
// for the same page multiple times. The condition of this while
// loop acts as a check, ensuring that we don't attempt to do the
// calculations again when we are called subsequent times for the
// same page.
while (last < pageIndex) {
// if we are finished all columns in all rows
if (row >= table.getRowCount() && col == 0) {
return NO_SUCH_PAGE;
}
// rather than multiplying every row and column by the scale factor
// in findNextClip, just pass a width and height that have already
// been divided by it
int scaledWidth = (int)(imgWidth / sf);
int scaledHeight = (int)((availableSpace - hclip.height) / sf);
// calculate the area of the table to be printed for this page
findNextClip(scaledWidth, scaledHeight);
last++;
}
// create a copy of the graphics so we don't affect the one given to us
Graphics2D g2d = (Graphics2D)graphics.create();
// translate into the co-ordinate system of the pageFormat
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// to save and store the transform
AffineTransform oldTrans;
// if there's footer text, print it at the bottom of the imageable area
if (footerText != null) {
oldTrans = g2d.getTransform();
g2d.translate(0, imgHeight - footerTextSpace);
printText(g2d, footerText, fRect, footerFont, imgWidth);
g2d.setTransform(oldTrans);
}
// if there's header text, print it at the top of the imageable area
// and then translate downwards
if (headerText != null) {
printText(g2d, headerText, hRect, headerFont, imgWidth);
g2d.translate(0, headerTextSpace + H_F_SPACE);
}
// constrain the table output to the available space
tempRect.x = 0;
tempRect.y = 0;
tempRect.width = imgWidth;
tempRect.height = availableSpace;
g2d.clip(tempRect);
// if we have a scale factor, scale the graphics object to fit
// the entire width
if (sf != 1.0D) {
g2d.scale(sf, sf);
// otherwise, ensure that the current portion of the table is
// centered horizontally
} else {
int diff = (imgWidth - clip.width) / 2;
g2d.translate(diff, 0);
}
// store the old transform and clip for later restoration
oldTrans = g2d.getTransform();
Shape oldClip = g2d.getClip();
// if there's a table header, print the current section and
// then translate downwards
if (header != null) {
hclip.x = clip.x;
hclip.width = clip.width;
g2d.translate(-hclip.x, 0);
g2d.clip(hclip);
header.print(g2d);
// restore the original transform and clip
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
// translate downwards
g2d.translate(0, hclip.height);
}
// print the current section of the table
g2d.translate(-clip.x, -clip.y);
g2d.clip(clip);
table.print(g2d);
// restore the original transform and clip
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
// draw a box around the table
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
// dispose the graphics copy
g2d.dispose();
return PAGE_EXISTS;
}
/** {@collect.stats}
* A helper method that encapsulates common code for rendering the
* header and footer text.
*
* @param g2d the graphics to draw into
* @param text the text to draw, non null
* @param rect the bounding rectangle for this text,
* as calculated at the given font, non null
* @param font the font to draw the text in, non null
* @param imgWidth the width of the area to draw into
*/
private void printText(Graphics2D g2d,
String text,
Rectangle2D rect,
Font font,
int imgWidth) {
int tx;
// if the text is small enough to fit, center it
if (rect.getWidth() < imgWidth) {
tx = (int)((imgWidth - rect.getWidth()) / 2);
// otherwise, if the table is LTR, ensure the left side of
// the text shows; the right can be clipped
} else if (table.getComponentOrientation().isLeftToRight()) {
tx = 0;
// otherwise, ensure the right side of the text shows
} else {
tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
}
int ty = (int)Math.ceil(Math.abs(rect.getY()));
g2d.setColor(Color.BLACK);
g2d.setFont(font);
g2d.drawString(text, tx, ty);
}
/** {@collect.stats}
* Calculate the area of the table to be printed for
* the next page. This should only be called if there
* are rows and columns left to print.
*
* To avoid an infinite loop in printing, this will
* always put at least one cell on each page.
*
* @param pw the width of the area to print in
* @param ph the height of the area to print in
*/
private void findNextClip(int pw, int ph) {
final boolean ltr = table.getComponentOrientation().isLeftToRight();
// if we're ready to start a new set of rows
if (col == 0) {
if (ltr) {
// adjust clip to the left of the first column
clip.x = 0;
} else {
// adjust clip to the right of the first column
clip.x = totalColWidth;
}
// adjust clip to the top of the next set of rows
clip.y += clip.height;
// adjust clip width and height to be zero
clip.width = 0;
clip.height = 0;
// fit as many rows as possible, and at least one
int rowCount = table.getRowCount();
int rowHeight = table.getRowHeight(row);
do {
clip.height += rowHeight;
if (++row >= rowCount) {
break;
}
rowHeight = table.getRowHeight(row);
} while (clip.height + rowHeight <= ph);
}
// we can short-circuit for JTable.PrintMode.FIT_WIDTH since
// we'll always fit all columns on the page
if (printMode == JTable.PrintMode.FIT_WIDTH) {
clip.x = 0;
clip.width = totalColWidth;
return;
}
if (ltr) {
// adjust clip to the left of the next set of columns
clip.x += clip.width;
}
// adjust clip width to be zero
clip.width = 0;
// fit as many columns as possible, and at least one
int colCount = table.getColumnCount();
int colWidth = colModel.getColumn(col).getWidth();
do {
clip.width += colWidth;
if (!ltr) {
clip.x -= colWidth;
}
if (++col >= colCount) {
// reset col to 0 to indicate we're finished all columns
col = 0;
break;
}
colWidth = colModel.getColumn(col).getWidth();
} while (clip.width + colWidth <= pw);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* Used to display a "Tip" for a Component. Typically components provide api
* to automate the process of using <code>ToolTip</code>s.
* For example, any Swing component can use the <code>JComponent</code>
* <code>setToolTipText</code> method to specify the text
* for a standard tooltip. A component that wants to create a custom
* <code>ToolTip</code>
* display can override <code>JComponent</code>'s <code>createToolTip</code>
* method and use a subclass of this class.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How to Use Tool Tips</a>
* in <em>The Java Tutorial</em>
* for further documentation.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JComponent#setToolTipText
* @see JComponent#createToolTip
* @author Dave Moore
* @author Rich Shiavi
*/
public class JToolTip extends JComponent implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ToolTipUI";
String tipText;
JComponent component;
/** {@collect.stats} Creates a tool tip. */
public JToolTip() {
setOpaque(true);
updateUI();
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the <code>ToolTipUI</code> object that renders this component
*/
public ToolTipUI getUI() {
return (ToolTipUI)ui;
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ToolTipUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "ToolTipUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Sets the text to show when the tool tip is displayed.
* The string <code>tipText</code> may be <code>null</code>.
*
* @param tipText the <code>String</code> to display
* @beaninfo
* preferred: true
* bound: true
* description: Sets the text of the tooltip
*/
public void setTipText(String tipText) {
String oldValue = this.tipText;
this.tipText = tipText;
firePropertyChange("tiptext", oldValue, tipText);
}
/** {@collect.stats}
* Returns the text that is shown when the tool tip is displayed.
* The returned value may be <code>null</code>.
*
* @return the <code>String</code> that is displayed
*/
public String getTipText() {
return tipText;
}
/** {@collect.stats}
* Specifies the component that the tooltip describes.
* The component <code>c</code> may be <code>null</code>
* and will have no effect.
* <p>
* This is a bound property.
*
* @param c the <code>JComponent</code> being described
* @see JComponent#createToolTip
* @beaninfo
* bound: true
* description: Sets the component that the tooltip describes.
*/
public void setComponent(JComponent c) {
JComponent oldValue = this.component;
component = c;
firePropertyChange("component", oldValue, c);
}
/** {@collect.stats}
* Returns the component the tooltip applies to.
* The returned value may be <code>null</code>.
*
* @return the component that the tooltip describes
*
* @see JComponent#createToolTip
*/
public JComponent getComponent() {
return component;
}
/** {@collect.stats}
* Always returns true since tooltips, by definition,
* should always be on top of all other windows.
*/
// package private
boolean alwaysOnTop() {
return true;
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code>
* in <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JToolTip</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JToolTip</code>
*/
protected String paramString() {
String tipTextString = (tipText != null ?
tipText : "");
return super.paramString() +
",tipText=" + tipTextString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JToolTip.
* For tool tips, the AccessibleContext takes the form of an
* AccessibleJToolTip.
* A new AccessibleJToolTip instance is created if necessary.
*
* @return an AccessibleJToolTip that serves as the
* AccessibleContext of this JToolTip
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJToolTip();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JToolTip</code> class. It provides an implementation of the
* Java Accessibility API appropriate to tool tip user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJToolTip extends AccessibleJComponent {
/** {@collect.stats}
* Get the accessible description of this object.
*
* @return a localized String describing this object.
*/
public String getAccessibleDescription() {
String description = accessibleDescription;
// fallback to client property
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
if (description == null) {
description = getTipText();
}
return description;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TOOL_TIP;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.security.AccessController;
import javax.accessibility.*;
import javax.swing.plaf.RootPaneUI;
import java.util.Vector;
import java.io.Serializable;
import javax.swing.border.*;
import sun.security.action.GetBooleanAction;
/** {@collect.stats}
* A lightweight container used behind the scenes by
* <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code>,
* <code>JApplet</code>, and <code>JInternalFrame</code>.
* For task-oriented information on functionality provided by root panes
* see <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html">How to Use Root Panes</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
* The following image shows the relationships between
* the classes that use root panes.
* <p align=center><img src="doc-files/JRootPane-1.gif"
* alt="The following text describes this graphic."
* HEIGHT=484 WIDTH=629></p>
* The "heavyweight" components (those that delegate to a peer, or native
* component on the host system) are shown with a darker, heavier box. The four
* heavyweight JFC/Swing containers (<code>JFrame</code>, <code>JDialog</code>,
* <code>JWindow</code>, and <code>JApplet</code>) are
* shown in relation to the AWT classes they extend.
* These four components are the
* only heavyweight containers in the Swing library. The lightweight container
* <code>JInternalFrame</code> is also shown.
* All five of these JFC/Swing containers implement the
* <code>RootPaneContainer</code> interface,
* and they all delegate their operations to a
* <code>JRootPane</code> (shown with a little "handle" on top).
* <blockquote>
* <b>Note:</b> The <code>JComponent</code> method <code>getRootPane</code>
* can be used to obtain the <code>JRootPane</code> that contains
* a given component.
* </blockquote>
* <table align="right" border="0" summary="layout">
* <tr>
* <td align="center">
* <img src="doc-files/JRootPane-2.gif"
* alt="The following text describes this graphic." HEIGHT=386 WIDTH=349>
* </td>
* </tr>
* </table>
* The diagram at right shows the structure of a <code>JRootPane</code>.
* A <code>JRootpane</code> is made up of a <code>glassPane</code>,
* an optional <code>menuBar</code>, and a <code>contentPane</code>.
* (The <code>JLayeredPane</code> manages the <code>menuBar</code>
* and the <code>contentPane</code>.)
* The <code>glassPane</code> sits over the top of everything,
* where it is in a position to intercept mouse movements.
* Since the <code>glassPane</code> (like the <code>contentPane</code>)
* can be an arbitrary component, it is also possible to set up the
* <code>glassPane</code> for drawing. Lines and images on the
* <code>glassPane</code> can then range
* over the frames underneath without being limited by their boundaries.
* <p>
* Although the <code>menuBar</code> component is optional,
* the <code>layeredPane</code>, <code>contentPane</code>,
* and <code>glassPane</code> always exist.
* Attempting to set them to <code>null</code> generates an exception.
* <p>
* To add components to the <code>JRootPane</code> (other than the
* optional menu bar), you add the object to the <code>contentPane</code>
* of the <code>JRootPane</code>, like this:
* <pre>
* rootPane.getContentPane().add(child);
* </pre>
* The same principle holds true for setting layout managers, removing
* components, listing children, etc. All these methods are invoked on
* the <code>contentPane</code> instead of on the <code>JRootPane</code>.
* <blockquote>
* <b>Note:</b> The default layout manager for the <code>contentPane</code> is
* a <code>BorderLayout</code> manager. However, the <code>JRootPane</code>
* uses a custom <code>LayoutManager</code>.
* So, when you want to change the layout manager for the components you added
* to a <code>JRootPane</code>, be sure to use code like this:
* <pre>
* rootPane.getContentPane().setLayout(new BoxLayout());
* </pre></blockquote>
* If a <code>JMenuBar</code> component is set on the <code>JRootPane</code>,
* it is positioned along the upper edge of the frame.
* The <code>contentPane</code> is adjusted in location and size to
* fill the remaining area.
* (The <code>JMenuBar</code> and the <code>contentPane</code> are added to the
* <code>layeredPane</code> component at the
* <code>JLayeredPane.FRAME_CONTENT_LAYER</code> layer.)
* <p>
* The <code>layeredPane</code> is the parent of all children in the
* <code>JRootPane</code> -- both as the direct parent of the menu and
* the grandparent of all components added to the <code>contentPane</code>.
* It is an instance of <code>JLayeredPane</code>,
* which provides the ability to add components at several layers.
* This capability is very useful when working with menu popups,
* dialog boxes, and dragging -- situations in which you need to place
* a component on top of all other components in the pane.
* <p>
* The <code>glassPane</code> sits on top of all other components in the
* <code>JRootPane</code>.
* That provides a convenient place to draw above all other components,
* and makes it possible to intercept mouse events,
* which is useful both for dragging and for drawing.
* Developers can use <code>setVisible</code> on the <code>glassPane</code>
* to control when the <code>glassPane</code> displays over the other children.
* By default the <code>glassPane</code> is not visible.
* <p>
* The custom <code>LayoutManager</code> used by <code>JRootPane</code>
* ensures that:
* <OL>
* <LI>The <code>glassPane</code> fills the entire viewable
* area of the <code>JRootPane</code> (bounds - insets).
* <LI>The <code>layeredPane</code> fills the entire viewable area of the
* <code>JRootPane</code>. (bounds - insets)
* <LI>The <code>menuBar</code> is positioned at the upper edge of the
* <code>layeredPane</code>.
* <LI>The <code>contentPane</code> fills the entire viewable area,
* minus the <code>menuBar</code>, if present.
* </OL>
* Any other views in the <code>JRootPane</code> view hierarchy are ignored.
* <p>
* If you replace the <code>LayoutManager</code> of the <code>JRootPane</code>,
* you are responsible for managing all of these views.
* So ordinarily you will want to be sure that you
* change the layout manager for the <code>contentPane</code> rather than
* for the <code>JRootPane</code> itself!
* <p>
* The painting architecture of Swing requires an opaque
* <code>JComponent</code>
* to exist in the containment hieararchy above all other components. This is
* typically provided by way of the content pane. If you replace the content
* pane, it is recommended that you make the content pane opaque
* by way of <code>setOpaque(true)</code>. Additionally, if the content pane
* overrides <code>paintComponent</code>, it
* will need to completely fill in the background in an opaque color in
* <code>paintComponent</code>.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JLayeredPane
* @see JMenuBar
* @see JWindow
* @see JFrame
* @see JDialog
* @see JApplet
* @see JInternalFrame
* @see JComponent
* @see BoxLayout
*
* @see <a href="http://java.sun.com/products/jfc/tsc/articles/mixing/">
* Mixing Heavy and Light Components</a>
*
* @author David Kloba
*/
/// PENDING(klobad) Who should be opaque in this component?
public class JRootPane extends JComponent implements Accessible {
private static final String uiClassID = "RootPaneUI";
/** {@collect.stats}
* Whether or not we should dump the stack when true double buffering
* is disabled. Default is false.
*/
private static final boolean LOG_DISABLE_TRUE_DOUBLE_BUFFERING;
/** {@collect.stats}
* Whether or not we should ignore requests to disable true double
* buffering. Default is false.
*/
private static final boolean IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should not provide any sort of
* Window decorations.
*
* @since 1.4
*/
public static final int NONE = 0;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Frame.
*
* @since 1.4
*/
public static final int FRAME = 1;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog.
*
* @since 1.4
*/
public static final int PLAIN_DIALOG = 2;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to display an informational message.
*
* @since 1.4
*/
public static final int INFORMATION_DIALOG = 3;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to display an error message.
*
* @since 1.4
*/
public static final int ERROR_DIALOG = 4;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to display a <code>JColorChooser</code>.
*
* @since 1.4
*/
public static final int COLOR_CHOOSER_DIALOG = 5;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to display a <code>JFileChooser</code>.
*
* @since 1.4
*/
public static final int FILE_CHOOSER_DIALOG = 6;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to present a question to the user.
*
* @since 1.4
*/
public static final int QUESTION_DIALOG = 7;
/** {@collect.stats}
* Constant used for the windowDecorationStyle property. Indicates that
* the <code>JRootPane</code> should provide decorations appropriate for
* a Dialog used to display a warning message.
*
* @since 1.4
*/
public static final int WARNING_DIALOG = 8;
private int windowDecorationStyle;
/** {@collect.stats} The menu bar. */
protected JMenuBar menuBar;
/** {@collect.stats} The content pane. */
protected Container contentPane;
/** {@collect.stats} The layered pane that manages the menu bar and content pane. */
protected JLayeredPane layeredPane;
/** {@collect.stats}
* The glass pane that overlays the menu bar and content pane,
* so it can intercept mouse movements and such.
*/
protected Component glassPane;
/** {@collect.stats}
* The button that gets activated when the pane has the focus and
* a UI-specific action like pressing the <b>Enter</b> key occurs.
*/
protected JButton defaultButton;
/** {@collect.stats}
* As of Java 2 platform v1.3 this unusable field is no longer used.
* To override the default button you should replace the <code>Action</code>
* in the <code>JRootPane</code>'s <code>ActionMap</code>. Please refer to
* the key bindings specification for further details.
*
* @deprecated As of Java 2 platform v1.3.
* @see #defaultButton
*/
@Deprecated
protected DefaultAction defaultPressAction;
/** {@collect.stats}
* As of Java 2 platform v1.3 this unusable field is no longer used.
* To override the default button you should replace the <code>Action</code>
* in the <code>JRootPane</code>'s <code>ActionMap</code>. Please refer to
* the key bindings specification for further details.
*
* @deprecated As of Java 2 platform v1.3.
* @see #defaultButton
*/
@Deprecated
protected DefaultAction defaultReleaseAction;
/** {@collect.stats}
* Whether or not true double buffering should be used. This is typically
* true, but may be set to false in special situations. For example,
* heavy weight popups (backed by a window) set this to false.
*/
boolean useTrueDoubleBuffering = true;
static {
LOG_DISABLE_TRUE_DOUBLE_BUFFERING =
AccessController.doPrivileged(new GetBooleanAction(
"swing.logDoubleBufferingDisable"));
IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING =
AccessController.doPrivileged(new GetBooleanAction(
"swing.ignoreDoubleBufferingDisable"));
}
/** {@collect.stats}
* Creates a <code>JRootPane</code>, setting up its
* <code>glassPane</code>, <code>layeredPane</code>,
* and <code>contentPane</code>.
*/
public JRootPane() {
setGlassPane(createGlassPane());
setLayeredPane(createLayeredPane());
setContentPane(createContentPane());
setLayout(createRootLayout());
setDoubleBuffered(true);
updateUI();
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void setDoubleBuffered(boolean aFlag) {
if (isDoubleBuffered() != aFlag) {
super.setDoubleBuffered(aFlag);
RepaintManager.currentManager(this).doubleBufferingChanged(this);
}
}
/** {@collect.stats}
* Returns a constant identifying the type of Window decorations the
* <code>JRootPane</code> is providing.
*
* @return One of <code>NONE</code>, <code>FRAME</code>,
* <code>PLAIN_DIALOG</code>, <code>INFORMATION_DIALOG</code>,
* <code>ERROR_DIALOG</code>, <code>COLOR_CHOOSER_DIALOG</code>,
* <code>FILE_CHOOSER_DIALOG</code>, <code>QUESTION_DIALOG</code> or
* <code>WARNING_DIALOG</code>.
* @see #setWindowDecorationStyle
* @since 1.4
*/
public int getWindowDecorationStyle() {
return windowDecorationStyle;
}
/** {@collect.stats}
* Sets the type of Window decorations (such as borders, widgets for
* closing a Window, title ...) the <code>JRootPane</code> should
* provide. The default is to provide no Window decorations
* (<code>NONE</code>).
* <p>
* This is only a hint, and some look and feels may not support
* this.
* This is a bound property.
*
* @param windowDecorationStyle Constant identifying Window decorations
* to provide.
* @see JDialog#setDefaultLookAndFeelDecorated
* @see JFrame#setDefaultLookAndFeelDecorated
* @see LookAndFeel#getSupportsWindowDecorations
* @throws IllegalArgumentException if <code>style</code> is
* not one of: <code>NONE</code>, <code>FRAME</code>,
* <code>PLAIN_DIALOG</code>, <code>INFORMATION_DIALOG</code>,
* <code>ERROR_DIALOG</code>, <code>COLOR_CHOOSER_DIALOG</code>,
* <code>FILE_CHOOSER_DIALOG</code>, <code>QUESTION_DIALOG</code>, or
* <code>WARNING_DIALOG</code>.
* @since 1.4
* @beaninfo
* bound: true
* enum: NONE JRootPane.NONE
* FRAME JRootPane.FRAME
* PLAIN_DIALOG JRootPane.PLAIN_DIALOG
* INFORMATION_DIALOG JRootPane.INFORMATION_DIALOG
* ERROR_DIALOG JRootPane.ERROR_DIALOG
* COLOR_CHOOSER_DIALOG JRootPane.COLOR_CHOOSER_DIALOG
* FILE_CHOOSER_DIALOG JRootPane.FILE_CHOOSER_DIALOG
* QUESTION_DIALOG JRootPane.QUESTION_DIALOG
* WARNING_DIALOG JRootPane.WARNING_DIALOG
* expert: true
* attribute: visualUpdate true
* description: Identifies the type of Window decorations to provide
*/
public void setWindowDecorationStyle(int windowDecorationStyle) {
if (windowDecorationStyle < 0 ||
windowDecorationStyle > WARNING_DIALOG) {
throw new IllegalArgumentException("Invalid decoration style");
}
int oldWindowDecorationStyle = getWindowDecorationStyle();
this.windowDecorationStyle = windowDecorationStyle;
firePropertyChange("windowDecorationStyle",
oldWindowDecorationStyle,
windowDecorationStyle);
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return <code>LabelUI</code> object
* @since 1.3
*/
public RootPaneUI getUI() {
return (RootPaneUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>LabelUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* expert: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
* @since 1.3
*/
public void setUI(RootPaneUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((RootPaneUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns a string that specifies the name of the L&F class
* that renders this component.
*
* @return the string "RootPaneUI"
*
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>layeredPane</code>.
* Bt default it creates a new <code>JLayeredPane</code>.
* @return the default <code>layeredPane</code>
*/
protected JLayeredPane createLayeredPane() {
JLayeredPane p = new JLayeredPane();
p.setName(this.getName()+".layeredPane");
return p;
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>contentPane</code>.
* By default this method creates a new <code>JComponent</code> add sets a
* <code>BorderLayout</code> as its <code>LayoutManager</code>.
* @return the default <code>contentPane</code>
*/
protected Container createContentPane() {
JComponent c = new JPanel();
c.setName(this.getName()+".contentPane");
c.setLayout(new BorderLayout() {
/* This BorderLayout subclass maps a null constraint to CENTER.
* Although the reference BorderLayout also does this, some VMs
* throw an IllegalArgumentException.
*/
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints == null) {
constraints = BorderLayout.CENTER;
}
super.addLayoutComponent(comp, constraints);
}
});
return c;
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>glassPane</code>.
* By default this method creates a new <code>JComponent</code>
* with visibility set to false.
* @return the default <code>glassPane</code>
*/
protected Component createGlassPane() {
JComponent c = new JPanel();
c.setName(this.getName()+".glassPane");
c.setVisible(false);
((JPanel)c).setOpaque(false);
return c;
}
/** {@collect.stats}
* Called by the constructor methods to create the default
* <code>layoutManager</code>.
* @return the default <code>layoutManager</code>.
*/
protected LayoutManager createRootLayout() {
return new RootLayout();
}
/** {@collect.stats}
* Adds or changes the menu bar used in the layered pane.
* @param menu the <code>JMenuBar</code> to add
*/
public void setJMenuBar(JMenuBar menu) {
if(menuBar != null && menuBar.getParent() == layeredPane)
layeredPane.remove(menuBar);
menuBar = menu;
if(menuBar != null)
layeredPane.add(menuBar, JLayeredPane.FRAME_CONTENT_LAYER);
}
/** {@collect.stats}
* Specifies the menu bar value.
* @deprecated As of Swing version 1.0.3
* replaced by <code>setJMenuBar(JMenuBar menu)</code>.
* @param menu the <code>JMenuBar</code> to add.
*/
@Deprecated
public void setMenuBar(JMenuBar menu){
if(menuBar != null && menuBar.getParent() == layeredPane)
layeredPane.remove(menuBar);
menuBar = menu;
if(menuBar != null)
layeredPane.add(menuBar, JLayeredPane.FRAME_CONTENT_LAYER);
}
/** {@collect.stats}
* Returns the menu bar from the layered pane.
* @return the <code>JMenuBar</code> used in the pane
*/
public JMenuBar getJMenuBar() { return menuBar; }
/** {@collect.stats}
* Returns the menu bar value.
* @deprecated As of Swing version 1.0.3
* replaced by <code>getJMenuBar()</code>.
* @return the <code>JMenuBar</code> used in the pane
*/
@Deprecated
public JMenuBar getMenuBar() { return menuBar; }
/** {@collect.stats}
* Sets the content pane -- the container that holds the components
* parented by the root pane.
* <p>
* Swing's painting architecture requires an opaque <code>JComponent</code>
* in the containment hiearchy. This is typically provided by the
* content pane. If you replace the content pane it is recommended you
* replace it with an opaque <code>JComponent</code>.
*
* @param content the <code>Container</code> to use for component-contents
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
*/
public void setContentPane(Container content) {
if(content == null)
throw new IllegalComponentStateException("contentPane cannot be set to null.");
if(contentPane != null && contentPane.getParent() == layeredPane)
layeredPane.remove(contentPane);
contentPane = content;
layeredPane.add(contentPane, JLayeredPane.FRAME_CONTENT_LAYER);
}
/** {@collect.stats}
* Returns the content pane -- the container that holds the components
* parented by the root pane.
*
* @return the <code>Container</code> that holds the component-contents
*/
public Container getContentPane() { return contentPane; }
// PENDING(klobad) Should this reparent the contentPane and MenuBar?
/** {@collect.stats}
* Sets the layered pane for the root pane. The layered pane
* typically holds a content pane and an optional <code>JMenuBar</code>.
*
* @param layered the <code>JLayeredPane</code> to use
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is <code>null</code>
*/
public void setLayeredPane(JLayeredPane layered) {
if(layered == null)
throw new IllegalComponentStateException("layeredPane cannot be set to null.");
if(layeredPane != null && layeredPane.getParent() == this)
this.remove(layeredPane);
layeredPane = layered;
this.add(layeredPane, -1);
}
/** {@collect.stats}
* Gets the layered pane used by the root pane. The layered pane
* typically holds a content pane and an optional <code>JMenuBar</code>.
*
* @return the <code>JLayeredPane</code> currently in use
*/
public JLayeredPane getLayeredPane() { return layeredPane; }
/** {@collect.stats}
* Sets a specified <code>Component</code> to be the glass pane for this
* root pane. The glass pane should normally be a lightweight,
* transparent component, because it will be made visible when
* ever the root pane needs to grab input events.
* <p>
* The new glass pane's visibility is changed to match that of
* the current glass pane. An implication of this is that care
* must be taken when you want to replace the glass pane and
* make it visible. Either of the following will work:
* <pre>
* root.setGlassPane(newGlassPane);
* newGlassPane.setVisible(true);
* </pre>
* or:
* <pre>
* root.getGlassPane().setVisible(true);
* root.setGlassPane(newGlassPane);
* </pre>
*
* @param glass the <code>Component</code> to use as the glass pane
* for this <code>JRootPane</code>
* @exception NullPointerException if the <code>glass</code> parameter is
* <code>null</code>
*/
public void setGlassPane(Component glass) {
if (glass == null) {
throw new NullPointerException("glassPane cannot be set to null.");
}
boolean visible = false;
if (glassPane != null && glassPane.getParent() == this) {
this.remove(glassPane);
visible = glassPane.isVisible();
}
glass.setVisible(visible);
glassPane = glass;
this.add(glassPane, 0);
if (visible) {
repaint();
}
}
/** {@collect.stats}
* Returns the current glass pane for this <code>JRootPane</code>.
* @return the current glass pane
* @see #setGlassPane
*/
public Component getGlassPane() {
return glassPane;
}
/** {@collect.stats}
* If a descendant of this <code>JRootPane</code> calls
* <code>revalidate</code>, validate from here on down.
*<p>
* Deferred requests to layout a component and its descendents again.
* For example, calls to <code>revalidate</code>, are pushed upwards to
* either a <code>JRootPane</code> or a <code>JScrollPane</code>
* because both classes override <code>isValidateRoot</code> to return true.
*
* @see JComponent#isValidateRoot
* @return true
*/
public boolean isValidateRoot() {
return true;
}
/** {@collect.stats}
* The <code>glassPane</code> and <code>contentPane</code>
* have the same bounds, which means <code>JRootPane</code>
* does not tiles its children and this should return false.
* On the other hand, the <code>glassPane</code>
* is normally not visible, and so this can return true if the
* <code>glassPane</code> isn't visible. Therefore, the
* return value here depends upon the visiblity of the
* <code>glassPane</code>.
*
* @return true if this component's children don't overlap
*/
public boolean isOptimizedDrawingEnabled() {
return !glassPane.isVisible();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void addNotify() {
super.addNotify();
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public void removeNotify() {
super.removeNotify();
}
/** {@collect.stats}
* Sets the <code>defaultButton</code> property,
* which determines the current default button for this <code>JRootPane</code>.
* The default button is the button which will be activated
* when a UI-defined activation event (typically the <b>Enter</b> key)
* occurs in the root pane regardless of whether or not the button
* has keyboard focus (unless there is another component within
* the root pane which consumes the activation event,
* such as a <code>JTextPane</code>).
* For default activation to work, the button must be an enabled
* descendent of the root pane when activation occurs.
* To remove a default button from this root pane, set this
* property to <code>null</code>.
*
* @see JButton#isDefaultButton
* @param defaultButton the <code>JButton</code> which is to be the default button
*
* @beaninfo
* description: The button activated by default in this root pane
*/
public void setDefaultButton(JButton defaultButton) {
JButton oldDefault = this.defaultButton;
if (oldDefault != defaultButton) {
this.defaultButton = defaultButton;
if (oldDefault != null) {
oldDefault.repaint();
}
if (defaultButton != null) {
defaultButton.repaint();
}
}
firePropertyChange("defaultButton", oldDefault, defaultButton);
}
/** {@collect.stats}
* Returns the value of the <code>defaultButton</code> property.
* @return the <code>JButton</code> which is currently the default button
* @see #setDefaultButton
*/
public JButton getDefaultButton() {
return defaultButton;
}
final void setUseTrueDoubleBuffering(boolean useTrueDoubleBuffering) {
this.useTrueDoubleBuffering = useTrueDoubleBuffering;
}
final boolean getUseTrueDoubleBuffering() {
return useTrueDoubleBuffering;
}
final void disableTrueDoubleBuffering() {
if (useTrueDoubleBuffering) {
if (!IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING) {
if (LOG_DISABLE_TRUE_DOUBLE_BUFFERING) {
System.out.println("Disabling true double buffering for " +
this);
Thread.dumpStack();
}
useTrueDoubleBuffering = false;
RepaintManager.currentManager(this).
doubleBufferingChanged(this);
}
}
}
static class DefaultAction extends AbstractAction {
JButton owner;
JRootPane root;
boolean press;
DefaultAction(JRootPane root, boolean press) {
this.root = root;
this.press = press;
}
public void setOwner(JButton owner) {
this.owner = owner;
}
public void actionPerformed(ActionEvent e) {
if (owner != null && SwingUtilities.getRootPane(owner) == root) {
ButtonModel model = owner.getModel();
if (press) {
model.setArmed(true);
model.setPressed(true);
} else {
model.setPressed(false);
}
}
}
public boolean isEnabled() {
return owner.getModel().isEnabled();
}
}
/** {@collect.stats}
* Overridden to enforce the position of the glass component as
* the zero child.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
*/
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
/// We are making sure the glassPane is on top.
if(glassPane != null
&& glassPane.getParent() == this
&& getComponent(0) != glassPane) {
add(glassPane, 0);
}
}
///////////////////////////////////////////////////////////////////////////////
//// Begin Inner Classes
///////////////////////////////////////////////////////////////////////////////
/** {@collect.stats}
* A custom layout manager that is responsible for the layout of
* layeredPane, glassPane, and menuBar.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class RootLayout implements LayoutManager2, Serializable
{
/** {@collect.stats}
* Returns the amount of space the layout would like to have.
*
* @param parent the Container for which this layout manager
* is being used
* @return a Dimension object containing the layout's preferred size
*/
public Dimension preferredLayoutSize(Container parent) {
Dimension rd, mbd;
Insets i = getInsets();
if(contentPane != null) {
rd = contentPane.getPreferredSize();
} else {
rd = parent.getSize();
}
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getPreferredSize();
} else {
mbd = new Dimension(0, 0);
}
return new Dimension(Math.max(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
/** {@collect.stats}
* Returns the minimum amount of space the layout needs.
*
* @param parent the Container for which this layout manager
* is being used
* @return a Dimension object containing the layout's minimum size
*/
public Dimension minimumLayoutSize(Container parent) {
Dimension rd, mbd;
Insets i = getInsets();
if(contentPane != null) {
rd = contentPane.getMinimumSize();
} else {
rd = parent.getSize();
}
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getMinimumSize();
} else {
mbd = new Dimension(0, 0);
}
return new Dimension(Math.max(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
/** {@collect.stats}
* Returns the maximum amount of space the layout can use.
*
* @param target the Container for which this layout manager
* is being used
* @return a Dimension object containing the layout's maximum size
*/
public Dimension maximumLayoutSize(Container target) {
Dimension rd, mbd;
Insets i = getInsets();
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getMaximumSize();
} else {
mbd = new Dimension(0, 0);
}
if(contentPane != null) {
rd = contentPane.getMaximumSize();
} else {
// This is silly, but should stop an overflow error
rd = new Dimension(Integer.MAX_VALUE,
Integer.MAX_VALUE - i.top - i.bottom - mbd.height - 1);
}
return new Dimension(Math.min(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
/** {@collect.stats}
* Instructs the layout manager to perform the layout for the specified
* container.
*
* @param parent the Container for which this layout manager
* is being used
*/
public void layoutContainer(Container parent) {
Rectangle b = parent.getBounds();
Insets i = getInsets();
int contentY = 0;
int w = b.width - i.right - i.left;
int h = b.height - i.top - i.bottom;
if(layeredPane != null) {
layeredPane.setBounds(i.left, i.top, w, h);
}
if(glassPane != null) {
glassPane.setBounds(i.left, i.top, w, h);
}
// Note: This is laying out the children in the layeredPane,
// technically, these are not our children.
if(menuBar != null && menuBar.isVisible()) {
Dimension mbd = menuBar.getPreferredSize();
menuBar.setBounds(0, 0, w, mbd.height);
contentY += mbd.height;
}
if(contentPane != null) {
contentPane.setBounds(0, contentY, w, h - contentY);
}
}
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public void addLayoutComponent(Component comp, Object constraints) {}
public float getLayoutAlignmentX(Container target) { return 0.0f; }
public float getLayoutAlignmentY(Container target) { return 0.0f; }
public void invalidateLayout(Container target) {}
}
/** {@collect.stats}
* Returns a string representation of this <code>JRootPane</code>.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JRootPane</code>.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JRootPane</code>. For root panes, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJRootPane</code>.
* A new <code>AccessibleJRootPane</code> instance is created if necessary.
*
* @return an <code>AccessibleJRootPane</code> that serves as the
* <code>AccessibleContext</code> of this <code>JRootPane</code>
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJRootPane();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JRootPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to root pane user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJRootPane extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of
* the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.ROOT_PANE;
}
/** {@collect.stats}
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
return super.getAccessibleChildrenCount();
}
/** {@collect.stats}
* Returns the specified Accessible child of the object. The Accessible
* children of an Accessible object are zero-based, so the first child
* of an Accessible child is at index 0, the second child is at index 1,
* and so on.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @see #getAccessibleChildrenCount
*/
public Accessible getAccessibleChild(int i) {
return super.getAccessibleChild(i);
}
} // inner class AccessibleJRootPane
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.image.*;
/** {@collect.stats} Color filter for DebugGraphics, used for images only.
*
* @author Dave Karlton
*/
class DebugGraphicsFilter extends RGBImageFilter {
Color color;
DebugGraphicsFilter(Color c) {
canFilterIndexColorModel = true;
color = c;
}
public int filterRGB(int x, int y, int rgb) {
return color.getRGB() | (rgb & 0xFF000000);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.beans.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.accessibility.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.text.NumberFormat;
import java.text.DateFormat;
import java.text.MessageFormat;
import javax.print.attribute.*;
import javax.print.PrintService;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
import static sun.swing.SwingUtilities2.Section.*;
import sun.swing.PrintingStatus;
import sun.swing.SwingLazyValue;
/** {@collect.stats}
* The <code>JTable</code> is used to display and edit regular two-dimensional tables
* of cells.
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html">How to Use Tables</a>
* in <em>The Java Tutorial</em>
* for task-oriented documentation and examples of using <code>JTable</code>.
*
* <p>
* The <code>JTable</code> has many
* facilities that make it possible to customize its rendering and editing
* but provides defaults for these features so that simple tables can be
* set up easily. For example, to set up a table with 10 rows and 10
* columns of numbers:
* <p>
* <pre>
* TableModel dataModel = new AbstractTableModel() {
* public int getColumnCount() { return 10; }
* public int getRowCount() { return 10;}
* public Object getValueAt(int row, int col) { return new Integer(row*col); }
* };
* JTable table = new JTable(dataModel);
* JScrollPane scrollpane = new JScrollPane(table);
* </pre>
* <p>
* {@code JTable}s are typically placed inside of a {@code JScrollPane}. By
* default, a {@code JTable} will adjust its width such that
* a horizontal scrollbar is unnecessary. To allow for a horizontal scrollbar,
* invoke {@link #setAutoResizeMode} with {@code AUTO_RESIZE_OFF}.
* Note that if you wish to use a <code>JTable</code> in a standalone
* view (outside of a <code>JScrollPane</code>) and want the header
* displayed, you can get it using {@link #getTableHeader} and
* display it separately.
* <p>
* To enable sorting and filtering of rows, use a
* {@code RowSorter}.
* You can set up a row sorter in either of two ways:
* <ul>
* <li>Directly set the {@code RowSorter}. For example:
* {@code table.setRowSorter(new TableRowSorter(model))}.
* <li>Set the {@code autoCreateRowSorter}
* property to {@code true}, so that the {@code JTable}
* creates a {@code RowSorter} for
* you. For example: {@code setAutoCreateRowSorter(true)}.
* </ul>
* <p>
* When designing applications that use the <code>JTable</code> it is worth paying
* close attention to the data structures that will represent the table's data.
* The <code>DefaultTableModel</code> is a model implementation that
* uses a <code>Vector</code> of <code>Vector</code>s of <code>Object</code>s to
* store the cell values. As well as copying the data from an
* application into the <code>DefaultTableModel</code>,
* it is also possible to wrap the data in the methods of the
* <code>TableModel</code> interface so that the data can be passed to the
* <code>JTable</code> directly, as in the example above. This often results
* in more efficient applications because the model is free to choose the
* internal representation that best suits the data.
* A good rule of thumb for deciding whether to use the <code>AbstractTableModel</code>
* or the <code>DefaultTableModel</code> is to use the <code>AbstractTableModel</code>
* as the base class for creating subclasses and the <code>DefaultTableModel</code>
* when subclassing is not required.
* <p>
* The "TableExample" directory in the demo area of the source distribution
* gives a number of complete examples of <code>JTable</code> usage,
* covering how the <code>JTable</code> can be used to provide an
* editable view of data taken from a database and how to modify
* the columns in the display to use specialized renderers and editors.
* <p>
* The <code>JTable</code> uses integers exclusively to refer to both the rows and the columns
* of the model that it displays. The <code>JTable</code> simply takes a tabular range of cells
* and uses <code>getValueAt(int, int)</code> to retrieve the
* values from the model during painting. It is important to remember that
* the column and row indexes returned by various <code>JTable</code> methods
* are in terms of the <code>JTable</code> (the view) and are not
* necessarily the same indexes used by the model.
* <p>
* By default, columns may be rearranged in the <code>JTable</code> so that the
* view's columns appear in a different order to the columns in the model.
* This does not affect the implementation of the model at all: when the
* columns are reordered, the <code>JTable</code> maintains the new order of the columns
* internally and converts its column indices before querying the model.
* <p>
* So, when writing a <code>TableModel</code>, it is not necessary to listen for column
* reordering events as the model will be queried in its own coordinate
* system regardless of what is happening in the view.
* In the examples area there is a demonstration of a sorting algorithm making
* use of exactly this technique to interpose yet another coordinate system
* where the order of the rows is changed, rather than the order of the columns.
* <p>
* Similarly when using the sorting and filtering functionality
* provided by <code>RowSorter</code> the underlying
* <code>TableModel</code> does not need to know how to do sorting,
* rather <code>RowSorter</code> will handle it. Coordinate
* conversions will be necessary when using the row based methods of
* <code>JTable</code> with the underlying <code>TableModel</code>.
* All of <code>JTable</code>s row based methods are in terms of the
* <code>RowSorter</code>, which is not necessarily the same as that
* of the underlying <code>TableModel</code>. For example, the
* selection is always in terms of <code>JTable</code> so that when
* using <code>RowSorter</code> you will need to convert using
* <code>convertRowIndexToView</code> or
* <code>convertRowIndexToModel</code>. The following shows how to
* convert coordinates from <code>JTable</code> to that of the
* underlying model:
* <pre>
* int[] selection = table.getSelectedRows();
* for (int i = 0; i < selection.length; i++) {
* selection[i] = table.convertRowIndexToModel(selection[i]);
* }
* // selection is now in terms of the underlying TableModel
* </pre>
* <p>
* By default if sorting is enabled <code>JTable</code> will persist the
* selection and variable row heights in terms of the model on
* sorting. For example if row 0, in terms of the underlying model,
* is currently selected, after the sort row 0, in terms of the
* underlying model will be selected. Visually the selection may
* change, but in terms of the underlying model it will remain the
* same. The one exception to that is if the model index is no longer
* visible or was removed. For example, if row 0 in terms of model
* was filtered out the selection will be empty after the sort.
* <p>
* J2SE 5 adds methods to <code>JTable</code> to provide convenient access to some
* common printing needs. Simple new {@link #print()} methods allow for quick
* and easy addition of printing support to your application. In addition, a new
* {@link #getPrintable} method is available for more advanced printing needs.
* <p>
* As for all <code>JComponent</code> classes, you can use
* {@link InputMap} and {@link ActionMap} to associate an
* {@link Action} object with a {@link KeyStroke} and execute the
* action under specified conditions.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
*
* @beaninfo
* attribute: isContainer false
* description: A component which displays data in a two dimensional grid.
*
* @author Philip Milne
* @author Shannon Hickey (printing support)
* @see javax.swing.table.DefaultTableModel
* @see javax.swing.table.TableRowSorter
*/
/* The first versions of the JTable, contained in Swing-0.1 through
* Swing-0.4, were written by Alan Chung.
*/
public class JTable extends JComponent implements TableModelListener, Scrollable,
TableColumnModelListener, ListSelectionListener, CellEditorListener,
Accessible, RowSorterListener
{
//
// Static Constants
//
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TableUI";
/** {@collect.stats} Do not adjust column widths automatically; use a horizontal scrollbar instead. */
public static final int AUTO_RESIZE_OFF = 0;
/** {@collect.stats} When a column is adjusted in the UI, adjust the next column the opposite way. */
public static final int AUTO_RESIZE_NEXT_COLUMN = 1;
/** {@collect.stats} During UI adjustment, change subsequent columns to preserve the total width;
* this is the default behavior. */
public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNS = 2;
/** {@collect.stats} During all resize operations, apply adjustments to the last column only. */
public static final int AUTO_RESIZE_LAST_COLUMN = 3;
/** {@collect.stats} During all resize operations, proportionately resize all columns. */
public static final int AUTO_RESIZE_ALL_COLUMNS = 4;
/** {@collect.stats}
* Printing modes, used in printing <code>JTable</code>s.
*
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean)
* @see #getPrintable
* @since 1.5
*/
public enum PrintMode {
/** {@collect.stats}
* Printing mode that prints the table at its current size,
* spreading both columns and rows across multiple pages if necessary.
*/
NORMAL,
/** {@collect.stats}
* Printing mode that scales the output smaller, if necessary,
* to fit the table's entire width (and thereby all columns) on each page;
* Rows are spread across multiple pages as necessary.
*/
FIT_WIDTH
}
//
// Instance Variables
//
/** {@collect.stats} The <code>TableModel</code> of the table. */
protected TableModel dataModel;
/** {@collect.stats} The <code>TableColumnModel</code> of the table. */
protected TableColumnModel columnModel;
/** {@collect.stats} The <code>ListSelectionModel</code> of the table, used to keep track of row selections. */
protected ListSelectionModel selectionModel;
/** {@collect.stats} The <code>TableHeader</code> working with the table. */
protected JTableHeader tableHeader;
/** {@collect.stats} The height in pixels of each row in the table. */
protected int rowHeight;
/** {@collect.stats} The height in pixels of the margin between the cells in each row. */
protected int rowMargin;
/** {@collect.stats} The color of the grid. */
protected Color gridColor;
/** {@collect.stats} The table draws horizontal lines between cells if <code>showHorizontalLines</code> is true. */
protected boolean showHorizontalLines;
/** {@collect.stats} The table draws vertical lines between cells if <code>showVerticalLines</code> is true. */
protected boolean showVerticalLines;
/** {@collect.stats}
* Determines if the table automatically resizes the
* width of the table's columns to take up the entire width of the
* table, and how it does the resizing.
*/
protected int autoResizeMode;
/** {@collect.stats}
* The table will query the <code>TableModel</code> to build the default
* set of columns if this is true.
*/
protected boolean autoCreateColumnsFromModel;
/** {@collect.stats} Used by the <code>Scrollable</code> interface to determine the initial visible area. */
protected Dimension preferredViewportSize;
/** {@collect.stats} True if row selection is allowed in this table. */
protected boolean rowSelectionAllowed;
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use the
* <code>rowSelectionAllowed</code> property and the
* <code>columnSelectionAllowed</code> property of the
* <code>columnModel</code> instead. Or use the
* method <code>getCellSelectionEnabled</code>.
*/
/*
* If true, both a row selection and a column selection
* can be non-empty at the same time, the selected cells are the
* the cells whose row and column are both selected.
*/
protected boolean cellSelectionEnabled;
/** {@collect.stats} If editing, the <code>Component</code> that is handling the editing. */
transient protected Component editorComp;
/** {@collect.stats}
* The active cell editor object, that overwrites the screen real estate
* occupied by the current cell and allows the user to change its contents.
* {@code null} if the table isn't currently editing.
*/
transient protected TableCellEditor cellEditor;
/** {@collect.stats} Identifies the column of the cell being edited. */
transient protected int editingColumn;
/** {@collect.stats} Identifies the row of the cell being edited. */
transient protected int editingRow;
/** {@collect.stats}
* A table of objects that display the contents of a cell,
* indexed by class as declared in <code>getColumnClass</code>
* in the <code>TableModel</code> interface.
*/
transient protected Hashtable defaultRenderersByColumnClass;
/** {@collect.stats}
* A table of objects that display and edit the contents of a cell,
* indexed by class as declared in <code>getColumnClass</code>
* in the <code>TableModel</code> interface.
*/
transient protected Hashtable defaultEditorsByColumnClass;
/** {@collect.stats} The foreground color of selected cells. */
protected Color selectionForeground;
/** {@collect.stats} The background color of selected cells. */
protected Color selectionBackground;
//
// Private state
//
// WARNING: If you directly access this field you should also change the
// SortManager.modelRowSizes field as well.
private SizeSequence rowModel;
private boolean dragEnabled;
private boolean surrendersFocusOnKeystroke;
private PropertyChangeListener editorRemover = null;
/** {@collect.stats}
* The last value of getValueIsAdjusting from the column selection models
* columnSelectionChanged notification. Used to test if a repaint is
* needed.
*/
private boolean columnSelectionAdjusting;
/** {@collect.stats}
* The last value of getValueIsAdjusting from the row selection models
* valueChanged notification. Used to test if a repaint is needed.
*/
private boolean rowSelectionAdjusting;
/** {@collect.stats}
* To communicate errors between threads during printing.
*/
private Throwable printError;
/** {@collect.stats}
* True when setRowHeight(int) has been invoked.
*/
private boolean isRowHeightSet;
/** {@collect.stats}
* If true, on a sort the selection is reset.
*/
private boolean updateSelectionOnSort;
/** {@collect.stats}
* Information used in sorting.
*/
private transient SortManager sortManager;
/** {@collect.stats}
* If true, when sorterChanged is invoked it's value is ignored.
*/
private boolean ignoreSortChange;
/** {@collect.stats}
* Whether or not sorterChanged has been invoked.
*/
private boolean sorterChanged;
/** {@collect.stats}
* If true, any time the model changes a new RowSorter is set.
*/
private boolean autoCreateRowSorter;
/** {@collect.stats}
* Whether or not the table always fills the viewport height.
* @see #setFillsViewportHeight
* @see #getScrollableTracksViewportHeight
*/
private boolean fillsViewportHeight;
/** {@collect.stats}
* The drop mode for this component.
*/
private DropMode dropMode = DropMode.USE_SELECTION;
/** {@collect.stats}
* The drop location.
*/
private transient DropLocation dropLocation;
/** {@collect.stats}
* A subclass of <code>TransferHandler.DropLocation</code> representing
* a drop location for a <code>JTable</code>.
*
* @see #getDropLocation
* @since 1.6
*/
public static final class DropLocation extends TransferHandler.DropLocation {
private final int row;
private final int col;
private final boolean isInsertRow;
private final boolean isInsertCol;
private DropLocation(Point p, int row, int col,
boolean isInsertRow, boolean isInsertCol) {
super(p);
this.row = row;
this.col = col;
this.isInsertRow = isInsertRow;
this.isInsertCol = isInsertCol;
}
/** {@collect.stats}
* Returns the row index where a dropped item should be placed in the
* table. Interpretation of the value depends on the return of
* <code>isInsertRow()</code>. If that method returns
* <code>true</code> this value indicates the index where a new
* row should be inserted. Otherwise, it represents the value
* of an existing row on which the data was dropped. This index is
* in terms of the view.
* <p>
* <code>-1</code> indicates that the drop occurred over empty space,
* and no row could be calculated.
*
* @return the drop row
*/
public int getRow() {
return row;
}
/** {@collect.stats}
* Returns the column index where a dropped item should be placed in the
* table. Interpretation of the value depends on the return of
* <code>isInsertColumn()</code>. If that method returns
* <code>true</code> this value indicates the index where a new
* column should be inserted. Otherwise, it represents the value
* of an existing column on which the data was dropped. This index is
* in terms of the view.
* <p>
* <code>-1</code> indicates that the drop occurred over empty space,
* and no column could be calculated.
*
* @return the drop row
*/
public int getColumn() {
return col;
}
/** {@collect.stats}
* Returns whether or not this location represents an insert
* of a row.
*
* @return whether or not this is an insert row
*/
public boolean isInsertRow() {
return isInsertRow;
}
/** {@collect.stats}
* Returns whether or not this location represents an insert
* of a column.
*
* @return whether or not this is an insert column
*/
public boolean isInsertColumn() {
return isInsertCol;
}
/** {@collect.stats}
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName()
+ "[dropPoint=" + getDropPoint() + ","
+ "row=" + row + ","
+ "column=" + col + ","
+ "insertRow=" + isInsertRow + ","
+ "insertColumn=" + isInsertCol + "]";
}
}
//
// Constructors
//
/** {@collect.stats}
* Constructs a default <code>JTable</code> that is initialized with a default
* data model, a default column model, and a default selection
* model.
*
* @see #createDefaultDataModel
* @see #createDefaultColumnModel
* @see #createDefaultSelectionModel
*/
public JTable() {
this(null, null, null);
}
/** {@collect.stats}
* Constructs a <code>JTable</code> that is initialized with
* <code>dm</code> as the data model, a default column model,
* and a default selection model.
*
* @param dm the data model for the table
* @see #createDefaultColumnModel
* @see #createDefaultSelectionModel
*/
public JTable(TableModel dm) {
this(dm, null, null);
}
/** {@collect.stats}
* Constructs a <code>JTable</code> that is initialized with
* <code>dm</code> as the data model, <code>cm</code>
* as the column model, and a default selection model.
*
* @param dm the data model for the table
* @param cm the column model for the table
* @see #createDefaultSelectionModel
*/
public JTable(TableModel dm, TableColumnModel cm) {
this(dm, cm, null);
}
/** {@collect.stats}
* Constructs a <code>JTable</code> that is initialized with
* <code>dm</code> as the data model, <code>cm</code> as the
* column model, and <code>sm</code> as the selection model.
* If any of the parameters are <code>null</code> this method
* will initialize the table with the corresponding default model.
* The <code>autoCreateColumnsFromModel</code> flag is set to false
* if <code>cm</code> is non-null, otherwise it is set to true
* and the column model is populated with suitable
* <code>TableColumns</code> for the columns in <code>dm</code>.
*
* @param dm the data model for the table
* @param cm the column model for the table
* @param sm the row selection model for the table
* @see #createDefaultDataModel
* @see #createDefaultColumnModel
* @see #createDefaultSelectionModel
*/
public JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
super();
setLayout(null);
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
JComponent.getManagingFocusForwardTraversalKeys());
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
JComponent.getManagingFocusBackwardTraversalKeys());
if (cm == null) {
cm = createDefaultColumnModel();
autoCreateColumnsFromModel = true;
}
setColumnModel(cm);
if (sm == null) {
sm = createDefaultSelectionModel();
}
setSelectionModel(sm);
// Set the model last, that way if the autoCreatColumnsFromModel has
// been set above, we will automatically populate an empty columnModel
// with suitable columns for the new model.
if (dm == null) {
dm = createDefaultDataModel();
}
setModel(dm);
initializeLocalVars();
updateUI();
}
/** {@collect.stats}
* Constructs a <code>JTable</code> with <code>numRows</code>
* and <code>numColumns</code> of empty cells using
* <code>DefaultTableModel</code>. The columns will have
* names of the form "A", "B", "C", etc.
*
* @param numRows the number of rows the table holds
* @param numColumns the number of columns the table holds
* @see javax.swing.table.DefaultTableModel
*/
public JTable(int numRows, int numColumns) {
this(new DefaultTableModel(numRows, numColumns));
}
/** {@collect.stats}
* Constructs a <code>JTable</code> to display the values in the
* <code>Vector</code> of <code>Vectors</code>, <code>rowData</code>,
* with column names, <code>columnNames</code>. The
* <code>Vectors</code> contained in <code>rowData</code>
* should contain the values for that row. In other words,
* the value of the cell at row 1, column 5 can be obtained
* with the following code:
* <p>
* <pre>((Vector)rowData.elementAt(1)).elementAt(5);</pre>
* <p>
* @param rowData the data for the new table
* @param columnNames names of each column
*/
public JTable(Vector rowData, Vector columnNames) {
this(new DefaultTableModel(rowData, columnNames));
}
/** {@collect.stats}
* Constructs a <code>JTable</code> to display the values in the two dimensional array,
* <code>rowData</code>, with column names, <code>columnNames</code>.
* <code>rowData</code> is an array of rows, so the value of the cell at row 1,
* column 5 can be obtained with the following code:
* <p>
* <pre> rowData[1][5]; </pre>
* <p>
* All rows must be of the same length as <code>columnNames</code>.
* <p>
* @param rowData the data for the new table
* @param columnNames names of each column
*/
public JTable(final Object[][] rowData, final Object[] columnNames) {
this(new AbstractTableModel() {
public String getColumnName(int column) { return columnNames[column].toString(); }
public int getRowCount() { return rowData.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) { return rowData[row][col]; }
public boolean isCellEditable(int row, int column) { return true; }
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
});
}
/** {@collect.stats}
* Calls the <code>configureEnclosingScrollPane</code> method.
*
* @see #configureEnclosingScrollPane
*/
public void addNotify() {
super.addNotify();
configureEnclosingScrollPane();
}
/** {@collect.stats}
* If this <code>JTable</code> is the <code>viewportView</code> of an enclosing <code>JScrollPane</code>
* (the usual situation), configure this <code>ScrollPane</code> by, amongst other things,
* installing the table's <code>tableHeader</code> as the <code>columnHeaderView</code> of the scroll pane.
* When a <code>JTable</code> is added to a <code>JScrollPane</code> in the usual way,
* using <code>new JScrollPane(myTable)</code>, <code>addNotify</code> is
* called in the <code>JTable</code> (when the table is added to the viewport).
* <code>JTable</code>'s <code>addNotify</code> method in turn calls this method,
* which is protected so that this default installation procedure can
* be overridden by a subclass.
*
* @see #addNotify
*/
protected void configureEnclosingScrollPane() {
Container p = getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)gp;
// Make certain we are the viewPort's view and not, for
// example, the rowHeaderView of the scrollPane -
// an implementor of fixed columns might do this.
JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) {
return;
}
scrollPane.setColumnHeaderView(getTableHeader());
// configure the scrollpane for any LAF dependent settings
configureEnclosingScrollPaneUI();
}
}
}
/** {@collect.stats}
* This is a sub-part of configureEnclosingScrollPane() that configures
* anything on the scrollpane that may change when the look and feel
* changes. It needed to be split out from configureEnclosingScrollPane() so
* that it can be called from updateUI() when the LAF changes without
* causing the regression found in bug 6687962. This was because updateUI()
* is called from the constructor which then caused
* configureEnclosingScrollPane() to be called by the constructor which
* changes its contract for any subclass that overrides it. So by splitting
* it out in this way configureEnclosingScrollPaneUI() can be called both
* from configureEnclosingScrollPane() and updateUI() in a safe manor.
*/
private void configureEnclosingScrollPaneUI() {
Container p = getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)gp;
// Make certain we are the viewPort's view and not, for
// example, the rowHeaderView of the scrollPane -
// an implementor of fixed columns might do this.
JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) {
return;
}
// scrollPane.getViewport().setBackingStoreEnabled(true);
Border border = scrollPane.getBorder();
if (border == null || border instanceof UIResource) {
Border scrollPaneBorder =
UIManager.getBorder("Table.scrollPaneBorder");
if (scrollPaneBorder != null) {
scrollPane.setBorder(scrollPaneBorder);
}
}
// add JScrollBar corner component if available from LAF and not already set by the user
Component corner =
scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER);
if (corner == null || corner instanceof UIResource){
corner = null;
Object componentClass = UIManager.get(
"Table.scrollPaneCornerComponent");
if (componentClass instanceof Class){
try {
corner = (Component)
((Class)componentClass).newInstance();
} catch (Exception e) {
// just ignore and don't set corner
}
}
scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
corner);
}
}
}
}
/** {@collect.stats}
* Calls the <code>unconfigureEnclosingScrollPane</code> method.
*
* @see #unconfigureEnclosingScrollPane
*/
public void removeNotify() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
removePropertyChangeListener("permanentFocusOwner", editorRemover);
editorRemover = null;
unconfigureEnclosingScrollPane();
super.removeNotify();
}
/** {@collect.stats}
* Reverses the effect of <code>configureEnclosingScrollPane</code>
* by replacing the <code>columnHeaderView</code> of the enclosing
* scroll pane with <code>null</code>. <code>JTable</code>'s
* <code>removeNotify</code> method calls
* this method, which is protected so that this default uninstallation
* procedure can be overridden by a subclass.
*
* @see #removeNotify
* @see #configureEnclosingScrollPane
* @since 1.3
*/
protected void unconfigureEnclosingScrollPane() {
Container p = getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)gp;
// Make certain we are the viewPort's view and not, for
// example, the rowHeaderView of the scrollPane -
// an implementor of fixed columns might do this.
JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) {
return;
}
scrollPane.setColumnHeaderView(null);
// remove ScrollPane corner if one was added by the LAF
Component corner =
scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER);
if (corner instanceof UIResource){
scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
null);
}
}
}
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "rowHeight") {
if (!isRowHeightSet) {
setRowHeight(((Number)value).intValue());
isRowHeightSet = false;
}
return;
}
super.setUIProperty(propertyName, value);
}
//
// Static Methods
//
/** {@collect.stats}
* Equivalent to <code>new JScrollPane(aTable)</code>.
*
* @deprecated As of Swing version 1.0.2,
* replaced by <code>new JScrollPane(aTable)</code>.
*/
@Deprecated
static public JScrollPane createScrollPaneForTable(JTable aTable) {
return new JScrollPane(aTable);
}
//
// Table Attributes
//
/** {@collect.stats}
* Sets the <code>tableHeader</code> working with this <code>JTable</code> to <code>newHeader</code>.
* It is legal to have a <code>null</code> <code>tableHeader</code>.
*
* @param tableHeader new tableHeader
* @see #getTableHeader
* @beaninfo
* bound: true
* description: The JTableHeader instance which renders the column headers.
*/
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != tableHeader) {
JTableHeader old = this.tableHeader;
// Release the old header
if (old != null) {
old.setTable(null);
}
this.tableHeader = tableHeader;
if (tableHeader != null) {
tableHeader.setTable(this);
}
firePropertyChange("tableHeader", old, tableHeader);
}
}
/** {@collect.stats}
* Returns the <code>tableHeader</code> used by this <code>JTable</code>.
*
* @return the <code>tableHeader</code> used by this table
* @see #setTableHeader
*/
public JTableHeader getTableHeader() {
return tableHeader;
}
/** {@collect.stats}
* Sets the height, in pixels, of all cells to <code>rowHeight</code>,
* revalidates, and repaints.
* The height of the cells will be equal to the row height minus
* the row margin.
*
* @param rowHeight new row height
* @exception IllegalArgumentException if <code>rowHeight</code> is
* less than 1
* @see #getRowHeight
* @beaninfo
* bound: true
* description: The height of the specified row.
*/
public void setRowHeight(int rowHeight) {
if (rowHeight <= 0) {
throw new IllegalArgumentException("New row height less than 1");
}
int old = this.rowHeight;
this.rowHeight = rowHeight;
rowModel = null;
if (sortManager != null) {
sortManager.modelRowSizes = null;
}
isRowHeightSet = true;
resizeAndRepaint();
firePropertyChange("rowHeight", old, rowHeight);
}
/** {@collect.stats}
* Returns the height of a table row, in pixels.
* The default row height is 16.0.
*
* @return the height in pixels of a table row
* @see #setRowHeight
*/
public int getRowHeight() {
return rowHeight;
}
private SizeSequence getRowModel() {
if (rowModel == null) {
rowModel = new SizeSequence(getRowCount(), getRowHeight());
}
return rowModel;
}
/** {@collect.stats}
* Sets the height for <code>row</code> to <code>rowHeight</code>,
* revalidates, and repaints. The height of the cells in this row
* will be equal to the row height minus the row margin.
*
* @param row the row whose height is being
changed
* @param rowHeight new row height, in pixels
* @exception IllegalArgumentException if <code>rowHeight</code> is
* less than 1
* @beaninfo
* bound: true
* description: The height in pixels of the cells in <code>row</code>
* @since 1.3
*/
public void setRowHeight(int row, int rowHeight) {
if (rowHeight <= 0) {
throw new IllegalArgumentException("New row height less than 1");
}
getRowModel().setSize(row, rowHeight);
if (sortManager != null) {
sortManager.setViewRowHeight(row, rowHeight);
}
resizeAndRepaint();
}
/** {@collect.stats}
* Returns the height, in pixels, of the cells in <code>row</code>.
* @param row the row whose height is to be returned
* @return the height, in pixels, of the cells in the row
* @since 1.3
*/
public int getRowHeight(int row) {
return (rowModel == null) ? getRowHeight() : rowModel.getSize(row);
}
/** {@collect.stats}
* Sets the amount of empty space between cells in adjacent rows.
*
* @param rowMargin the number of pixels between cells in a row
* @see #getRowMargin
* @beaninfo
* bound: true
* description: The amount of space between cells.
*/
public void setRowMargin(int rowMargin) {
int old = this.rowMargin;
this.rowMargin = rowMargin;
resizeAndRepaint();
firePropertyChange("rowMargin", old, rowMargin);
}
/** {@collect.stats}
* Gets the amount of empty space, in pixels, between cells. Equivalent to:
* <code>getIntercellSpacing().height</code>.
* @return the number of pixels between cells in a row
*
* @see #setRowMargin
*/
public int getRowMargin() {
return rowMargin;
}
/** {@collect.stats}
* Sets the <code>rowMargin</code> and the <code>columnMargin</code> --
* the height and width of the space between cells -- to
* <code>intercellSpacing</code>.
*
* @param intercellSpacing a <code>Dimension</code>
* specifying the new width
* and height between cells
* @see #getIntercellSpacing
* @beaninfo
* description: The spacing between the cells,
* drawn in the background color of the JTable.
*/
public void setIntercellSpacing(Dimension intercellSpacing) {
// Set the rowMargin here and columnMargin in the TableColumnModel
setRowMargin(intercellSpacing.height);
getColumnModel().setColumnMargin(intercellSpacing.width);
resizeAndRepaint();
}
/** {@collect.stats}
* Returns the horizontal and vertical space between cells.
* The default spacing is (1, 1), which provides room to draw the grid.
*
* @return the horizontal and vertical spacing between cells
* @see #setIntercellSpacing
*/
public Dimension getIntercellSpacing() {
return new Dimension(getColumnModel().getColumnMargin(), rowMargin);
}
/** {@collect.stats}
* Sets the color used to draw grid lines to <code>gridColor</code> and redisplays.
* The default color is look and feel dependent.
*
* @param gridColor the new color of the grid lines
* @exception IllegalArgumentException if <code>gridColor</code> is <code>null</code>
* @see #getGridColor
* @beaninfo
* bound: true
* description: The grid color.
*/
public void setGridColor(Color gridColor) {
if (gridColor == null) {
throw new IllegalArgumentException("New color is null");
}
Color old = this.gridColor;
this.gridColor = gridColor;
firePropertyChange("gridColor", old, gridColor);
// Redraw
repaint();
}
/** {@collect.stats}
* Returns the color used to draw grid lines.
* The default color is look and feel dependent.
*
* @return the color used to draw grid lines
* @see #setGridColor
*/
public Color getGridColor() {
return gridColor;
}
/** {@collect.stats}
* Sets whether the table draws grid lines around cells.
* If <code>showGrid</code> is true it does; if it is false it doesn't.
* There is no <code>getShowGrid</code> method as this state is held
* in two variables -- <code>showHorizontalLines</code> and <code>showVerticalLines</code> --
* each of which can be queried independently.
*
* @param showGrid true if table view should draw grid lines
*
* @see #setShowVerticalLines
* @see #setShowHorizontalLines
* @beaninfo
* description: The color used to draw the grid lines.
*/
public void setShowGrid(boolean showGrid) {
setShowHorizontalLines(showGrid);
setShowVerticalLines(showGrid);
// Redraw
repaint();
}
/** {@collect.stats}
* Sets whether the table draws horizontal lines between cells.
* If <code>showHorizontalLines</code> is true it does; if it is false it doesn't.
*
* @param showHorizontalLines true if table view should draw horizontal lines
* @see #getShowHorizontalLines
* @see #setShowGrid
* @see #setShowVerticalLines
* @beaninfo
* bound: true
* description: Whether horizontal lines should be drawn in between the cells.
*/
public void setShowHorizontalLines(boolean showHorizontalLines) {
boolean old = this.showHorizontalLines;
this.showHorizontalLines = showHorizontalLines;
firePropertyChange("showHorizontalLines", old, showHorizontalLines);
// Redraw
repaint();
}
/** {@collect.stats}
* Sets whether the table draws vertical lines between cells.
* If <code>showVerticalLines</code> is true it does; if it is false it doesn't.
*
* @param showVerticalLines true if table view should draw vertical lines
* @see #getShowVerticalLines
* @see #setShowGrid
* @see #setShowHorizontalLines
* @beaninfo
* bound: true
* description: Whether vertical lines should be drawn in between the cells.
*/
public void setShowVerticalLines(boolean showVerticalLines) {
boolean old = this.showVerticalLines;
this.showVerticalLines = showVerticalLines;
firePropertyChange("showVerticalLines", old, showVerticalLines);
// Redraw
repaint();
}
/** {@collect.stats}
* Returns true if the table draws horizontal lines between cells, false if it
* doesn't. The default is true.
*
* @return true if the table draws horizontal lines between cells, false if it
* doesn't
* @see #setShowHorizontalLines
*/
public boolean getShowHorizontalLines() {
return showHorizontalLines;
}
/** {@collect.stats}
* Returns true if the table draws vertical lines between cells, false if it
* doesn't. The default is true.
*
* @return true if the table draws vertical lines between cells, false if it
* doesn't
* @see #setShowVerticalLines
*/
public boolean getShowVerticalLines() {
return showVerticalLines;
}
/** {@collect.stats}
* Sets the table's auto resize mode when the table is resized. For further
* information on how the different resize modes work, see
* {@link #doLayout}.
*
* @param mode One of 5 legal values:
* AUTO_RESIZE_OFF,
* AUTO_RESIZE_NEXT_COLUMN,
* AUTO_RESIZE_SUBSEQUENT_COLUMNS,
* AUTO_RESIZE_LAST_COLUMN,
* AUTO_RESIZE_ALL_COLUMNS
*
* @see #getAutoResizeMode
* @see #doLayout
* @beaninfo
* bound: true
* description: Whether the columns should adjust themselves automatically.
* enum: AUTO_RESIZE_OFF JTable.AUTO_RESIZE_OFF
* AUTO_RESIZE_NEXT_COLUMN JTable.AUTO_RESIZE_NEXT_COLUMN
* AUTO_RESIZE_SUBSEQUENT_COLUMNS JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS
* AUTO_RESIZE_LAST_COLUMN JTable.AUTO_RESIZE_LAST_COLUMN
* AUTO_RESIZE_ALL_COLUMNS JTable.AUTO_RESIZE_ALL_COLUMNS
*/
public void setAutoResizeMode(int mode) {
if ((mode == AUTO_RESIZE_OFF) ||
(mode == AUTO_RESIZE_NEXT_COLUMN) ||
(mode == AUTO_RESIZE_SUBSEQUENT_COLUMNS) ||
(mode == AUTO_RESIZE_LAST_COLUMN) ||
(mode == AUTO_RESIZE_ALL_COLUMNS)) {
int old = autoResizeMode;
autoResizeMode = mode;
resizeAndRepaint();
if (tableHeader != null) {
tableHeader.resizeAndRepaint();
}
firePropertyChange("autoResizeMode", old, autoResizeMode);
}
}
/** {@collect.stats}
* Returns the auto resize mode of the table. The default mode
* is AUTO_RESIZE_SUBSEQUENT_COLUMNS.
*
* @return the autoResizeMode of the table
*
* @see #setAutoResizeMode
* @see #doLayout
*/
public int getAutoResizeMode() {
return autoResizeMode;
}
/** {@collect.stats}
* Sets this table's <code>autoCreateColumnsFromModel</code> flag.
* This method calls <code>createDefaultColumnsFromModel</code> if
* <code>autoCreateColumnsFromModel</code> changes from false to true.
*
* @param autoCreateColumnsFromModel true if <code>JTable</code> should automatically create columns
* @see #getAutoCreateColumnsFromModel
* @see #createDefaultColumnsFromModel
* @beaninfo
* bound: true
* description: Automatically populates the columnModel when a new TableModel is submitted.
*/
public void setAutoCreateColumnsFromModel(boolean autoCreateColumnsFromModel) {
if (this.autoCreateColumnsFromModel != autoCreateColumnsFromModel) {
boolean old = this.autoCreateColumnsFromModel;
this.autoCreateColumnsFromModel = autoCreateColumnsFromModel;
if (autoCreateColumnsFromModel) {
createDefaultColumnsFromModel();
}
firePropertyChange("autoCreateColumnsFromModel", old, autoCreateColumnsFromModel);
}
}
/** {@collect.stats}
* Determines whether the table will create default columns from the model.
* If true, <code>setModel</code> will clear any existing columns and
* create new columns from the new model. Also, if the event in
* the <code>tableChanged</code> notification specifies that the
* entire table changed, then the columns will be rebuilt.
* The default is true.
*
* @return the autoCreateColumnsFromModel of the table
* @see #setAutoCreateColumnsFromModel
* @see #createDefaultColumnsFromModel
*/
public boolean getAutoCreateColumnsFromModel() {
return autoCreateColumnsFromModel;
}
/** {@collect.stats}
* Creates default columns for the table from
* the data model using the <code>getColumnCount</code> method
* defined in the <code>TableModel</code> interface.
* <p>
* Clears any existing columns before creating the
* new columns based on information from the model.
*
* @see #getAutoCreateColumnsFromModel
*/
public void createDefaultColumnsFromModel() {
TableModel m = getModel();
if (m != null) {
// Remove any current columns
TableColumnModel cm = getColumnModel();
while (cm.getColumnCount() > 0) {
cm.removeColumn(cm.getColumn(0));
}
// Create new columns from the data model info
for (int i = 0; i < m.getColumnCount(); i++) {
TableColumn newColumn = new TableColumn(i);
addColumn(newColumn);
}
}
}
/** {@collect.stats}
* Sets a default cell renderer to be used if no renderer has been set in
* a <code>TableColumn</code>. If renderer is <code>null</code>,
* removes the default renderer for this column class.
*
* @param columnClass set the default cell renderer for this columnClass
* @param renderer default cell renderer to be used for this
* columnClass
* @see #getDefaultRenderer
* @see #setDefaultEditor
*/
public void setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) {
if (renderer != null) {
defaultRenderersByColumnClass.put(columnClass, renderer);
}
else {
defaultRenderersByColumnClass.remove(columnClass);
}
}
/** {@collect.stats}
* Returns the cell renderer to be used when no renderer has been set in
* a <code>TableColumn</code>. During the rendering of cells the renderer is fetched from
* a <code>Hashtable</code> of entries according to the class of the cells in the column. If
* there is no entry for this <code>columnClass</code> the method returns
* the entry for the most specific superclass. The <code>JTable</code> installs entries
* for <code>Object</code>, <code>Number</code>, and <code>Boolean</code>, all of which can be modified
* or replaced.
*
* @param columnClass return the default cell renderer
* for this columnClass
* @return the renderer for this columnClass
* @see #setDefaultRenderer
* @see #getColumnClass
*/
public TableCellRenderer getDefaultRenderer(Class<?> columnClass) {
if (columnClass == null) {
return null;
}
else {
Object renderer = defaultRenderersByColumnClass.get(columnClass);
if (renderer != null) {
return (TableCellRenderer)renderer;
}
else {
return getDefaultRenderer(columnClass.getSuperclass());
}
}
}
/** {@collect.stats}
* Sets a default cell editor to be used if no editor has been set in
* a <code>TableColumn</code>. If no editing is required in a table, or a
* particular column in a table, uses the <code>isCellEditable</code>
* method in the <code>TableModel</code> interface to ensure that this
* <code>JTable</code> will not start an editor in these columns.
* If editor is <code>null</code>, removes the default editor for this
* column class.
*
* @param columnClass set the default cell editor for this columnClass
* @param editor default cell editor to be used for this columnClass
* @see TableModel#isCellEditable
* @see #getDefaultEditor
* @see #setDefaultRenderer
*/
public void setDefaultEditor(Class<?> columnClass, TableCellEditor editor) {
if (editor != null) {
defaultEditorsByColumnClass.put(columnClass, editor);
}
else {
defaultEditorsByColumnClass.remove(columnClass);
}
}
/** {@collect.stats}
* Returns the editor to be used when no editor has been set in
* a <code>TableColumn</code>. During the editing of cells the editor is fetched from
* a <code>Hashtable</code> of entries according to the class of the cells in the column. If
* there is no entry for this <code>columnClass</code> the method returns
* the entry for the most specific superclass. The <code>JTable</code> installs entries
* for <code>Object</code>, <code>Number</code>, and <code>Boolean</code>, all of which can be modified
* or replaced.
*
* @param columnClass return the default cell editor for this columnClass
* @return the default cell editor to be used for this columnClass
* @see #setDefaultEditor
* @see #getColumnClass
*/
public TableCellEditor getDefaultEditor(Class<?> columnClass) {
if (columnClass == null) {
return null;
}
else {
Object editor = defaultEditorsByColumnClass.get(columnClass);
if (editor != null) {
return (TableCellEditor)editor;
}
else {
return getDefaultEditor(columnClass.getSuperclass());
}
}
}
/** {@collect.stats}
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* table's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the table's
* {@code TableUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* an item (in single selection mode) or a selection (in other selection
* modes) and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* table's {@code TransferHandler}.
*
* @param b whether or not to enable automatic drag handling
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/** {@collect.stats}
* Returns whether or not automatic drag handling is enabled.
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
/** {@collect.stats}
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of one of the other modes is recommended, however, for an
* improved user experience. <code>DropMode.ON</code>, for instance,
* offers similar behavior of showing items as selected, but does so without
* affecting the actual selection in the table.
* <p>
* <code>JTable</code> supports the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.ON</code></li>
* <li><code>DropMode.INSERT</code></li>
* <li><code>DropMode.INSERT_ROWS</code></li>
* <li><code>DropMode.INSERT_COLS</code></li>
* <li><code>DropMode.ON_OR_INSERT</code></li>
* <li><code>DropMode.ON_OR_INSERT_ROWS</code></li>
* <li><code>DropMode.ON_OR_INSERT_COLS</code></li>
* </ul>
* <p>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see TransferHandler
* @since 1.6
*/
public final void setDropMode(DropMode dropMode) {
if (dropMode != null) {
switch (dropMode) {
case USE_SELECTION:
case ON:
case INSERT:
case INSERT_ROWS:
case INSERT_COLS:
case ON_OR_INSERT:
case ON_OR_INSERT_ROWS:
case ON_OR_INSERT_COLS:
this.dropMode = dropMode;
return;
}
}
throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for table");
}
/** {@collect.stats}
* Returns the drop mode for this component.
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
public final DropMode getDropMode() {
return dropMode;
}
/** {@collect.stats}
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
DropLocation dropLocationForPoint(Point p) {
DropLocation location = null;
int row = rowAtPoint(p);
int col = columnAtPoint(p);
boolean outside = Boolean.TRUE == getClientProperty("Table.isFileList")
&& SwingUtilities2.pointOutsidePrefSize(this, row, col, p);
Rectangle rect = getCellRect(row, col, true);
Section xSection, ySection;
boolean between = false;
boolean ltr = getComponentOrientation().isLeftToRight();
switch(dropMode) {
case USE_SELECTION:
case ON:
if (row == -1 || col == -1 || outside) {
location = new DropLocation(p, -1, -1, false, false);
} else {
location = new DropLocation(p, row, col, false, false);
}
break;
case INSERT:
if (row == -1 && col == -1) {
location = new DropLocation(p, 0, 0, true, true);
break;
}
xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
if (row == -1) {
if (xSection == LEADING) {
location = new DropLocation(p, getRowCount(), col, true, true);
} else if (xSection == TRAILING) {
location = new DropLocation(p, getRowCount(), col + 1, true, true);
} else {
location = new DropLocation(p, getRowCount(), col, true, false);
}
} else if (xSection == LEADING || xSection == TRAILING) {
ySection = SwingUtilities2.liesInVertical(rect, p, true);
if (ySection == LEADING) {
between = true;
} else if (ySection == TRAILING) {
row++;
between = true;
}
location = new DropLocation(p, row,
xSection == TRAILING ? col + 1 : col,
between, true);
} else {
if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
row++;
}
location = new DropLocation(p, row, col, true, false);
}
break;
case INSERT_ROWS:
if (row == -1 && col == -1) {
location = new DropLocation(p, -1, -1, false, false);
break;
}
if (row == -1) {
location = new DropLocation(p, getRowCount(), col, true, false);
break;
}
if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
row++;
}
location = new DropLocation(p, row, col, true, false);
break;
case ON_OR_INSERT_ROWS:
if (row == -1 && col == -1) {
location = new DropLocation(p, -1, -1, false, false);
break;
}
if (row == -1) {
location = new DropLocation(p, getRowCount(), col, true, false);
break;
}
ySection = SwingUtilities2.liesInVertical(rect, p, true);
if (ySection == LEADING) {
between = true;
} else if (ySection == TRAILING) {
row++;
between = true;
}
location = new DropLocation(p, row, col, between, false);
break;
case INSERT_COLS:
if (row == -1) {
location = new DropLocation(p, -1, -1, false, false);
break;
}
if (col == -1) {
location = new DropLocation(p, getColumnCount(), col, false, true);
break;
}
if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
col++;
}
location = new DropLocation(p, row, col, false, true);
break;
case ON_OR_INSERT_COLS:
if (row == -1) {
location = new DropLocation(p, -1, -1, false, false);
break;
}
if (col == -1) {
location = new DropLocation(p, row, getColumnCount(), false, true);
break;
}
xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
if (xSection == LEADING) {
between = true;
} else if (xSection == TRAILING) {
col++;
between = true;
}
location = new DropLocation(p, row, col, false, between);
break;
case ON_OR_INSERT:
if (row == -1 && col == -1) {
location = new DropLocation(p, 0, 0, true, true);
break;
}
xSection = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
if (row == -1) {
if (xSection == LEADING) {
location = new DropLocation(p, getRowCount(), col, true, true);
} else if (xSection == TRAILING) {
location = new DropLocation(p, getRowCount(), col + 1, true, true);
} else {
location = new DropLocation(p, getRowCount(), col, true, false);
}
break;
}
ySection = SwingUtilities2.liesInVertical(rect, p, true);
if (ySection == LEADING) {
between = true;
} else if (ySection == TRAILING) {
row++;
between = true;
}
location = new DropLocation(p, row,
xSection == TRAILING ? col + 1 : col,
between,
xSection != MIDDLE);
break;
default:
assert false : "Unexpected drop mode";
}
return location;
}
/** {@collect.stats}
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
Object retVal = null;
DropLocation tableLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (tableLocation == null) {
if (!forDrop && state != null) {
clearSelection();
int[] rows = (int[])((int[][])state)[0];
int[] cols = (int[])((int[][])state)[1];
int[] anchleads = (int[])((int[][])state)[2];
for (int i = 0; i < rows.length; i++) {
addRowSelectionInterval(rows[i], rows[i]);
}
for (int i = 0; i < cols.length; i++) {
addColumnSelectionInterval(cols[i], cols[i]);
}
SwingUtilities2.setLeadAnchorWithoutSelection(
getSelectionModel(), anchleads[1], anchleads[0]);
SwingUtilities2.setLeadAnchorWithoutSelection(
getColumnModel().getSelectionModel(),
anchleads[3], anchleads[2]);
}
} else {
if (dropLocation == null) {
retVal = new int[][]{
getSelectedRows(),
getSelectedColumns(),
{getAdjustedIndex(getSelectionModel()
.getAnchorSelectionIndex(), true),
getAdjustedIndex(getSelectionModel()
.getLeadSelectionIndex(), true),
getAdjustedIndex(getColumnModel().getSelectionModel()
.getAnchorSelectionIndex(), false),
getAdjustedIndex(getColumnModel().getSelectionModel()
.getLeadSelectionIndex(), false)}};
} else {
retVal = state;
}
if (tableLocation.getRow() == -1) {
clearSelectionAndLeadAnchor();
} else {
setRowSelectionInterval(tableLocation.getRow(),
tableLocation.getRow());
setColumnSelectionInterval(tableLocation.getColumn(),
tableLocation.getColumn());
}
}
}
DropLocation old = dropLocation;
dropLocation = tableLocation;
firePropertyChange("dropLocation", old, dropLocation);
return retVal;
}
/** {@collect.stats}
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public final DropLocation getDropLocation() {
return dropLocation;
}
/** {@collect.stats}
* Specifies whether a {@code RowSorter} should be created for the
* table whenever its model changes.
* <p>
* When {@code setAutoCreateRowSorter(true)} is invoked, a {@code
* TableRowSorter} is immediately created and installed on the
* table. While the {@code autoCreateRowSorter} property remains
* {@code true}, every time the model is changed, a new {@code
* TableRowSorter} is created and set as the table's row sorter.
*
* @param autoCreateRowSorter whether or not a {@code RowSorter}
* should be automatically created
* @see javax.swing.table.TableRowSorter
* @beaninfo
* bound: true
* preferred: true
* description: Whether or not to turn on sorting by default.
* @since 1.6
*/
public void setAutoCreateRowSorter(boolean autoCreateRowSorter) {
boolean oldValue = this.autoCreateRowSorter;
this.autoCreateRowSorter = autoCreateRowSorter;
if (autoCreateRowSorter) {
setRowSorter(new TableRowSorter(getModel()));
}
firePropertyChange("autoCreateRowSorter", oldValue,
autoCreateRowSorter);
}
/** {@collect.stats}
* Returns {@code true} if whenever the model changes, a new
* {@code RowSorter} should be created and installed
* as the table's sorter; otherwise, returns {@code false}.
*
* @return true if a {@code RowSorter} should be created when
* the model changes
* @since 1.6
*/
public boolean getAutoCreateRowSorter() {
return autoCreateRowSorter;
}
/** {@collect.stats}
* Specifies whether the selection should be updated after sorting.
* If true, on sorting the selection is reset such that
* the same rows, in terms of the model, remain selected. The default
* is true.
*
* @param update whether or not to update the selection on sorting
* @beaninfo
* bound: true
* expert: true
* description: Whether or not to update the selection on sorting
* @since 1.6
*/
public void setUpdateSelectionOnSort(boolean update) {
if (updateSelectionOnSort != update) {
updateSelectionOnSort = update;
firePropertyChange("updateSelectionOnSort", !update, update);
}
}
/** {@collect.stats}
* Returns true if the selection should be updated after sorting.
*
* @return whether to update the selection on a sort
* @since 1.6
*/
public boolean getUpdateSelectionOnSort() {
return updateSelectionOnSort;
}
/** {@collect.stats}
* Sets the <code>RowSorter</code>. <code>RowSorter</code> is used
* to provide sorting and filtering to a <code>JTable</code>.
* <p>
* This method clears the selection and resets any variable row heights.
* <p>
* If the underlying model of the <code>RowSorter</code> differs from
* that of this <code>JTable</code> undefined behavior will result.
*
* @param sorter the <code>RowSorter</code>; <code>null</code> turns
* sorting off
* @see javax.swing.table.TableRowSorter
* @since 1.6
*/
public void setRowSorter(RowSorter<? extends TableModel> sorter) {
RowSorter<? extends TableModel> oldRowSorter = null;
if (sortManager != null) {
oldRowSorter = sortManager.sorter;
sortManager.dispose();
sortManager = null;
}
rowModel = null;
clearSelectionAndLeadAnchor();
if (sorter != null) {
sortManager = new SortManager(sorter);
}
resizeAndRepaint();
firePropertyChange("rowSorter", oldRowSorter, sorter);
firePropertyChange("sorter", oldRowSorter, sorter);
}
/** {@collect.stats}
* Returns the object responsible for sorting.
*
* @return the object responsible for sorting
* @since 1.6
*/
public RowSorter<? extends TableModel> getRowSorter() {
return (sortManager != null) ? sortManager.sorter : null;
}
//
// Selection methods
//
/** {@collect.stats}
* Sets the table's selection mode to allow only single selections, a single
* contiguous interval, or multiple intervals.
* <P>
* <bold>Note:</bold>
* <code>JTable</code> provides all the methods for handling
* column and row selection. When setting states,
* such as <code>setSelectionMode</code>, it not only
* updates the mode for the row selection model but also sets similar
* values in the selection model of the <code>columnModel</code>.
* If you want to have the row and column selection models operating
* in different modes, set them both directly.
* <p>
* Both the row and column selection models for <code>JTable</code>
* default to using a <code>DefaultListSelectionModel</code>
* so that <code>JTable</code> works the same way as the
* <code>JList</code>. See the <code>setSelectionMode</code> method
* in <code>JList</code> for details about the modes.
*
* @see JList#setSelectionMode
* @beaninfo
* description: The selection mode used by the row and column selection models.
* enum: SINGLE_SELECTION ListSelectionModel.SINGLE_SELECTION
* SINGLE_INTERVAL_SELECTION ListSelectionModel.SINGLE_INTERVAL_SELECTION
* MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
*/
public void setSelectionMode(int selectionMode) {
clearSelection();
getSelectionModel().setSelectionMode(selectionMode);
getColumnModel().getSelectionModel().setSelectionMode(selectionMode);
}
/** {@collect.stats}
* Sets whether the rows in this model can be selected.
*
* @param rowSelectionAllowed true if this model will allow row selection
* @see #getRowSelectionAllowed
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true, an entire row is selected for each selected cell.
*/
public void setRowSelectionAllowed(boolean rowSelectionAllowed) {
boolean old = this.rowSelectionAllowed;
this.rowSelectionAllowed = rowSelectionAllowed;
if (old != rowSelectionAllowed) {
repaint();
}
firePropertyChange("rowSelectionAllowed", old, rowSelectionAllowed);
}
/** {@collect.stats}
* Returns true if rows can be selected.
*
* @return true if rows can be selected, otherwise false
* @see #setRowSelectionAllowed
*/
public boolean getRowSelectionAllowed() {
return rowSelectionAllowed;
}
/** {@collect.stats}
* Sets whether the columns in this model can be selected.
*
* @param columnSelectionAllowed true if this model will allow column selection
* @see #getColumnSelectionAllowed
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If true, an entire column is selected for each selected cell.
*/
public void setColumnSelectionAllowed(boolean columnSelectionAllowed) {
boolean old = columnModel.getColumnSelectionAllowed();
columnModel.setColumnSelectionAllowed(columnSelectionAllowed);
if (old != columnSelectionAllowed) {
repaint();
}
firePropertyChange("columnSelectionAllowed", old, columnSelectionAllowed);
}
/** {@collect.stats}
* Returns true if columns can be selected.
*
* @return true if columns can be selected, otherwise false
* @see #setColumnSelectionAllowed
*/
public boolean getColumnSelectionAllowed() {
return columnModel.getColumnSelectionAllowed();
}
/** {@collect.stats}
* Sets whether this table allows both a column selection and a
* row selection to exist simultaneously. When set,
* the table treats the intersection of the row and column selection
* models as the selected cells. Override <code>isCellSelected</code> to
* change this default behavior. This method is equivalent to setting
* both the <code>rowSelectionAllowed</code> property and
* <code>columnSelectionAllowed</code> property of the
* <code>columnModel</code> to the supplied value.
*
* @param cellSelectionEnabled true if simultaneous row and column
* selection is allowed
* @see #getCellSelectionEnabled
* @see #isCellSelected
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Select a rectangular region of cells rather than
* rows or columns.
*/
public void setCellSelectionEnabled(boolean cellSelectionEnabled) {
setRowSelectionAllowed(cellSelectionEnabled);
setColumnSelectionAllowed(cellSelectionEnabled);
boolean old = this.cellSelectionEnabled;
this.cellSelectionEnabled = cellSelectionEnabled;
firePropertyChange("cellSelectionEnabled", old, cellSelectionEnabled);
}
/** {@collect.stats}
* Returns true if both row and column selection models are enabled.
* Equivalent to <code>getRowSelectionAllowed() &&
* getColumnSelectionAllowed()</code>.
*
* @return true if both row and column selection models are enabled
*
* @see #setCellSelectionEnabled
*/
public boolean getCellSelectionEnabled() {
return getRowSelectionAllowed() && getColumnSelectionAllowed();
}
/** {@collect.stats}
* Selects all rows, columns, and cells in the table.
*/
public void selectAll() {
// If I'm currently editing, then I should stop editing
if (isEditing()) {
removeEditor();
}
if (getRowCount() > 0 && getColumnCount() > 0) {
int oldLead;
int oldAnchor;
ListSelectionModel selModel;
selModel = selectionModel;
selModel.setValueIsAdjusting(true);
oldLead = getAdjustedIndex(selModel.getLeadSelectionIndex(), true);
oldAnchor = getAdjustedIndex(selModel.getAnchorSelectionIndex(), true);
setRowSelectionInterval(0, getRowCount()-1);
// this is done to restore the anchor and lead
SwingUtilities2.setLeadAnchorWithoutSelection(selModel, oldLead, oldAnchor);
selModel.setValueIsAdjusting(false);
selModel = columnModel.getSelectionModel();
selModel.setValueIsAdjusting(true);
oldLead = getAdjustedIndex(selModel.getLeadSelectionIndex(), false);
oldAnchor = getAdjustedIndex(selModel.getAnchorSelectionIndex(), false);
setColumnSelectionInterval(0, getColumnCount()-1);
// this is done to restore the anchor and lead
SwingUtilities2.setLeadAnchorWithoutSelection(selModel, oldLead, oldAnchor);
selModel.setValueIsAdjusting(false);
}
}
/** {@collect.stats}
* Deselects all selected columns and rows.
*/
public void clearSelection() {
selectionModel.clearSelection();
columnModel.getSelectionModel().clearSelection();
}
private void clearSelectionAndLeadAnchor() {
selectionModel.setValueIsAdjusting(true);
columnModel.getSelectionModel().setValueIsAdjusting(true);
clearSelection();
selectionModel.setAnchorSelectionIndex(-1);
selectionModel.setLeadSelectionIndex(-1);
columnModel.getSelectionModel().setAnchorSelectionIndex(-1);
columnModel.getSelectionModel().setLeadSelectionIndex(-1);
selectionModel.setValueIsAdjusting(false);
columnModel.getSelectionModel().setValueIsAdjusting(false);
}
private int getAdjustedIndex(int index, boolean row) {
int compare = row ? getRowCount() : getColumnCount();
return index < compare ? index : -1;
}
private int boundRow(int row) throws IllegalArgumentException {
if (row < 0 || row >= getRowCount()) {
throw new IllegalArgumentException("Row index out of range");
}
return row;
}
private int boundColumn(int col) {
if (col< 0 || col >= getColumnCount()) {
throw new IllegalArgumentException("Column index out of range");
}
return col;
}
/** {@collect.stats}
* Selects the rows from <code>index0</code> to <code>index1</code>,
* inclusive.
*
* @exception IllegalArgumentException if <code>index0</code> or
* <code>index1</code> lie outside
* [0, <code>getRowCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void setRowSelectionInterval(int index0, int index1) {
selectionModel.setSelectionInterval(boundRow(index0), boundRow(index1));
}
/** {@collect.stats}
* Selects the columns from <code>index0</code> to <code>index1</code>,
* inclusive.
*
* @exception IllegalArgumentException if <code>index0</code> or
* <code>index1</code> lie outside
* [0, <code>getColumnCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void setColumnSelectionInterval(int index0, int index1) {
columnModel.getSelectionModel().setSelectionInterval(boundColumn(index0), boundColumn(index1));
}
/** {@collect.stats}
* Adds the rows from <code>index0</code> to <code>index1</code>, inclusive, to
* the current selection.
*
* @exception IllegalArgumentException if <code>index0</code> or <code>index1</code>
* lie outside [0, <code>getRowCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void addRowSelectionInterval(int index0, int index1) {
selectionModel.addSelectionInterval(boundRow(index0), boundRow(index1));
}
/** {@collect.stats}
* Adds the columns from <code>index0</code> to <code>index1</code>,
* inclusive, to the current selection.
*
* @exception IllegalArgumentException if <code>index0</code> or
* <code>index1</code> lie outside
* [0, <code>getColumnCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void addColumnSelectionInterval(int index0, int index1) {
columnModel.getSelectionModel().addSelectionInterval(boundColumn(index0), boundColumn(index1));
}
/** {@collect.stats}
* Deselects the rows from <code>index0</code> to <code>index1</code>, inclusive.
*
* @exception IllegalArgumentException if <code>index0</code> or
* <code>index1</code> lie outside
* [0, <code>getRowCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void removeRowSelectionInterval(int index0, int index1) {
selectionModel.removeSelectionInterval(boundRow(index0), boundRow(index1));
}
/** {@collect.stats}
* Deselects the columns from <code>index0</code> to <code>index1</code>, inclusive.
*
* @exception IllegalArgumentException if <code>index0</code> or
* <code>index1</code> lie outside
* [0, <code>getColumnCount()</code>-1]
* @param index0 one end of the interval
* @param index1 the other end of the interval
*/
public void removeColumnSelectionInterval(int index0, int index1) {
columnModel.getSelectionModel().removeSelectionInterval(boundColumn(index0), boundColumn(index1));
}
/** {@collect.stats}
* Returns the index of the first selected row, -1 if no row is selected.
* @return the index of the first selected row
*/
public int getSelectedRow() {
return selectionModel.getMinSelectionIndex();
}
/** {@collect.stats}
* Returns the index of the first selected column,
* -1 if no column is selected.
* @return the index of the first selected column
*/
public int getSelectedColumn() {
return columnModel.getSelectionModel().getMinSelectionIndex();
}
/** {@collect.stats}
* Returns the indices of all selected rows.
*
* @return an array of integers containing the indices of all selected rows,
* or an empty array if no row is selected
* @see #getSelectedRow
*/
public int[] getSelectedRows() {
int iMin = selectionModel.getMinSelectionIndex();
int iMax = selectionModel.getMaxSelectionIndex();
if ((iMin == -1) || (iMax == -1)) {
return new int[0];
}
int[] rvTmp = new int[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (selectionModel.isSelectedIndex(i)) {
rvTmp[n++] = i;
}
}
int[] rv = new int[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
/** {@collect.stats}
* Returns the indices of all selected columns.
*
* @return an array of integers containing the indices of all selected columns,
* or an empty array if no column is selected
* @see #getSelectedColumn
*/
public int[] getSelectedColumns() {
return columnModel.getSelectedColumns();
}
/** {@collect.stats}
* Returns the number of selected rows.
*
* @return the number of selected rows, 0 if no rows are selected
*/
public int getSelectedRowCount() {
int iMin = selectionModel.getMinSelectionIndex();
int iMax = selectionModel.getMaxSelectionIndex();
int count = 0;
for(int i = iMin; i <= iMax; i++) {
if (selectionModel.isSelectedIndex(i)) {
count++;
}
}
return count;
}
/** {@collect.stats}
* Returns the number of selected columns.
*
* @return the number of selected columns, 0 if no columns are selected
*/
public int getSelectedColumnCount() {
return columnModel.getSelectedColumnCount();
}
/** {@collect.stats}
* Returns true if the specified index is in the valid range of rows,
* and the row at that index is selected.
*
* @return true if <code>row</code> is a valid index and the row at
* that index is selected (where 0 is the first row)
*/
public boolean isRowSelected(int row) {
return selectionModel.isSelectedIndex(row);
}
/** {@collect.stats}
* Returns true if the specified index is in the valid range of columns,
* and the column at that index is selected.
*
* @param column the column in the column model
* @return true if <code>column</code> is a valid index and the column at
* that index is selected (where 0 is the first column)
*/
public boolean isColumnSelected(int column) {
return columnModel.getSelectionModel().isSelectedIndex(column);
}
/** {@collect.stats}
* Returns true if the specified indices are in the valid range of rows
* and columns and the cell at the specified position is selected.
* @param row the row being queried
* @param column the column being queried
*
* @return true if <code>row</code> and <code>column</code> are valid indices
* and the cell at index <code>(row, column)</code> is selected,
* where the first row and first column are at index 0
*/
public boolean isCellSelected(int row, int column) {
if (!getRowSelectionAllowed() && !getColumnSelectionAllowed()) {
return false;
}
return (!getRowSelectionAllowed() || isRowSelected(row)) &&
(!getColumnSelectionAllowed() || isColumnSelected(column));
}
private void changeSelectionModel(ListSelectionModel sm, int index,
boolean toggle, boolean extend, boolean selected,
int anchor, boolean anchorSelected) {
if (extend) {
if (toggle) {
if (anchorSelected) {
sm.addSelectionInterval(anchor, index);
} else {
sm.removeSelectionInterval(anchor, index);
// this is a Windows-only behavior that we want for file lists
if (Boolean.TRUE == getClientProperty("Table.isFileList")) {
sm.addSelectionInterval(index, index);
sm.setAnchorSelectionIndex(anchor);
}
}
}
else {
sm.setSelectionInterval(anchor, index);
}
}
else {
if (toggle) {
if (selected) {
sm.removeSelectionInterval(index, index);
}
else {
sm.addSelectionInterval(index, index);
}
}
else {
sm.setSelectionInterval(index, index);
}
}
}
/** {@collect.stats}
* Updates the selection models of the table, depending on the state of the
* two flags: <code>toggle</code> and <code>extend</code>. Most changes
* to the selection that are the result of keyboard or mouse events received
* by the UI are channeled through this method so that the behavior may be
* overridden by a subclass. Some UIs may need more functionality than
* this method provides, such as when manipulating the lead for discontiguous
* selection, and may not call into this method for some selection changes.
* <p>
* This implementation uses the following conventions:
* <ul>
* <li> <code>toggle</code>: <em>false</em>, <code>extend</code>: <em>false</em>.
* Clear the previous selection and ensure the new cell is selected.
* <li> <code>toggle</code>: <em>false</em>, <code>extend</code>: <em>true</em>.
* Extend the previous selection from the anchor to the specified cell,
* clearing all other selections.
* <li> <code>toggle</code>: <em>true</em>, <code>extend</code>: <em>false</em>.
* If the specified cell is selected, deselect it. If it is not selected, select it.
* <li> <code>toggle</code>: <em>true</em>, <code>extend</code>: <em>true</em>.
* Apply the selection state of the anchor to all cells between it and the
* specified cell.
* </ul>
* @param rowIndex affects the selection at <code>row</code>
* @param columnIndex affects the selection at <code>column</code>
* @param toggle see description above
* @param extend if true, extend the current selection
*
* @since 1.3
*/
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
ListSelectionModel rsm = getSelectionModel();
ListSelectionModel csm = getColumnModel().getSelectionModel();
int anchorRow = getAdjustedIndex(rsm.getAnchorSelectionIndex(), true);
int anchorCol = getAdjustedIndex(csm.getAnchorSelectionIndex(), false);
boolean anchorSelected = true;
if (anchorRow == -1) {
if (getRowCount() > 0) {
anchorRow = 0;
}
anchorSelected = false;
}
if (anchorCol == -1) {
if (getColumnCount() > 0) {
anchorCol = 0;
}
anchorSelected = false;
}
// Check the selection here rather than in each selection model.
// This is significant in cell selection mode if we are supposed
// to be toggling the selection. In this case it is better to
// ensure that the cell's selection state will indeed be changed.
// If this were done in the code for the selection model it
// might leave a cell in selection state if the row was
// selected but the column was not - as it would toggle them both.
boolean selected = isCellSelected(rowIndex, columnIndex);
anchorSelected = anchorSelected && isCellSelected(anchorRow, anchorCol);
changeSelectionModel(csm, columnIndex, toggle, extend, selected,
anchorCol, anchorSelected);
changeSelectionModel(rsm, rowIndex, toggle, extend, selected,
anchorRow, anchorSelected);
// Scroll after changing the selection as blit scrolling is immediate,
// so that if we cause the repaint after the scroll we end up painting
// everything!
if (getAutoscrolls()) {
Rectangle cellRect = getCellRect(rowIndex, columnIndex, false);
if (cellRect != null) {
scrollRectToVisible(cellRect);
}
}
}
/** {@collect.stats}
* Returns the foreground color for selected cells.
*
* @return the <code>Color</code> object for the foreground property
* @see #setSelectionForeground
* @see #setSelectionBackground
*/
public Color getSelectionForeground() {
return selectionForeground;
}
/** {@collect.stats}
* Sets the foreground color for selected cells. Cell renderers
* can use this color to render text and graphics for selected
* cells.
* <p>
* The default value of this property is defined by the look
* and feel implementation.
* <p>
* This is a <a href="http://java.sun.com/docs/books/tutorial/javabeans/whatis/beanDefinition.html">JavaBeans</a> bound property.
*
* @param selectionForeground the <code>Color</code> to use in the foreground
* for selected list items
* @see #getSelectionForeground
* @see #setSelectionBackground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @beaninfo
* bound: true
* description: A default foreground color for selected cells.
*/
public void setSelectionForeground(Color selectionForeground) {
Color old = this.selectionForeground;
this.selectionForeground = selectionForeground;
firePropertyChange("selectionForeground", old, selectionForeground);
if ( !selectionForeground.equals(old) )
{
repaint();
}
}
/** {@collect.stats}
* Returns the background color for selected cells.
*
* @return the <code>Color</code> used for the background of selected list items
* @see #setSelectionBackground
* @see #setSelectionForeground
*/
public Color getSelectionBackground() {
return selectionBackground;
}
/** {@collect.stats}
* Sets the background color for selected cells. Cell renderers
* can use this color to the fill selected cells.
* <p>
* The default value of this property is defined by the look
* and feel implementation.
* <p>
* This is a <a href="http://java.sun.com/docs/books/tutorial/javabeans/whatis/beanDefinition.html">JavaBeans</a> bound property.
*
* @param selectionBackground the <code>Color</code> to use for the background
* of selected cells
* @see #getSelectionBackground
* @see #setSelectionForeground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @beaninfo
* bound: true
* description: A default background color for selected cells.
*/
public void setSelectionBackground(Color selectionBackground) {
Color old = this.selectionBackground;
this.selectionBackground = selectionBackground;
firePropertyChange("selectionBackground", old, selectionBackground);
if ( !selectionBackground.equals(old) )
{
repaint();
}
}
/** {@collect.stats}
* Returns the <code>TableColumn</code> object for the column in the table
* whose identifier is equal to <code>identifier</code>, when compared using
* <code>equals</code>.
*
* @return the <code>TableColumn</code> object that matches the identifier
* @exception IllegalArgumentException if <code>identifier</code> is <code>null</code> or no <code>TableColumn</code> has this identifier
*
* @param identifier the identifier object
*/
public TableColumn getColumn(Object identifier) {
TableColumnModel cm = getColumnModel();
int columnIndex = cm.getColumnIndex(identifier);
return cm.getColumn(columnIndex);
}
//
// Informally implement the TableModel interface.
//
/** {@collect.stats}
* Maps the index of the column in the view at
* <code>viewColumnIndex</code> to the index of the column
* in the table model. Returns the index of the corresponding
* column in the model. If <code>viewColumnIndex</code>
* is less than zero, returns <code>viewColumnIndex</code>.
*
* @param viewColumnIndex the index of the column in the view
* @return the index of the corresponding column in the model
*
* @see #convertColumnIndexToView
*/
public int convertColumnIndexToModel(int viewColumnIndex) {
if (viewColumnIndex < 0) {
return viewColumnIndex;
}
return getColumnModel().getColumn(viewColumnIndex).getModelIndex();
}
/** {@collect.stats}
* Maps the index of the column in the table model at
* <code>modelColumnIndex</code> to the index of the column
* in the view. Returns the index of the
* corresponding column in the view; returns -1 if this column is not
* being displayed. If <code>modelColumnIndex</code> is less than zero,
* returns <code>modelColumnIndex</code>.
*
* @param modelColumnIndex the index of the column in the model
* @return the index of the corresponding column in the view
*
* @see #convertColumnIndexToModel
*/
public int convertColumnIndexToView(int modelColumnIndex) {
if (modelColumnIndex < 0) {
return modelColumnIndex;
}
TableColumnModel cm = getColumnModel();
for (int column = 0; column < getColumnCount(); column++) {
if (cm.getColumn(column).getModelIndex() == modelColumnIndex) {
return column;
}
}
return -1;
}
/** {@collect.stats}
* Maps the index of the row in terms of the
* <code>TableModel</code> to the view. If the contents of the
* model are not sorted the model and view indices are the same.
*
* @param modelRowIndex the index of the row in terms of the model
* @return the index of the corresponding row in the view, or -1 if
* the row isn't visible
* @throws IndexOutOfBoundsException if sorting is enabled and passed an
* index outside the number of rows of the <code>TableModel</code>
* @see javax.swing.table.TableRowSorter
* @since 1.6
*/
public int convertRowIndexToView(int modelRowIndex) {
RowSorter sorter = getRowSorter();
if (sorter != null) {
return sorter.convertRowIndexToView(modelRowIndex);
}
return modelRowIndex;
}
/** {@collect.stats}
* Maps the index of the row in terms of the view to the
* underlying <code>TableModel</code>. If the contents of the
* model are not sorted the model and view indices are the same.
*
* @param viewRowIndex the index of the row in the view
* @return the index of the corresponding row in the model
* @throws IndexOutOfBoundsException if sorting is enabled and passed an
* index outside the range of the <code>JTable</code> as
* determined by the method <code>getRowCount</code>
* @see javax.swing.table.TableRowSorter
* @see #getRowCount
* @since 1.6
*/
public int convertRowIndexToModel(int viewRowIndex) {
RowSorter sorter = getRowSorter();
if (sorter != null) {
return sorter.convertRowIndexToModel(viewRowIndex);
}
return viewRowIndex;
}
/** {@collect.stats}
* Returns the number of rows that can be shown in the
* <code>JTable</code>, given unlimited space. If a
* <code>RowSorter</code> with a filter has been specified, the
* number of rows returned may differ from that of the underlying
* <code>TableModel</code>.
*
* @return the number of rows shown in the <code>JTable</code>
* @see #getColumnCount
*/
public int getRowCount() {
RowSorter sorter = getRowSorter();
if (sorter != null) {
return sorter.getViewRowCount();
}
return getModel().getRowCount();
}
/** {@collect.stats}
* Returns the number of columns in the column model. Note that this may
* be different from the number of columns in the table model.
*
* @return the number of columns in the table
* @see #getRowCount
* @see #removeColumn
*/
public int getColumnCount() {
return getColumnModel().getColumnCount();
}
/** {@collect.stats}
* Returns the name of the column appearing in the view at
* column position <code>column</code>.
*
* @param column the column in the view being queried
* @return the name of the column at position <code>column</code>
in the view where the first column is column 0
*/
public String getColumnName(int column) {
return getModel().getColumnName(convertColumnIndexToModel(column));
}
/** {@collect.stats}
* Returns the type of the column appearing in the view at
* column position <code>column</code>.
*
* @param column the column in the view being queried
* @return the type of the column at position <code>column</code>
* in the view where the first column is column 0
*/
public Class<?> getColumnClass(int column) {
return getModel().getColumnClass(convertColumnIndexToModel(column));
}
/** {@collect.stats}
* Returns the cell value at <code>row</code> and <code>column</code>.
* <p>
* <b>Note</b>: The column is specified in the table view's display
* order, and not in the <code>TableModel</code>'s column
* order. This is an important distinction because as the
* user rearranges the columns in the table,
* the column at a given index in the view will change.
* Meanwhile the user's actions never affect the model's
* column ordering.
*
* @param row the row whose value is to be queried
* @param column the column whose value is to be queried
* @return the Object at the specified cell
*/
public Object getValueAt(int row, int column) {
return getModel().getValueAt(convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
/** {@collect.stats}
* Sets the value for the cell in the table model at <code>row</code>
* and <code>column</code>.
* <p>
* <b>Note</b>: The column is specified in the table view's display
* order, and not in the <code>TableModel</code>'s column
* order. This is an important distinction because as the
* user rearranges the columns in the table,
* the column at a given index in the view will change.
* Meanwhile the user's actions never affect the model's
* column ordering.
*
* <code>aValue</code> is the new value.
*
* @param aValue the new value
* @param row the row of the cell to be changed
* @param column the column of the cell to be changed
* @see #getValueAt
*/
public void setValueAt(Object aValue, int row, int column) {
getModel().setValueAt(aValue, convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
/** {@collect.stats}
* Returns true if the cell at <code>row</code> and <code>column</code>
* is editable. Otherwise, invoking <code>setValueAt</code> on the cell
* will have no effect.
* <p>
* <b>Note</b>: The column is specified in the table view's display
* order, and not in the <code>TableModel</code>'s column
* order. This is an important distinction because as the
* user rearranges the columns in the table,
* the column at a given index in the view will change.
* Meanwhile the user's actions never affect the model's
* column ordering.
*
*
* @param row the row whose value is to be queried
* @param column the column whose value is to be queried
* @return true if the cell is editable
* @see #setValueAt
*/
public boolean isCellEditable(int row, int column) {
return getModel().isCellEditable(convertRowIndexToModel(row),
convertColumnIndexToModel(column));
}
//
// Adding and removing columns in the view
//
/** {@collect.stats}
* Appends <code>aColumn</code> to the end of the array of columns held by
* this <code>JTable</code>'s column model.
* If the column name of <code>aColumn</code> is <code>null</code>,
* sets the column name of <code>aColumn</code> to the name
* returned by <code>getModel().getColumnName()</code>.
* <p>
* To add a column to this <code>JTable</code> to display the
* <code>modelColumn</code>'th column of data in the model with a
* given <code>width</code>, <code>cellRenderer</code>,
* and <code>cellEditor</code> you can use:
* <pre>
*
* addColumn(new TableColumn(modelColumn, width, cellRenderer, cellEditor));
*
* </pre>
* [Any of the <code>TableColumn</code> constructors can be used
* instead of this one.]
* The model column number is stored inside the <code>TableColumn</code>
* and is used during rendering and editing to locate the appropriates
* data values in the model. The model column number does not change
* when columns are reordered in the view.
*
* @param aColumn the <code>TableColumn</code> to be added
* @see #removeColumn
*/
public void addColumn(TableColumn aColumn) {
if (aColumn.getHeaderValue() == null) {
int modelColumn = aColumn.getModelIndex();
String columnName = getModel().getColumnName(modelColumn);
aColumn.setHeaderValue(columnName);
}
getColumnModel().addColumn(aColumn);
}
/** {@collect.stats}
* Removes <code>aColumn</code> from this <code>JTable</code>'s
* array of columns. Note: this method does not remove the column
* of data from the model; it just removes the <code>TableColumn</code>
* that was responsible for displaying it.
*
* @param aColumn the <code>TableColumn</code> to be removed
* @see #addColumn
*/
public void removeColumn(TableColumn aColumn) {
getColumnModel().removeColumn(aColumn);
}
/** {@collect.stats}
* Moves the column <code>column</code> to the position currently
* occupied by the column <code>targetColumn</code> in the view.
* The old column at <code>targetColumn</code> is
* shifted left or right to make room.
*
* @param column the index of column to be moved
* @param targetColumn the new index of the column
*/
public void moveColumn(int column, int targetColumn) {
getColumnModel().moveColumn(column, targetColumn);
}
//
// Cover methods for various models and helper methods
//
/** {@collect.stats}
* Returns the index of the column that <code>point</code> lies in,
* or -1 if the result is not in the range
* [0, <code>getColumnCount()</code>-1].
*
* @param point the location of interest
* @return the index of the column that <code>point</code> lies in,
* or -1 if the result is not in the range
* [0, <code>getColumnCount()</code>-1]
* @see #rowAtPoint
*/
public int columnAtPoint(Point point) {
int x = point.x;
if( !getComponentOrientation().isLeftToRight() ) {
x = getWidth() - x - 1;
}
return getColumnModel().getColumnIndexAtX(x);
}
/** {@collect.stats}
* Returns the index of the row that <code>point</code> lies in,
* or -1 if the result is not in the range
* [0, <code>getRowCount()</code>-1].
*
* @param point the location of interest
* @return the index of the row that <code>point</code> lies in,
* or -1 if the result is not in the range
* [0, <code>getRowCount()</code>-1]
* @see #columnAtPoint
*/
public int rowAtPoint(Point point) {
int y = point.y;
int result = (rowModel == null) ? y/getRowHeight() : rowModel.getIndex(y);
if (result < 0) {
return -1;
}
else if (result >= getRowCount()) {
return -1;
}
else {
return result;
}
}
/** {@collect.stats}
* Returns a rectangle for the cell that lies at the intersection of
* <code>row</code> and <code>column</code>.
* If <code>includeSpacing</code> is true then the value returned
* has the full height and width of the row and column
* specified. If it is false, the returned rectangle is inset by the
* intercell spacing to return the true bounds of the rendering or
* editing component as it will be set during rendering.
* <p>
* If the column index is valid but the row index is less
* than zero the method returns a rectangle with the
* <code>y</code> and <code>height</code> values set appropriately
* and the <code>x</code> and <code>width</code> values both set
* to zero. In general, when either the row or column indices indicate a
* cell outside the appropriate range, the method returns a rectangle
* depicting the closest edge of the closest cell that is within
* the table's range. When both row and column indices are out
* of range the returned rectangle covers the closest
* point of the closest cell.
* <p>
* In all cases, calculations that use this method to calculate
* results along one axis will not fail because of anomalies in
* calculations along the other axis. When the cell is not valid
* the <code>includeSpacing</code> parameter is ignored.
*
* @param row the row index where the desired cell
* is located
* @param column the column index where the desired cell
* is located in the display; this is not
* necessarily the same as the column index
* in the data model for the table; the
* {@link #convertColumnIndexToView(int)}
* method may be used to convert a data
* model column index to a display
* column index
* @param includeSpacing if false, return the true cell bounds -
* computed by subtracting the intercell
* spacing from the height and widths of
* the column and row models
*
* @return the rectangle containing the cell at location
* <code>row</code>,<code>column</code>
* @see #getIntercellSpacing
*/
public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
Rectangle r = new Rectangle();
boolean valid = true;
if (row < 0) {
// y = height = 0;
valid = false;
}
else if (row >= getRowCount()) {
r.y = getHeight();
valid = false;
}
else {
r.height = getRowHeight(row);
r.y = (rowModel == null) ? row * r.height : rowModel.getPosition(row);
}
if (column < 0) {
if( !getComponentOrientation().isLeftToRight() ) {
r.x = getWidth();
}
// otherwise, x = width = 0;
valid = false;
}
else if (column >= getColumnCount()) {
if( getComponentOrientation().isLeftToRight() ) {
r.x = getWidth();
}
// otherwise, x = width = 0;
valid = false;
}
else {
TableColumnModel cm = getColumnModel();
if( getComponentOrientation().isLeftToRight() ) {
for(int i = 0; i < column; i++) {
r.x += cm.getColumn(i).getWidth();
}
} else {
for(int i = cm.getColumnCount()-1; i > column; i--) {
r.x += cm.getColumn(i).getWidth();
}
}
r.width = cm.getColumn(column).getWidth();
}
if (valid && !includeSpacing) {
// Bound the margins by their associated dimensions to prevent
// returning bounds with negative dimensions.
int rm = Math.min(getRowMargin(), r.height);
int cm = Math.min(getColumnModel().getColumnMargin(), r.width);
// This is not the same as grow(), it rounds differently.
r.setBounds(r.x + cm/2, r.y + rm/2, r.width - cm, r.height - rm);
}
return r;
}
private int viewIndexForColumn(TableColumn aColumn) {
TableColumnModel cm = getColumnModel();
for (int column = 0; column < cm.getColumnCount(); column++) {
if (cm.getColumn(column) == aColumn) {
return column;
}
}
return -1;
}
/** {@collect.stats}
* Causes this table to lay out its rows and columns. Overridden so
* that columns can be resized to accomodate a change in the size of
* a containing parent.
* Resizes one or more of the columns in the table
* so that the total width of all of this <code>JTable</code>'s
* columns is equal to the width of the table.
* <p>
* Before the layout begins the method gets the
* <code>resizingColumn</code> of the <code>tableHeader</code>.
* When the method is called as a result of the resizing of an enclosing window,
* the <code>resizingColumn</code> is <code>null</code>. This means that resizing
* has taken place "outside" the <code>JTable</code> and the change -
* or "delta" - should be distributed to all of the columns regardless
* of this <code>JTable</code>'s automatic resize mode.
* <p>
* If the <code>resizingColumn</code> is not <code>null</code>, it is one of
* the columns in the table that has changed size rather than
* the table itself. In this case the auto-resize modes govern
* the way the extra (or deficit) space is distributed
* amongst the available columns.
* <p>
* The modes are:
* <ul>
* <li> AUTO_RESIZE_OFF: Don't automatically adjust the column's
* widths at all. Use a horizontal scrollbar to accomodate the
* columns when their sum exceeds the width of the
* <code>Viewport</code>. If the <code>JTable</code> is not
* enclosed in a <code>JScrollPane</code> this may
* leave parts of the table invisible.
* <li> AUTO_RESIZE_NEXT_COLUMN: Use just the column after the
* resizing column. This results in the "boundary" or divider
* between adjacent cells being independently adjustable.
* <li> AUTO_RESIZE_SUBSEQUENT_COLUMNS: Use all columns after the
* one being adjusted to absorb the changes. This is the
* default behavior.
* <li> AUTO_RESIZE_LAST_COLUMN: Automatically adjust the
* size of the last column only. If the bounds of the last column
* prevent the desired size from being allocated, set the
* width of the last column to the appropriate limit and make
* no further adjustments.
* <li> AUTO_RESIZE_ALL_COLUMNS: Spread the delta amongst all the columns
* in the <code>JTable</code>, including the one that is being
* adjusted.
* </ul>
* <p>
* <bold>Note:</bold> When a <code>JTable</code> makes adjustments
* to the widths of the columns it respects their minimum and
* maximum values absolutely. It is therefore possible that,
* even after this method is called, the total width of the columns
* is still not equal to the width of the table. When this happens
* the <code>JTable</code> does not put itself
* in AUTO_RESIZE_OFF mode to bring up a scroll bar, or break other
* commitments of its current auto-resize mode -- instead it
* allows its bounds to be set larger (or smaller) than the total of the
* column minimum or maximum, meaning, either that there
* will not be enough room to display all of the columns, or that the
* columns will not fill the <code>JTable</code>'s bounds.
* These respectively, result in the clipping of some columns
* or an area being painted in the <code>JTable</code>'s
* background color during painting.
* <p>
* The mechanism for distributing the delta amongst the available
* columns is provided in a private method in the <code>JTable</code>
* class:
* <pre>
* adjustSizes(long targetSize, final Resizable3 r, boolean inverse)
* </pre>
* an explanation of which is provided in the following section.
* <code>Resizable3</code> is a private
* interface that allows any data structure containing a collection
* of elements with a size, preferred size, maximum size and minimum size
* to have its elements manipulated by the algorithm.
* <p>
* <H3> Distributing the delta </H3>
* <p>
* <H4> Overview </H4>
* <P>
* Call "DELTA" the difference between the target size and the
* sum of the preferred sizes of the elements in r. The individual
* sizes are calculated by taking the original preferred
* sizes and adding a share of the DELTA - that share being based on
* how far each preferred size is from its limiting bound (minimum or
* maximum).
* <p>
* <H4>Definition</H4>
* <P>
* Call the individual constraints min[i], max[i], and pref[i].
* <p>
* Call their respective sums: MIN, MAX, and PREF.
* <p>
* Each new size will be calculated using:
* <p>
* <pre>
* size[i] = pref[i] + delta[i]
* </pre>
* where each individual delta[i] is calculated according to:
* <p>
* If (DELTA < 0) we are in shrink mode where:
* <p>
* <PRE>
* DELTA
* delta[i] = ------------ * (pref[i] - min[i])
* (PREF - MIN)
* </PRE>
* If (DELTA > 0) we are in expand mode where:
* <p>
* <PRE>
* DELTA
* delta[i] = ------------ * (max[i] - pref[i])
* (MAX - PREF)
* </PRE>
* <P>
* The overall effect is that the total size moves that same percentage,
* k, towards the total minimum or maximum and that percentage guarantees
* accomodation of the required space, DELTA.
*
* <H4>Details</H4>
* <P>
* Naive evaluation of the formulae presented here would be subject to
* the aggregated rounding errors caused by doing this operation in finite
* precision (using ints). To deal with this, the multiplying factor above,
* is constantly recalculated and this takes account of the rounding
* errors in the previous iterations. The result is an algorithm that
* produces a set of integers whose values exactly sum to the supplied
* <code>targetSize</code>, and does so by spreading the rounding
* errors evenly over the given elements.
*
* <H4>When the MAX and MIN bounds are hit</H4>
* <P>
* When <code>targetSize</code> is outside the [MIN, MAX] range,
* the algorithm sets all sizes to their appropriate limiting value
* (maximum or minimum).
*
*/
public void doLayout() {
TableColumn resizingColumn = getResizingColumn();
if (resizingColumn == null) {
setWidthsFromPreferredWidths(false);
}
else {
// JTable behaves like a layout manger - but one in which the
// user can come along and dictate how big one of the children
// (columns) is supposed to be.
// A column has been resized and JTable may need to distribute
// any overall delta to other columns, according to the resize mode.
int columnIndex = viewIndexForColumn(resizingColumn);
int delta = getWidth() - getColumnModel().getTotalColumnWidth();
accommodateDelta(columnIndex, delta);
delta = getWidth() - getColumnModel().getTotalColumnWidth();
// If the delta cannot be completely accomodated, then the
// resizing column will have to take any remainder. This means
// that the column is not being allowed to take the requested
// width. This happens under many circumstances: For example,
// AUTO_RESIZE_NEXT_COLUMN specifies that any delta be distributed
// to the column after the resizing column. If one were to attempt
// to resize the last column of the table, there would be no
// columns after it, and hence nowhere to distribute the delta.
// It would then be given entirely back to the resizing column,
// preventing it from changing size.
if (delta != 0) {
resizingColumn.setWidth(resizingColumn.getWidth() + delta);
}
// At this point the JTable has to work out what preferred sizes
// would have resulted in the layout the user has chosen.
// Thereafter, during window resizing etc. it has to work off
// the preferred sizes as usual - the idea being that, whatever
// the user does, everything stays in synch and things don't jump
// around.
setWidthsFromPreferredWidths(true);
}
super.doLayout();
}
private TableColumn getResizingColumn() {
return (tableHeader == null) ? null
: tableHeader.getResizingColumn();
}
/** {@collect.stats}
* Sizes the table columns to fit the available space.
* @deprecated As of Swing version 1.0.3,
* replaced by <code>doLayout()</code>.
* @see #doLayout
*/
@Deprecated
public void sizeColumnsToFit(boolean lastColumnOnly) {
int oldAutoResizeMode = autoResizeMode;
setAutoResizeMode(lastColumnOnly ? AUTO_RESIZE_LAST_COLUMN
: AUTO_RESIZE_ALL_COLUMNS);
sizeColumnsToFit(-1);
setAutoResizeMode(oldAutoResizeMode);
}
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.4. Please use the
* <code>doLayout()</code> method instead.
* @param resizingColumn the column whose resizing made this adjustment
* necessary or -1 if there is no such column
* @see #doLayout
*/
public void sizeColumnsToFit(int resizingColumn) {
if (resizingColumn == -1) {
setWidthsFromPreferredWidths(false);
}
else {
if (autoResizeMode == AUTO_RESIZE_OFF) {
TableColumn aColumn = getColumnModel().getColumn(resizingColumn);
aColumn.setPreferredWidth(aColumn.getWidth());
}
else {
int delta = getWidth() - getColumnModel().getTotalColumnWidth();
accommodateDelta(resizingColumn, delta);
setWidthsFromPreferredWidths(true);
}
}
}
private void setWidthsFromPreferredWidths(final boolean inverse) {
int totalWidth = getWidth();
int totalPreferred = getPreferredSize().width;
int target = !inverse ? totalWidth : totalPreferred;
final TableColumnModel cm = columnModel;
Resizable3 r = new Resizable3() {
public int getElementCount() { return cm.getColumnCount(); }
public int getLowerBoundAt(int i) { return cm.getColumn(i).getMinWidth(); }
public int getUpperBoundAt(int i) { return cm.getColumn(i).getMaxWidth(); }
public int getMidPointAt(int i) {
if (!inverse) {
return cm.getColumn(i).getPreferredWidth();
}
else {
return cm.getColumn(i).getWidth();
}
}
public void setSizeAt(int s, int i) {
if (!inverse) {
cm.getColumn(i).setWidth(s);
}
else {
cm.getColumn(i).setPreferredWidth(s);
}
}
};
adjustSizes(target, r, inverse);
}
// Distribute delta over columns, as indicated by the autoresize mode.
private void accommodateDelta(int resizingColumnIndex, int delta) {
int columnCount = getColumnCount();
int from = resizingColumnIndex;
int to = columnCount;
// Use the mode to determine how to absorb the changes.
switch(autoResizeMode) {
case AUTO_RESIZE_NEXT_COLUMN:
from = from + 1;
to = Math.min(from + 1, columnCount); break;
case AUTO_RESIZE_SUBSEQUENT_COLUMNS:
from = from + 1;
to = columnCount; break;
case AUTO_RESIZE_LAST_COLUMN:
from = columnCount - 1;
to = from + 1; break;
case AUTO_RESIZE_ALL_COLUMNS:
from = 0;
to = columnCount; break;
default:
return;
}
final int start = from;
final int end = to;
final TableColumnModel cm = columnModel;
Resizable3 r = new Resizable3() {
public int getElementCount() { return end-start; }
public int getLowerBoundAt(int i) { return cm.getColumn(i+start).getMinWidth(); }
public int getUpperBoundAt(int i) { return cm.getColumn(i+start).getMaxWidth(); }
public int getMidPointAt(int i) { return cm.getColumn(i+start).getWidth(); }
public void setSizeAt(int s, int i) { cm.getColumn(i+start).setWidth(s); }
};
int totalWidth = 0;
for(int i = from; i < to; i++) {
TableColumn aColumn = columnModel.getColumn(i);
int input = aColumn.getWidth();
totalWidth = totalWidth + input;
}
adjustSizes(totalWidth + delta, r, false);
return;
}
private interface Resizable2 {
public int getElementCount();
public int getLowerBoundAt(int i);
public int getUpperBoundAt(int i);
public void setSizeAt(int newSize, int i);
}
private interface Resizable3 extends Resizable2 {
public int getMidPointAt(int i);
}
private void adjustSizes(long target, final Resizable3 r, boolean inverse) {
int N = r.getElementCount();
long totalPreferred = 0;
for(int i = 0; i < N; i++) {
totalPreferred += r.getMidPointAt(i);
}
Resizable2 s;
if ((target < totalPreferred) == !inverse) {
s = new Resizable2() {
public int getElementCount() { return r.getElementCount(); }
public int getLowerBoundAt(int i) { return r.getLowerBoundAt(i); }
public int getUpperBoundAt(int i) { return r.getMidPointAt(i); }
public void setSizeAt(int newSize, int i) { r.setSizeAt(newSize, i); }
};
}
else {
s = new Resizable2() {
public int getElementCount() { return r.getElementCount(); }
public int getLowerBoundAt(int i) { return r.getMidPointAt(i); }
public int getUpperBoundAt(int i) { return r.getUpperBoundAt(i); }
public void setSizeAt(int newSize, int i) { r.setSizeAt(newSize, i); }
};
}
adjustSizes(target, s, !inverse);
}
private void adjustSizes(long target, Resizable2 r, boolean limitToRange) {
long totalLowerBound = 0;
long totalUpperBound = 0;
for(int i = 0; i < r.getElementCount(); i++) {
totalLowerBound += r.getLowerBoundAt(i);
totalUpperBound += r.getUpperBoundAt(i);
}
if (limitToRange) {
target = Math.min(Math.max(totalLowerBound, target), totalUpperBound);
}
for(int i = 0; i < r.getElementCount(); i++) {
int lowerBound = r.getLowerBoundAt(i);
int upperBound = r.getUpperBoundAt(i);
// Check for zero. This happens when the distribution of the delta
// finishes early due to a series of "fixed" entries at the end.
// In this case, lowerBound == upperBound, for all subsequent terms.
int newSize;
if (totalLowerBound == totalUpperBound) {
newSize = lowerBound;
}
else {
double f = (double)(target - totalLowerBound)/(totalUpperBound - totalLowerBound);
newSize = (int)Math.round(lowerBound+f*(upperBound - lowerBound));
// We'd need to round manually in an all integer version.
// size[i] = (int)(((totalUpperBound - target) * lowerBound +
// (target - totalLowerBound) * upperBound)/(totalUpperBound-totalLowerBound));
}
r.setSizeAt(newSize, i);
target -= newSize;
totalLowerBound -= lowerBound;
totalUpperBound -= upperBound;
}
}
/** {@collect.stats}
* Overrides <code>JComponent</code>'s <code>getToolTipText</code>
* method in order to allow the renderer's tips to be used
* if it has text set.
* <p>
* <bold>Note:</bold> For <code>JTable</code> to properly display
* tooltips of its renderers
* <code>JTable</code> must be a registered component with the
* <code>ToolTipManager</code>.
* This is done automatically in <code>initializeLocalVars</code>,
* but if at a later point <code>JTable</code> is told
* <code>setToolTipText(null)</code> it will unregister the table
* component, and no tips from renderers will display anymore.
*
* @see JComponent#getToolTipText
*/
public String getToolTipText(MouseEvent event) {
String tip = null;
Point p = event.getPoint();
// Locate the renderer under the event location
int hitColumnIndex = columnAtPoint(p);
int hitRowIndex = rowAtPoint(p);
if ((hitColumnIndex != -1) && (hitRowIndex != -1)) {
TableCellRenderer renderer = getCellRenderer(hitRowIndex, hitColumnIndex);
Component component = prepareRenderer(renderer, hitRowIndex, hitColumnIndex);
// Now have to see if the component is a JComponent before
// getting the tip
if (component instanceof JComponent) {
// Convert the event to the renderer's coordinate system
Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false);
p.translate(-cellRect.x, -cellRect.y);
MouseEvent newEvent = new MouseEvent(component, event.getID(),
event.getWhen(), event.getModifiers(),
p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
tip = ((JComponent)component).getToolTipText(newEvent);
}
}
// No tip from the renderer get our own tip
if (tip == null)
tip = getToolTipText();
return tip;
}
//
// Editing Support
//
/** {@collect.stats}
* Sets whether editors in this JTable get the keyboard focus
* when an editor is activated as a result of the JTable
* forwarding keyboard events for a cell.
* By default, this property is false, and the JTable
* retains the focus unless the cell is clicked.
*
* @param surrendersFocusOnKeystroke true if the editor should get the focus
* when keystrokes cause the editor to be
* activated
*
*
* @see #getSurrendersFocusOnKeystroke
* @since 1.4
*/
public void setSurrendersFocusOnKeystroke(boolean surrendersFocusOnKeystroke) {
this.surrendersFocusOnKeystroke = surrendersFocusOnKeystroke;
}
/** {@collect.stats}
* Returns true if the editor should get the focus
* when keystrokes cause the editor to be activated
*
* @return true if the editor should get the focus
* when keystrokes cause the editor to be
* activated
*
* @see #setSurrendersFocusOnKeystroke
* @since 1.4
*/
public boolean getSurrendersFocusOnKeystroke() {
return surrendersFocusOnKeystroke;
}
/** {@collect.stats}
* Programmatically starts editing the cell at <code>row</code> and
* <code>column</code>, if those indices are in the valid range, and
* the cell at those indices is editable.
* Note that this is a convenience method for
* <code>editCellAt(int, int, null)</code>.
*
* @param row the row to be edited
* @param column the column to be edited
* @return false if for any reason the cell cannot be edited,
* or if the indices are invalid
*/
public boolean editCellAt(int row, int column) {
return editCellAt(row, column, null);
}
/** {@collect.stats}
* Programmatically starts editing the cell at <code>row</code> and
* <code>column</code>, if those indices are in the valid range, and
* the cell at those indices is editable.
* To prevent the <code>JTable</code> from
* editing a particular table, column or cell value, return false from
* the <code>isCellEditable</code> method in the <code>TableModel</code>
* interface.
*
* @param row the row to be edited
* @param column the column to be edited
* @param e event to pass into <code>shouldSelectCell</code>;
* note that as of Java 2 platform v1.2, the call to
* <code>shouldSelectCell</code> is no longer made
* @return false if for any reason the cell cannot be edited,
* or if the indices are invalid
*/
public boolean editCellAt(int row, int column, EventObject e){
if (cellEditor != null && !cellEditor.stopCellEditing()) {
return false;
}
if (row < 0 || row >= getRowCount() ||
column < 0 || column >= getColumnCount()) {
return false;
}
if (!isCellEditable(row, column))
return false;
if (editorRemover == null) {
KeyboardFocusManager fm =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
editorRemover = new CellEditorRemover(fm);
fm.addPropertyChangeListener("permanentFocusOwner", editorRemover);
}
TableCellEditor editor = getCellEditor(row, column);
if (editor != null && editor.isCellEditable(e)) {
editorComp = prepareEditor(editor, row, column);
if (editorComp == null) {
removeEditor();
return false;
}
editorComp.setBounds(getCellRect(row, column, false));
add(editorComp);
editorComp.validate();
editorComp.repaint();
setCellEditor(editor);
setEditingRow(row);
setEditingColumn(column);
editor.addCellEditorListener(this);
return true;
}
return false;
}
/** {@collect.stats}
* Returns true if a cell is being edited.
*
* @return true if the table is editing a cell
* @see #editingColumn
* @see #editingRow
*/
public boolean isEditing() {
return (cellEditor == null)? false : true;
}
/** {@collect.stats}
* Returns the component that is handling the editing session.
* If nothing is being edited, returns null.
*
* @return Component handling editing session
*/
public Component getEditorComponent() {
return editorComp;
}
/** {@collect.stats}
* Returns the index of the column that contains the cell currently
* being edited. If nothing is being edited, returns -1.
*
* @return the index of the column that contains the cell currently
* being edited; returns -1 if nothing being edited
* @see #editingRow
*/
public int getEditingColumn() {
return editingColumn;
}
/** {@collect.stats}
* Returns the index of the row that contains the cell currently
* being edited. If nothing is being edited, returns -1.
*
* @return the index of the row that contains the cell currently
* being edited; returns -1 if nothing being edited
* @see #editingColumn
*/
public int getEditingRow() {
return editingRow;
}
//
// Managing TableUI
//
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the <code>TableUI</code> object that renders this component
*/
public TableUI getUI() {
return (TableUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component and repaints.
*
* @param ui the TableUI L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(TableUI ui) {
if (this.ui != ui) {
super.setUI(ui);
repaint();
}
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
// Update the UIs of the cell renderers, cell editors and header renderers.
TableColumnModel cm = getColumnModel();
for(int column = 0; column < cm.getColumnCount(); column++) {
TableColumn aColumn = cm.getColumn(column);
SwingUtilities.updateRendererOrEditorUI(aColumn.getCellRenderer());
SwingUtilities.updateRendererOrEditorUI(aColumn.getCellEditor());
SwingUtilities.updateRendererOrEditorUI(aColumn.getHeaderRenderer());
}
// Update the UIs of all the default renderers.
Enumeration defaultRenderers = defaultRenderersByColumnClass.elements();
while (defaultRenderers.hasMoreElements()) {
SwingUtilities.updateRendererOrEditorUI(defaultRenderers.nextElement());
}
// Update the UIs of all the default editors.
Enumeration defaultEditors = defaultEditorsByColumnClass.elements();
while (defaultEditors.hasMoreElements()) {
SwingUtilities.updateRendererOrEditorUI(defaultEditors.nextElement());
}
// Update the UI of the table header
if (tableHeader != null && tableHeader.getParent() == null) {
tableHeader.updateUI();
}
// Update UI applied to parent ScrollPane
configureEnclosingScrollPaneUI();
setUI((TableUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the suffix used to construct the name of the L&F class used to
* render this component.
*
* @return the string "TableUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
//
// Managing models
//
/** {@collect.stats}
* Sets the data model for this table to <code>newModel</code> and registers
* with it for listener notifications from the new data model.
*
* @param dataModel the new data source for this table
* @exception IllegalArgumentException if <code>newModel</code> is <code>null</code>
* @see #getModel
* @beaninfo
* bound: true
* description: The model that is the source of the data for this view.
*/
public void setModel(TableModel dataModel) {
if (dataModel == null) {
throw new IllegalArgumentException("Cannot set a null TableModel");
}
if (this.dataModel != dataModel) {
TableModel old = this.dataModel;
if (old != null) {
old.removeTableModelListener(this);
}
this.dataModel = dataModel;
dataModel.addTableModelListener(this);
tableChanged(new TableModelEvent(dataModel, TableModelEvent.HEADER_ROW));
firePropertyChange("model", old, dataModel);
if (getAutoCreateRowSorter()) {
setRowSorter(new TableRowSorter(dataModel));
}
}
}
/** {@collect.stats}
* Returns the <code>TableModel</code> that provides the data displayed by this
* <code>JTable</code>.
*
* @return the <code>TableModel</code> that provides the data displayed by this <code>JTable</code>
* @see #setModel
*/
public TableModel getModel() {
return dataModel;
}
/** {@collect.stats}
* Sets the column model for this table to <code>newModel</code> and registers
* for listener notifications from the new column model. Also sets
* the column model of the <code>JTableHeader</code> to <code>columnModel</code>.
*
* @param columnModel the new data source for this table
* @exception IllegalArgumentException if <code>columnModel</code> is <code>null</code>
* @see #getColumnModel
* @beaninfo
* bound: true
* description: The object governing the way columns appear in the view.
*/
public void setColumnModel(TableColumnModel columnModel) {
if (columnModel == null) {
throw new IllegalArgumentException("Cannot set a null ColumnModel");
}
TableColumnModel old = this.columnModel;
if (columnModel != old) {
if (old != null) {
old.removeColumnModelListener(this);
}
this.columnModel = columnModel;
columnModel.addColumnModelListener(this);
// Set the column model of the header as well.
if (tableHeader != null) {
tableHeader.setColumnModel(columnModel);
}
firePropertyChange("columnModel", old, columnModel);
resizeAndRepaint();
}
}
/** {@collect.stats}
* Returns the <code>TableColumnModel</code> that contains all column information
* of this table.
*
* @return the object that provides the column state of the table
* @see #setColumnModel
*/
public TableColumnModel getColumnModel() {
return columnModel;
}
/** {@collect.stats}
* Sets the row selection model for this table to <code>newModel</code>
* and registers for listener notifications from the new selection model.
*
* @param newModel the new selection model
* @exception IllegalArgumentException if <code>newModel</code> is <code>null</code>
* @see #getSelectionModel
* @beaninfo
* bound: true
* description: The selection model for rows.
*/
public void setSelectionModel(ListSelectionModel newModel) {
if (newModel == null) {
throw new IllegalArgumentException("Cannot set a null SelectionModel");
}
ListSelectionModel oldModel = selectionModel;
if (newModel != oldModel) {
if (oldModel != null) {
oldModel.removeListSelectionListener(this);
}
selectionModel = newModel;
newModel.addListSelectionListener(this);
firePropertyChange("selectionModel", oldModel, newModel);
repaint();
}
}
/** {@collect.stats}
* Returns the <code>ListSelectionModel</code> that is used to maintain row
* selection state.
*
* @return the object that provides row selection state, <code>null</code>
* if row selection is not allowed
* @see #setSelectionModel
*/
public ListSelectionModel getSelectionModel() {
return selectionModel;
}
//
// RowSorterListener
//
/** {@collect.stats}
* <code>RowSorterListener</code> notification that the
* <code>RowSorter</code> has changed in some way.
*
* @param e the <code>RowSorterEvent</code> describing the change
* @throws NullPointerException if <code>e</code> is <code>null</code>
* @since 1.6
*/
public void sorterChanged(RowSorterEvent e) {
if (e.getType() == RowSorterEvent.Type.SORT_ORDER_CHANGED) {
JTableHeader header = getTableHeader();
if (header != null) {
header.repaint();
}
}
else if (e.getType() == RowSorterEvent.Type.SORTED) {
sorterChanged = true;
if (!ignoreSortChange) {
sortedTableChanged(e, null);
}
}
}
/** {@collect.stats}
* SortManager provides support for managing the selection and variable
* row heights when sorting is enabled. This information is encapsulated
* into a class to avoid bulking up JTable.
*/
private final class SortManager {
RowSorter<? extends TableModel> sorter;
// Selection, in terms of the model. This is lazily created
// as needed.
private ListSelectionModel modelSelection;
private int modelLeadIndex;
// Set to true while in the process of changing the selection.
// If this is true the selection change is ignored.
private boolean syncingSelection;
// Temporary cache of selection, in terms of model. This is only used
// if we don't need the full weight of modelSelection.
private int[] lastModelSelection;
// Heights of the rows in terms of the model.
private SizeSequence modelRowSizes;
SortManager(RowSorter<? extends TableModel> sorter) {
this.sorter = sorter;
sorter.addRowSorterListener(JTable.this);
}
/** {@collect.stats}
* Disposes any resources used by this SortManager.
*/
public void dispose() {
if (sorter != null) {
sorter.removeRowSorterListener(JTable.this);
}
}
/** {@collect.stats}
* Sets the height for a row at a specified index.
*/
public void setViewRowHeight(int viewIndex, int rowHeight) {
if (modelRowSizes == null) {
modelRowSizes = new SizeSequence(getModel().getRowCount(),
getRowHeight());
}
modelRowSizes.setSize(convertRowIndexToModel(viewIndex),rowHeight);
}
/** {@collect.stats}
* Invoked when the underlying model has completely changed.
*/
public void allChanged() {
modelLeadIndex = -1;
modelSelection = null;
modelRowSizes = null;
}
/** {@collect.stats}
* Invoked when the selection, on the view, has changed.
*/
public void viewSelectionChanged(ListSelectionEvent e) {
if (!syncingSelection && modelSelection != null) {
modelSelection = null;
}
}
/** {@collect.stats}
* Invoked when either the table model has changed, or the RowSorter
* has changed. This is invoked prior to notifying the sorter of the
* change.
*/
public void prepareForChange(RowSorterEvent sortEvent,
ModelChange change) {
if (getUpdateSelectionOnSort()) {
cacheSelection(sortEvent, change);
}
}
/** {@collect.stats}
* Updates the internal cache of the selection based on the change.
*/
private void cacheSelection(RowSorterEvent sortEvent,
ModelChange change) {
if (sortEvent != null) {
// sort order changed. If modelSelection is null and filtering
// is enabled we need to cache the selection in terms of the
// underlying model, this will allow us to correctly restore
// the selection even if rows are filtered out.
if (modelSelection == null &&
sorter.getViewRowCount() != getModel().getRowCount()) {
modelSelection = new DefaultListSelectionModel();
ListSelectionModel viewSelection = getSelectionModel();
int min = viewSelection.getMinSelectionIndex();
int max = viewSelection.getMaxSelectionIndex();
int modelIndex;
for (int viewIndex = min; viewIndex <= max; viewIndex++) {
if (viewSelection.isSelectedIndex(viewIndex)) {
modelIndex = convertRowIndexToModel(
sortEvent, viewIndex);
if (modelIndex != -1) {
modelSelection.addSelectionInterval(
modelIndex, modelIndex);
}
}
}
modelIndex = convertRowIndexToModel(sortEvent,
viewSelection.getLeadSelectionIndex());
SwingUtilities2.setLeadAnchorWithoutSelection(
modelSelection, modelIndex, modelIndex);
} else if (modelSelection == null) {
// Sorting changed, haven't cached selection in terms
// of model and no filtering. Temporarily cache selection.
cacheModelSelection(sortEvent);
}
} else if (change.allRowsChanged) {
// All the rows have changed, chuck any cached selection.
modelSelection = null;
} else if (modelSelection != null) {
// Table changed, reflect changes in cached selection model.
switch(change.type) {
case TableModelEvent.DELETE:
modelSelection.removeIndexInterval(change.startModelIndex,
change.endModelIndex);
break;
case TableModelEvent.INSERT:
modelSelection.insertIndexInterval(change.startModelIndex,
change.endModelIndex,
true);
break;
default:
break;
}
} else {
// table changed, but haven't cached rows, temporarily
// cache them.
cacheModelSelection(null);
}
}
private void cacheModelSelection(RowSorterEvent sortEvent) {
lastModelSelection = convertSelectionToModel(sortEvent);
modelLeadIndex = convertRowIndexToModel(sortEvent,
selectionModel.getLeadSelectionIndex());
}
/** {@collect.stats}
* Inovked when either the table has changed or the sorter has changed
* and after the sorter has been notified. If necessary this will
* reapply the selection and variable row heights.
*/
public void processChange(RowSorterEvent sortEvent,
ModelChange change,
boolean sorterChanged) {
if (change != null) {
if (change.allRowsChanged) {
modelRowSizes = null;
rowModel = null;
} else if (modelRowSizes != null) {
if (change.type == TableModelEvent.INSERT) {
modelRowSizes.insertEntries(change.startModelIndex,
change.endModelIndex -
change.startModelIndex + 1,
getRowHeight());
} else if (change.type == TableModelEvent.DELETE) {
modelRowSizes.removeEntries(change.startModelIndex,
change.endModelIndex -
change.startModelIndex +1 );
}
}
}
if (sorterChanged) {
setViewRowHeightsFromModel();
restoreSelection(change);
}
}
/** {@collect.stats}
* Resets the variable row heights in terms of the view from
* that of the variable row heights in terms of the model.
*/
private void setViewRowHeightsFromModel() {
if (modelRowSizes != null) {
rowModel.setSizes(getRowCount(), getRowHeight());
for (int viewIndex = getRowCount() - 1; viewIndex >= 0;
viewIndex--) {
int modelIndex = convertRowIndexToModel(viewIndex);
rowModel.setSize(viewIndex,
modelRowSizes.getSize(modelIndex));
}
}
}
/** {@collect.stats}
* Restores the selection from that in terms of the model.
*/
private void restoreSelection(ModelChange change) {
syncingSelection = true;
if (lastModelSelection != null) {
restoreSortingSelection(lastModelSelection,
modelLeadIndex, change);
lastModelSelection = null;
} else if (modelSelection != null) {
ListSelectionModel viewSelection = getSelectionModel();
viewSelection.setValueIsAdjusting(true);
viewSelection.clearSelection();
int min = modelSelection.getMinSelectionIndex();
int max = modelSelection.getMaxSelectionIndex();
int viewIndex;
for (int modelIndex = min; modelIndex <= max; modelIndex++) {
if (modelSelection.isSelectedIndex(modelIndex)) {
viewIndex = convertRowIndexToView(modelIndex);
if (viewIndex != -1) {
viewSelection.addSelectionInterval(viewIndex,
viewIndex);
}
}
}
// Restore the lead
int viewLeadIndex = modelSelection.getLeadSelectionIndex();
if (viewLeadIndex != -1) {
viewLeadIndex = convertRowIndexToView(viewLeadIndex);
}
SwingUtilities2.setLeadAnchorWithoutSelection(
viewSelection, viewLeadIndex, viewLeadIndex);
viewSelection.setValueIsAdjusting(false);
}
syncingSelection = false;
}
}
/** {@collect.stats}
* ModelChange is used when sorting to restore state, it corresponds
* to data from a TableModelEvent. The values are precalculated as
* they are used extensively.
*/
private final class ModelChange {
// Starting index of the change, in terms of the model
int startModelIndex;
// Ending index of the change, in terms of the model
int endModelIndex;
// Type of change
int type;
// Number of rows in the model
int modelRowCount;
// The event that triggered this.
TableModelEvent event;
// Length of the change (end - start + 1)
int length;
// True if the event indicates all the contents have changed
boolean allRowsChanged;
ModelChange(TableModelEvent e) {
startModelIndex = Math.max(0, e.getFirstRow());
endModelIndex = e.getLastRow();
modelRowCount = getModel().getRowCount();
if (endModelIndex < 0) {
endModelIndex = Math.max(0, modelRowCount - 1);
}
length = endModelIndex - startModelIndex + 1;
type = e.getType();
event = e;
allRowsChanged = (e.getLastRow() == Integer.MAX_VALUE);
}
}
/** {@collect.stats}
* Invoked when <code>sorterChanged</code> is invoked, or
* when <code>tableChanged</code> is invoked and sorting is enabled.
*/
private void sortedTableChanged(RowSorterEvent sortedEvent,
TableModelEvent e) {
int editingModelIndex = -1;
ModelChange change = (e != null) ? new ModelChange(e) : null;
if ((change == null || !change.allRowsChanged) &&
this.editingRow != -1) {
editingModelIndex = convertRowIndexToModel(sortedEvent,
this.editingRow);
}
sortManager.prepareForChange(sortedEvent, change);
if (e != null) {
if (change.type == TableModelEvent.UPDATE) {
repaintSortedRows(change);
}
notifySorter(change);
if (change.type != TableModelEvent.UPDATE) {
// If the Sorter is unsorted we will not have received
// notification, force treating insert/delete as a change.
sorterChanged = true;
}
}
else {
sorterChanged = true;
}
sortManager.processChange(sortedEvent, change, sorterChanged);
if (sorterChanged) {
// Update the editing row
if (this.editingRow != -1) {
int newIndex = (editingModelIndex == -1) ? -1 :
convertRowIndexToView(editingModelIndex,change);
restoreSortingEditingRow(newIndex);
}
// And handle the appropriate repainting.
if (e == null || change.type != TableModelEvent.UPDATE) {
resizeAndRepaint();
}
}
// Check if lead/anchor need to be reset.
if (change != null && change.allRowsChanged) {
clearSelectionAndLeadAnchor();
resizeAndRepaint();
}
}
/** {@collect.stats}
* Repaints the sort of sorted rows in response to a TableModelEvent.
*/
private void repaintSortedRows(ModelChange change) {
if (change.startModelIndex > change.endModelIndex ||
change.startModelIndex + 10 < change.endModelIndex) {
// Too much has changed, punt
repaint();
return;
}
int eventColumn = change.event.getColumn();
int columnViewIndex = eventColumn;
if (columnViewIndex == TableModelEvent.ALL_COLUMNS) {
columnViewIndex = 0;
}
else {
columnViewIndex = convertColumnIndexToView(columnViewIndex);
if (columnViewIndex == -1) {
return;
}
}
int modelIndex = change.startModelIndex;
while (modelIndex <= change.endModelIndex) {
int viewIndex = convertRowIndexToView(modelIndex++);
if (viewIndex != -1) {
Rectangle dirty = getCellRect(viewIndex, columnViewIndex,
false);
int x = dirty.x;
int w = dirty.width;
if (eventColumn == TableModelEvent.ALL_COLUMNS) {
x = 0;
w = getWidth();
}
repaint(x, dirty.y, w, dirty.height);
}
}
}
/** {@collect.stats}
* Restores the selection after a model event/sort order changes.
* All coordinates are in terms of the model.
*/
private void restoreSortingSelection(int[] selection, int lead,
ModelChange change) {
// Convert the selection from model to view
for (int i = selection.length - 1; i >= 0; i--) {
selection[i] = convertRowIndexToView(selection[i], change);
}
lead = convertRowIndexToView(lead, change);
// Check for the common case of no change in selection for 1 row
if (selection.length == 0 ||
(selection.length == 1 && selection[0] == getSelectedRow())) {
return;
}
// And apply the new selection
selectionModel.setValueIsAdjusting(true);
selectionModel.clearSelection();
for (int i = selection.length - 1; i >= 0; i--) {
if (selection[i] != -1) {
selectionModel.addSelectionInterval(selection[i],
selection[i]);
}
}
SwingUtilities2.setLeadAnchorWithoutSelection(
selectionModel, lead, lead);
selectionModel.setValueIsAdjusting(false);
}
/** {@collect.stats}
* Restores the editing row after a model event/sort order change.
*
* @param editingRow new index of the editingRow, in terms of the view
*/
private void restoreSortingEditingRow(int editingRow) {
if (editingRow == -1) {
// Editing row no longer being shown, cancel editing
TableCellEditor editor = getCellEditor();
if (editor != null) {
// First try and cancel
editor.cancelCellEditing();
if (getCellEditor() != null) {
// CellEditor didn't cede control, forcefully
// remove it
removeEditor();
}
}
}
else {
// Repositioning handled in BasicTableUI
this.editingRow = editingRow;
repaint();
}
}
/** {@collect.stats}
* Notifies the sorter of a change in the underlying model.
*/
private void notifySorter(ModelChange change) {
try {
ignoreSortChange = true;
sorterChanged = false;
switch(change.type) {
case TableModelEvent.UPDATE:
if (change.event.getLastRow() == Integer.MAX_VALUE) {
sortManager.sorter.allRowsChanged();
} else if (change.event.getColumn() ==
TableModelEvent.ALL_COLUMNS) {
sortManager.sorter.rowsUpdated(change.startModelIndex,
change.endModelIndex);
} else {
sortManager.sorter.rowsUpdated(change.startModelIndex,
change.endModelIndex,
change.event.getColumn());
}
break;
case TableModelEvent.INSERT:
sortManager.sorter.rowsInserted(change.startModelIndex,
change.endModelIndex);
break;
case TableModelEvent.DELETE:
sortManager.sorter.rowsDeleted(change.startModelIndex,
change.endModelIndex);
break;
}
} finally {
ignoreSortChange = false;
}
}
/** {@collect.stats}
* Converts a model index to view index. This is called when the
* sorter or model changes and sorting is enabled.
*
* @param change describes the TableModelEvent that initiated the change;
* will be null if called as the result of a sort
*/
private int convertRowIndexToView(int modelIndex, ModelChange change) {
if (modelIndex < 0) {
return -1;
}
if (change != null && modelIndex >= change.startModelIndex) {
if (change.type == TableModelEvent.INSERT) {
if (modelIndex + change.length >= change.modelRowCount) {
return -1;
}
return sortManager.sorter.convertRowIndexToView(
modelIndex + change.length);
}
else if (change.type == TableModelEvent.DELETE) {
if (modelIndex <= change.endModelIndex) {
// deleted
return -1;
}
else {
if (modelIndex - change.length >= change.modelRowCount) {
return -1;
}
return sortManager.sorter.convertRowIndexToView(
modelIndex - change.length);
}
}
// else, updated
}
if (modelIndex >= getModel().getRowCount()) {
return -1;
}
return sortManager.sorter.convertRowIndexToView(modelIndex);
}
/** {@collect.stats}
* Converts the selection to model coordinates. This is used when
* the model changes or the sorter changes.
*/
private int[] convertSelectionToModel(RowSorterEvent e) {
int[] selection = getSelectedRows();
for (int i = selection.length - 1; i >= 0; i--) {
selection[i] = convertRowIndexToModel(e, selection[i]);
}
return selection;
}
private int convertRowIndexToModel(RowSorterEvent e, int viewIndex) {
if (e != null) {
if (e.getPreviousRowCount() == 0) {
return viewIndex;
}
// range checking handled by RowSorterEvent
return e.convertPreviousRowIndexToModel(viewIndex);
}
// Make sure the viewIndex is valid
if (viewIndex < 0 || viewIndex >= getRowCount()) {
return -1;
}
return convertRowIndexToModel(viewIndex);
}
//
// Implementing TableModelListener interface
//
/** {@collect.stats}
* Invoked when this table's <code>TableModel</code> generates
* a <code>TableModelEvent</code>.
* The <code>TableModelEvent</code> should be constructed in the
* coordinate system of the model; the appropriate mapping to the
* view coordinate system is performed by this <code>JTable</code>
* when it receives the event.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
* <p>
* Note that as of 1.3, this method clears the selection, if any.
*/
public void tableChanged(TableModelEvent e) {
if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
// The whole thing changed
clearSelectionAndLeadAnchor();
rowModel = null;
if (sortManager != null) {
try {
ignoreSortChange = true;
sortManager.sorter.modelStructureChanged();
} finally {
ignoreSortChange = false;
}
sortManager.allChanged();
}
if (getAutoCreateColumnsFromModel()) {
// This will effect invalidation of the JTable and JTableHeader.
createDefaultColumnsFromModel();
return;
}
resizeAndRepaint();
return;
}
if (sortManager != null) {
sortedTableChanged(null, e);
return;
}
// The totalRowHeight calculated below will be incorrect if
// there are variable height rows. Repaint the visible region,
// but don't return as a revalidate may be necessary as well.
if (rowModel != null) {
repaint();
}
if (e.getType() == TableModelEvent.INSERT) {
tableRowsInserted(e);
return;
}
if (e.getType() == TableModelEvent.DELETE) {
tableRowsDeleted(e);
return;
}
int modelColumn = e.getColumn();
int start = e.getFirstRow();
int end = e.getLastRow();
Rectangle dirtyRegion;
if (modelColumn == TableModelEvent.ALL_COLUMNS) {
// 1 or more rows changed
dirtyRegion = new Rectangle(0, start * getRowHeight(),
getColumnModel().getTotalColumnWidth(), 0);
}
else {
// A cell or column of cells has changed.
// Unlike the rest of the methods in the JTable, the TableModelEvent
// uses the coordinate system of the model instead of the view.
// This is the only place in the JTable where this "reverse mapping"
// is used.
int column = convertColumnIndexToView(modelColumn);
dirtyRegion = getCellRect(start, column, false);
}
// Now adjust the height of the dirty region according to the value of "end".
// Check for Integer.MAX_VALUE as this will cause an overflow.
if (end != Integer.MAX_VALUE) {
dirtyRegion.height = (end-start+1)*getRowHeight();
repaint(dirtyRegion.x, dirtyRegion.y, dirtyRegion.width, dirtyRegion.height);
}
// In fact, if the end is Integer.MAX_VALUE we need to revalidate anyway
// because the scrollbar may need repainting.
else {
clearSelectionAndLeadAnchor();
resizeAndRepaint();
rowModel = null;
}
}
/*
* Invoked when rows have been inserted into the table.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the TableModelEvent encapsulating the insertion
*/
private void tableRowsInserted(TableModelEvent e) {
int start = e.getFirstRow();
int end = e.getLastRow();
if (start < 0) {
start = 0;
}
if (end < 0) {
end = getRowCount()-1;
}
// Adjust the selection to account for the new rows.
int length = end - start + 1;
selectionModel.insertIndexInterval(start, length, true);
// If we have variable height rows, adjust the row model.
if (rowModel != null) {
rowModel.insertEntries(start, length, getRowHeight());
}
int rh = getRowHeight() ;
Rectangle drawRect = new Rectangle(0, start * rh,
getColumnModel().getTotalColumnWidth(),
(getRowCount()-start) * rh);
revalidate();
// PENDING(milne) revalidate calls repaint() if parent is a ScrollPane
// repaint still required in the unusual case where there is no ScrollPane
repaint(drawRect);
}
/*
* Invoked when rows have been removed from the table.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the TableModelEvent encapsulating the deletion
*/
private void tableRowsDeleted(TableModelEvent e) {
int start = e.getFirstRow();
int end = e.getLastRow();
if (start < 0) {
start = 0;
}
if (end < 0) {
end = getRowCount()-1;
}
int deletedCount = end - start + 1;
int previousRowCount = getRowCount() + deletedCount;
// Adjust the selection to account for the new rows
selectionModel.removeIndexInterval(start, end);
// If we have variable height rows, adjust the row model.
if (rowModel != null) {
rowModel.removeEntries(start, deletedCount);
}
int rh = getRowHeight();
Rectangle drawRect = new Rectangle(0, start * rh,
getColumnModel().getTotalColumnWidth(),
(previousRowCount - start) * rh);
revalidate();
// PENDING(milne) revalidate calls repaint() if parent is a ScrollPane
// repaint still required in the unusual case where there is no ScrollPane
repaint(drawRect);
}
//
// Implementing TableColumnModelListener interface
//
/** {@collect.stats}
* Invoked when a column is added to the table column model.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @see TableColumnModelListener
*/
public void columnAdded(TableColumnModelEvent e) {
// If I'm currently editing, then I should stop editing
if (isEditing()) {
removeEditor();
}
resizeAndRepaint();
}
/** {@collect.stats}
* Invoked when a column is removed from the table column model.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @see TableColumnModelListener
*/
public void columnRemoved(TableColumnModelEvent e) {
// If I'm currently editing, then I should stop editing
if (isEditing()) {
removeEditor();
}
resizeAndRepaint();
}
/** {@collect.stats}
* Invoked when a column is repositioned. If a cell is being
* edited, then editing is stopped and the cell is redrawn.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnMoved(TableColumnModelEvent e) {
// If I'm currently editing, then I should stop editing
if (isEditing()) {
removeEditor();
}
repaint();
}
/** {@collect.stats}
* Invoked when a column is moved due to a margin change.
* If a cell is being edited, then editing is stopped and the cell
* is redrawn.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnMarginChanged(ChangeEvent e) {
if (isEditing()) {
removeEditor();
}
TableColumn resizingColumn = getResizingColumn();
// Need to do this here, before the parent's
// layout manager calls getPreferredSize().
if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF) {
resizingColumn.setPreferredWidth(resizingColumn.getWidth());
}
resizeAndRepaint();
}
private int limit(int i, int a, int b) {
return Math.min(b, Math.max(i, a));
}
/** {@collect.stats}
* Invoked when the selection model of the <code>TableColumnModel</code>
* is changed.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnSelectionChanged(ListSelectionEvent e) {
boolean isAdjusting = e.getValueIsAdjusting();
if (columnSelectionAdjusting && !isAdjusting) {
// The assumption is that when the model is no longer adjusting
// we will have already gotten all the changes, and therefore
// don't need to do an additional paint.
columnSelectionAdjusting = false;
return;
}
columnSelectionAdjusting = isAdjusting;
// The getCellRect() call will fail unless there is at least one row.
if (getRowCount() <= 0 || getColumnCount() <= 0) {
return;
}
int firstIndex = limit(e.getFirstIndex(), 0, getColumnCount()-1);
int lastIndex = limit(e.getLastIndex(), 0, getColumnCount()-1);
int minRow = 0;
int maxRow = getRowCount() - 1;
if (getRowSelectionAllowed()) {
minRow = selectionModel.getMinSelectionIndex();
maxRow = selectionModel.getMaxSelectionIndex();
int leadRow = getAdjustedIndex(selectionModel.getLeadSelectionIndex(), true);
if (minRow == -1 || maxRow == -1) {
if (leadRow == -1) {
// nothing to repaint, return
return;
}
// only thing to repaint is the lead
minRow = maxRow = leadRow;
} else {
// We need to consider more than just the range between
// the min and max selected index. The lead row, which could
// be outside this range, should be considered also.
if (leadRow != -1) {
minRow = Math.min(minRow, leadRow);
maxRow = Math.max(maxRow, leadRow);
}
}
}
Rectangle firstColumnRect = getCellRect(minRow, firstIndex, false);
Rectangle lastColumnRect = getCellRect(maxRow, lastIndex, false);
Rectangle dirtyRegion = firstColumnRect.union(lastColumnRect);
repaint(dirtyRegion);
}
//
// Implementing ListSelectionListener interface
//
/** {@collect.stats}
* Invoked when the row selection changes -- repaints to show the new
* selection.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see ListSelectionListener
*/
public void valueChanged(ListSelectionEvent e) {
if (sortManager != null) {
sortManager.viewSelectionChanged(e);
}
boolean isAdjusting = e.getValueIsAdjusting();
if (rowSelectionAdjusting && !isAdjusting) {
// The assumption is that when the model is no longer adjusting
// we will have already gotten all the changes, and therefore
// don't need to do an additional paint.
rowSelectionAdjusting = false;
return;
}
rowSelectionAdjusting = isAdjusting;
// The getCellRect() calls will fail unless there is at least one column.
if (getRowCount() <= 0 || getColumnCount() <= 0) {
return;
}
int firstIndex = limit(e.getFirstIndex(), 0, getRowCount()-1);
int lastIndex = limit(e.getLastIndex(), 0, getRowCount()-1);
Rectangle firstRowRect = getCellRect(firstIndex, 0, false);
Rectangle lastRowRect = getCellRect(lastIndex, getColumnCount()-1, false);
Rectangle dirtyRegion = firstRowRect.union(lastRowRect);
repaint(dirtyRegion);
}
//
// Implementing the CellEditorListener interface
//
/** {@collect.stats}
* Invoked when editing is finished. The changes are saved and the
* editor is discarded.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see CellEditorListener
*/
public void editingStopped(ChangeEvent e) {
// Take in the new value
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
setValueAt(value, editingRow, editingColumn);
removeEditor();
}
}
/** {@collect.stats}
* Invoked when editing is canceled. The editor object is discarded
* and the cell is rendered once again.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by JTable.
*
* @param e the event received
* @see CellEditorListener
*/
public void editingCanceled(ChangeEvent e) {
removeEditor();
}
//
// Implementing the Scrollable interface
//
/** {@collect.stats}
* Sets the preferred size of the viewport for this table.
*
* @param size a <code>Dimension</code> object specifying the <code>preferredSize</code> of a
* <code>JViewport</code> whose view is this table
* @see Scrollable#getPreferredScrollableViewportSize
* @beaninfo
* description: The preferred size of the viewport.
*/
public void setPreferredScrollableViewportSize(Dimension size) {
preferredViewportSize = size;
}
/** {@collect.stats}
* Returns the preferred size of the viewport for this table.
*
* @return a <code>Dimension</code> object containing the <code>preferredSize</code> of the <code>JViewport</code>
* which displays this table
* @see Scrollable#getPreferredScrollableViewportSize
*/
public Dimension getPreferredScrollableViewportSize() {
return preferredViewportSize;
}
/** {@collect.stats}
* Returns the scroll increment (in pixels) that completely exposes one new
* row or column (depending on the orientation).
* <p>
* This method is called each time the user requests a unit scroll.
*
* @param visibleRect the view area visible within the viewport
* @param orientation either <code>SwingConstants.VERTICAL</code>
* or <code>SwingConstants.HORIZONTAL</code>
* @param direction less than zero to scroll up/left,
* greater than zero for down/right
* @return the "unit" increment for scrolling in the specified direction
* @see Scrollable#getScrollableUnitIncrement
*/
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction) {
int leadingRow;
int leadingCol;
Rectangle leadingCellRect;
int leadingVisibleEdge;
int leadingCellEdge;
int leadingCellSize;
leadingRow = getLeadingRow(visibleRect);
leadingCol = getLeadingCol(visibleRect);
if (orientation == SwingConstants.VERTICAL && leadingRow < 0) {
// Couldn't find leading row - return some default value
return getRowHeight();
}
else if (orientation == SwingConstants.HORIZONTAL && leadingCol < 0) {
// Couldn't find leading col - return some default value
return 100;
}
// Note that it's possible for one of leadingCol or leadingRow to be
// -1, depending on the orientation. This is okay, as getCellRect()
// still provides enough information to calculate the unit increment.
leadingCellRect = getCellRect(leadingRow, leadingCol, true);
leadingVisibleEdge = leadingEdge(visibleRect, orientation);
leadingCellEdge = leadingEdge(leadingCellRect, orientation);
if (orientation == SwingConstants.VERTICAL) {
leadingCellSize = leadingCellRect.height;
}
else {
leadingCellSize = leadingCellRect.width;
}
// 4 cases:
// #1: Leading cell fully visible, reveal next cell
// #2: Leading cell fully visible, hide leading cell
// #3: Leading cell partially visible, hide rest of leading cell
// #4: Leading cell partially visible, reveal rest of leading cell
if (leadingVisibleEdge == leadingCellEdge) { // Leading cell is fully
// visible
// Case #1: Reveal previous cell
if (direction < 0) {
int retVal = 0;
if (orientation == SwingConstants.VERTICAL) {
// Loop past any zero-height rows
while (--leadingRow >= 0) {
retVal = getRowHeight(leadingRow);
if (retVal != 0) {
break;
}
}
}
else { // HORIZONTAL
// Loop past any zero-width cols
while (--leadingCol >= 0) {
retVal = getCellRect(leadingRow, leadingCol, true).width;
if (retVal != 0) {
break;
}
}
}
return retVal;
}
else { // Case #2: hide leading cell
return leadingCellSize;
}
}
else { // Leading cell is partially hidden
// Compute visible, hidden portions
int hiddenAmt = Math.abs(leadingVisibleEdge - leadingCellEdge);
int visibleAmt = leadingCellSize - hiddenAmt;
if (direction > 0) {
// Case #3: hide showing portion of leading cell
return visibleAmt;
}
else { // Case #4: reveal hidden portion of leading cell
return hiddenAmt;
}
}
}
/** {@collect.stats}
* Returns <code>visibleRect.height</code> or
* <code>visibleRect.width</code>,
* depending on this table's orientation. Note that as of Swing 1.1.1
* (Java 2 v 1.2.2) the value
* returned will ensure that the viewport is cleanly aligned on
* a row boundary.
*
* @return <code>visibleRect.height</code> or
* <code>visibleRect.width</code>
* per the orientation
* @see Scrollable#getScrollableBlockIncrement
*/
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) {
if (getRowCount() == 0) {
// Short-circuit empty table model
if (SwingConstants.VERTICAL == orientation) {
int rh = getRowHeight();
return (rh > 0) ? Math.max(rh, (visibleRect.height / rh) * rh) :
visibleRect.height;
}
else {
return visibleRect.width;
}
}
// Shortcut for vertical scrolling of a table w/ uniform row height
if (null == rowModel && SwingConstants.VERTICAL == orientation) {
int row = rowAtPoint(visibleRect.getLocation());
assert row != -1;
int col = columnAtPoint(visibleRect.getLocation());
Rectangle cellRect = getCellRect(row, col, true);
if (cellRect.y == visibleRect.y) {
int rh = getRowHeight();
assert rh > 0;
return Math.max(rh, (visibleRect.height / rh) * rh);
}
}
if (direction < 0) {
return getPreviousBlockIncrement(visibleRect, orientation);
}
else {
return getNextBlockIncrement(visibleRect, orientation);
}
}
/** {@collect.stats}
* Called to get the block increment for upward scrolling in cases of
* horizontal scrolling, or for vertical scrolling of a table with
* variable row heights.
*/
private int getPreviousBlockIncrement(Rectangle visibleRect,
int orientation) {
// Measure back from visible leading edge
// If we hit the cell on its leading edge, it becomes the leading cell.
// Else, use following cell
int row;
int col;
int newEdge;
Point newCellLoc;
int visibleLeadingEdge = leadingEdge(visibleRect, orientation);
boolean leftToRight = getComponentOrientation().isLeftToRight();
int newLeadingEdge;
// Roughly determine the new leading edge by measuring back from the
// leading visible edge by the size of the visible rect, and find the
// cell there.
if (orientation == SwingConstants.VERTICAL) {
newEdge = visibleLeadingEdge - visibleRect.height;
int x = visibleRect.x + (leftToRight ? 0 : visibleRect.width);
newCellLoc = new Point(x, newEdge);
}
else if (leftToRight) {
newEdge = visibleLeadingEdge - visibleRect.width;
newCellLoc = new Point(newEdge, visibleRect.y);
}
else { // Horizontal, right-to-left
newEdge = visibleLeadingEdge + visibleRect.width;
newCellLoc = new Point(newEdge - 1, visibleRect.y);
}
row = rowAtPoint(newCellLoc);
col = columnAtPoint(newCellLoc);
// If we're measuring past the beginning of the table, we get an invalid
// cell. Just go to the beginning of the table in this case.
if (orientation == SwingConstants.VERTICAL & row < 0) {
newLeadingEdge = 0;
}
else if (orientation == SwingConstants.HORIZONTAL & col < 0) {
if (leftToRight) {
newLeadingEdge = 0;
}
else {
newLeadingEdge = getWidth();
}
}
else {
// Refine our measurement
Rectangle newCellRect = getCellRect(row, col, true);
int newCellLeadingEdge = leadingEdge(newCellRect, orientation);
int newCellTrailingEdge = trailingEdge(newCellRect, orientation);
// Usually, we hit in the middle of newCell, and want to scroll to
// the beginning of the cell after newCell. But there are a
// couple corner cases where we want to scroll to the beginning of
// newCell itself. These cases are:
// 1) newCell is so large that it ends at or extends into the
// visibleRect (newCell is the leading cell, or is adjacent to
// the leading cell)
// 2) newEdge happens to fall right on the beginning of a cell
// Case 1
if ((orientation == SwingConstants.VERTICAL || leftToRight) &&
(newCellTrailingEdge >= visibleLeadingEdge)) {
newLeadingEdge = newCellLeadingEdge;
}
else if (orientation == SwingConstants.HORIZONTAL &&
!leftToRight &&
newCellTrailingEdge <= visibleLeadingEdge) {
newLeadingEdge = newCellLeadingEdge;
}
// Case 2:
else if (newEdge == newCellLeadingEdge) {
newLeadingEdge = newCellLeadingEdge;
}
// Common case: scroll to cell after newCell
else {
newLeadingEdge = newCellTrailingEdge;
}
}
return Math.abs(visibleLeadingEdge - newLeadingEdge);
}
/** {@collect.stats}
* Called to get the block increment for downward scrolling in cases of
* horizontal scrolling, or for vertical scrolling of a table with
* variable row heights.
*/
private int getNextBlockIncrement(Rectangle visibleRect,
int orientation) {
// Find the cell at the trailing edge. Return the distance to put
// that cell at the leading edge.
int trailingRow = getTrailingRow(visibleRect);
int trailingCol = getTrailingCol(visibleRect);
Rectangle cellRect;
boolean cellFillsVis;
int cellLeadingEdge;
int cellTrailingEdge;
int newLeadingEdge;
int visibleLeadingEdge = leadingEdge(visibleRect, orientation);
// If we couldn't find trailing cell, just return the size of the
// visibleRect. Note that, for instance, we don't need the
// trailingCol to proceed if we're scrolling vertically, because
// cellRect will still fill in the required dimensions. This would
// happen if we're scrolling vertically, and the table is not wide
// enough to fill the visibleRect.
if (orientation == SwingConstants.VERTICAL && trailingRow < 0) {
return visibleRect.height;
}
else if (orientation == SwingConstants.HORIZONTAL && trailingCol < 0) {
return visibleRect.width;
}
cellRect = getCellRect(trailingRow, trailingCol, true);
cellLeadingEdge = leadingEdge(cellRect, orientation);
cellTrailingEdge = trailingEdge(cellRect, orientation);
if (orientation == SwingConstants.VERTICAL ||
getComponentOrientation().isLeftToRight()) {
cellFillsVis = cellLeadingEdge <= visibleLeadingEdge;
}
else { // Horizontal, right-to-left
cellFillsVis = cellLeadingEdge >= visibleLeadingEdge;
}
if (cellFillsVis) {
// The visibleRect contains a single large cell. Scroll to the end
// of this cell, so the following cell is the first cell.
newLeadingEdge = cellTrailingEdge;
}
else if (cellTrailingEdge == trailingEdge(visibleRect, orientation)) {
// The trailing cell happens to end right at the end of the
// visibleRect. Again, scroll to the beginning of the next cell.
newLeadingEdge = cellTrailingEdge;
}
else {
// Common case: the trailing cell is partially visible, and isn't
// big enough to take up the entire visibleRect. Scroll so it
// becomes the leading cell.
newLeadingEdge = cellLeadingEdge;
}
return Math.abs(newLeadingEdge - visibleLeadingEdge);
}
/*
* Return the row at the top of the visibleRect
*
* May return -1
*/
private int getLeadingRow(Rectangle visibleRect) {
Point leadingPoint;
if (getComponentOrientation().isLeftToRight()) {
leadingPoint = new Point(visibleRect.x, visibleRect.y);
}
else {
leadingPoint = new Point(visibleRect.x + visibleRect.width - 1,
visibleRect.y);
}
return rowAtPoint(leadingPoint);
}
/*
* Return the column at the leading edge of the visibleRect.
*
* May return -1
*/
private int getLeadingCol(Rectangle visibleRect) {
Point leadingPoint;
if (getComponentOrientation().isLeftToRight()) {
leadingPoint = new Point(visibleRect.x, visibleRect.y);
}
else {
leadingPoint = new Point(visibleRect.x + visibleRect.width - 1,
visibleRect.y);
}
return columnAtPoint(leadingPoint);
}
/*
* Return the row at the bottom of the visibleRect.
*
* May return -1
*/
private int getTrailingRow(Rectangle visibleRect) {
Point trailingPoint;
if (getComponentOrientation().isLeftToRight()) {
trailingPoint = new Point(visibleRect.x,
visibleRect.y + visibleRect.height - 1);
}
else {
trailingPoint = new Point(visibleRect.x + visibleRect.width - 1,
visibleRect.y + visibleRect.height - 1);
}
return rowAtPoint(trailingPoint);
}
/*
* Return the column at the trailing edge of the visibleRect.
*
* May return -1
*/
private int getTrailingCol(Rectangle visibleRect) {
Point trailingPoint;
if (getComponentOrientation().isLeftToRight()) {
trailingPoint = new Point(visibleRect.x + visibleRect.width - 1,
visibleRect.y);
}
else {
trailingPoint = new Point(visibleRect.x, visibleRect.y);
}
return columnAtPoint(trailingPoint);
}
/*
* Returns the leading edge ("beginning") of the given Rectangle.
* For VERTICAL, this is the top, for left-to-right, the left side, and for
* right-to-left, the right side.
*/
private int leadingEdge(Rectangle rect, int orientation) {
if (orientation == SwingConstants.VERTICAL) {
return rect.y;
}
else if (getComponentOrientation().isLeftToRight()) {
return rect.x;
}
else { // Horizontal, right-to-left
return rect.x + rect.width;
}
}
/*
* Returns the trailing edge ("end") of the given Rectangle.
* For VERTICAL, this is the bottom, for left-to-right, the right side, and
* for right-to-left, the left side.
*/
private int trailingEdge(Rectangle rect, int orientation) {
if (orientation == SwingConstants.VERTICAL) {
return rect.y + rect.height;
}
else if (getComponentOrientation().isLeftToRight()) {
return rect.x + rect.width;
}
else { // Horizontal, right-to-left
return rect.x;
}
}
/** {@collect.stats}
* Returns false if <code>autoResizeMode</code> is set to
* <code>AUTO_RESIZE_OFF</code>, which indicates that the
* width of the viewport does not determine the width
* of the table. Otherwise returns true.
*
* @return false if <code>autoResizeMode</code> is set
* to <code>AUTO_RESIZE_OFF</code>, otherwise returns true
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
return !(autoResizeMode == AUTO_RESIZE_OFF);
}
/** {@collect.stats}
* Returns {@code false} to indicate that the height of the viewport does
* not determine the height of the table, unless
* {@code getFillsViewportHeight} is {@code true} and the preferred height
* of the table is smaller than the viewport's height.
*
* @return {@code false} unless {@code getFillsViewportHeight} is
* {@code true} and the table needs to be stretched to fill
* the viewport
* @see Scrollable#getScrollableTracksViewportHeight
* @see #setFillsViewportHeight
* @see #getFillsViewportHeight
*/
public boolean getScrollableTracksViewportHeight() {
return getFillsViewportHeight()
&& getParent() instanceof JViewport
&& (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
/** {@collect.stats}
* Sets whether or not this table is always made large enough
* to fill the height of an enclosing viewport. If the preferred
* height of the table is smaller than the viewport, then the table
* will be stretched to fill the viewport. In other words, this
* ensures the table is never smaller than the viewport.
* The default for this property is {@code false}.
*
* @param fillsViewportHeight whether or not this table is always
* made large enough to fill the height of an enclosing
* viewport
* @see #getFillsViewportHeight
* @see #getScrollableTracksViewportHeight
* @since 1.6
* @beaninfo
* bound: true
* description: Whether or not this table is always made large enough
* to fill the height of an enclosing viewport
*/
public void setFillsViewportHeight(boolean fillsViewportHeight) {
boolean old = this.fillsViewportHeight;
this.fillsViewportHeight = fillsViewportHeight;
resizeAndRepaint();
firePropertyChange("fillsViewportHeight", old, fillsViewportHeight);
}
/** {@collect.stats}
* Returns whether or not this table is always made large enough
* to fill the height of an enclosing viewport.
*
* @return whether or not this table is always made large enough
* to fill the height of an enclosing viewport
* @see #setFillsViewportHeight
* @since 1.6
*/
public boolean getFillsViewportHeight() {
return fillsViewportHeight;
}
//
// Protected Methods
//
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
// Start editing when a key is typed. UI classes can disable this behavior
// by setting the client property JTable.autoStartsEdit to Boolean.FALSE.
if (!retValue && condition == WHEN_ANCESTOR_OF_FOCUSED_COMPONENT &&
isFocusOwner() &&
!Boolean.FALSE.equals((Boolean)getClientProperty("JTable.autoStartsEdit"))) {
// We do not have a binding for the event.
Component editorComponent = getEditorComponent();
if (editorComponent == null) {
// Only attempt to install the editor on a KEY_PRESSED,
if (e == null || e.getID() != KeyEvent.KEY_PRESSED) {
return false;
}
// Don't start when just a modifier is pressed
int code = e.getKeyCode();
if (code == KeyEvent.VK_SHIFT || code == KeyEvent.VK_CONTROL ||
code == KeyEvent.VK_ALT) {
return false;
}
// Try to install the editor
int leadRow = getSelectionModel().getLeadSelectionIndex();
int leadColumn = getColumnModel().getSelectionModel().
getLeadSelectionIndex();
if (leadRow != -1 && leadColumn != -1 && !isEditing()) {
if (!editCellAt(leadRow, leadColumn, e)) {
return false;
}
}
editorComponent = getEditorComponent();
if (editorComponent == null) {
return false;
}
}
// If the editorComponent is a JComponent, pass the event to it.
if (editorComponent instanceof JComponent) {
retValue = ((JComponent)editorComponent).processKeyBinding
(ks, e, WHEN_FOCUSED, pressed);
// If we have started an editor as a result of the user
// pressing a key and the surrendersFocusOnKeystroke property
// is true, give the focus to the new editor.
if (getSurrendersFocusOnKeystroke()) {
editorComponent.requestFocus();
}
}
}
return retValue;
}
private void setLazyValue(Hashtable h, Class c, String s) {
h.put(c, new SwingLazyValue(s));
}
private void setLazyRenderer(Class c, String s) {
setLazyValue(defaultRenderersByColumnClass, c, s);
}
/** {@collect.stats}
* Creates default cell renderers for objects, numbers, doubles, dates,
* booleans, and icons.
* @see javax.swing.table.DefaultTableCellRenderer
*
*/
protected void createDefaultRenderers() {
defaultRenderersByColumnClass = new UIDefaults(8, 0.75f);
// Objects
setLazyRenderer(Object.class, "javax.swing.table.DefaultTableCellRenderer$UIResource");
// Numbers
setLazyRenderer(Number.class, "javax.swing.JTable$NumberRenderer");
// Doubles and Floats
setLazyRenderer(Float.class, "javax.swing.JTable$DoubleRenderer");
setLazyRenderer(Double.class, "javax.swing.JTable$DoubleRenderer");
// Dates
setLazyRenderer(Date.class, "javax.swing.JTable$DateRenderer");
// Icons and ImageIcons
setLazyRenderer(Icon.class, "javax.swing.JTable$IconRenderer");
setLazyRenderer(ImageIcon.class, "javax.swing.JTable$IconRenderer");
// Booleans
setLazyRenderer(Boolean.class, "javax.swing.JTable$BooleanRenderer");
}
/** {@collect.stats}
* Default Renderers
**/
static class NumberRenderer extends DefaultTableCellRenderer.UIResource {
public NumberRenderer() {
super();
setHorizontalAlignment(JLabel.RIGHT);
}
}
static class DoubleRenderer extends NumberRenderer {
NumberFormat formatter;
public DoubleRenderer() { super(); }
public void setValue(Object value) {
if (formatter == null) {
formatter = NumberFormat.getInstance();
}
setText((value == null) ? "" : formatter.format(value));
}
}
static class DateRenderer extends DefaultTableCellRenderer.UIResource {
DateFormat formatter;
public DateRenderer() { super(); }
public void setValue(Object value) {
if (formatter==null) {
formatter = DateFormat.getDateInstance();
}
setText((value == null) ? "" : formatter.format(value));
}
}
static class IconRenderer extends DefaultTableCellRenderer.UIResource {
public IconRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
}
public void setValue(Object value) { setIcon((value instanceof Icon) ? (Icon)value : null); }
}
static class BooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource
{
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public BooleanRenderer() {
super();
setHorizontalAlignment(JLabel.CENTER);
setBorderPainted(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected((value != null && ((Boolean)value).booleanValue()));
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
} else {
setBorder(noFocusBorder);
}
return this;
}
}
private void setLazyEditor(Class c, String s) {
setLazyValue(defaultEditorsByColumnClass, c, s);
}
/** {@collect.stats}
* Creates default cell editors for objects, numbers, and boolean values.
* @see DefaultCellEditor
*/
protected void createDefaultEditors() {
defaultEditorsByColumnClass = new UIDefaults(3, 0.75f);
// Objects
setLazyEditor(Object.class, "javax.swing.JTable$GenericEditor");
// Numbers
setLazyEditor(Number.class, "javax.swing.JTable$NumberEditor");
// Booleans
setLazyEditor(Boolean.class, "javax.swing.JTable$BooleanEditor");
}
/** {@collect.stats}
* Default Editors
*/
static class GenericEditor extends DefaultCellEditor {
Class[] argTypes = new Class[]{String.class};
java.lang.reflect.Constructor constructor;
Object value;
public GenericEditor() {
super(new JTextField());
getComponent().setName("Table.editor");
}
public boolean stopCellEditing() {
String s = (String)super.getCellEditorValue();
// Here we are dealing with the case where a user
// has deleted the string value in a cell, possibly
// after a failed validation. Return null, so that
// they have the option to replace the value with
// null or use escape to restore the original.
// For Strings, return "" for backward compatibility.
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
super.stopCellEditing();
}
try {
value = constructor.newInstance(new Object[]{s});
}
catch (Exception e) {
((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
return super.stopCellEditing();
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column) {
this.value = null;
((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
try {
Class type = table.getColumnClass(column);
// Since our obligation is to produce a value which is
// assignable for the required type it is OK to use the
// String constructor for columns which are declared
// to contain Objects. A String is an Object.
if (type == Object.class) {
type = String.class;
}
constructor = type.getConstructor(argTypes);
}
catch (Exception e) {
return null;
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
public Object getCellEditorValue() {
return value;
}
}
static class NumberEditor extends GenericEditor {
public NumberEditor() {
((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT);
}
}
static class BooleanEditor extends DefaultCellEditor {
public BooleanEditor() {
super(new JCheckBox());
JCheckBox checkBox = (JCheckBox)getComponent();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
}
/** {@collect.stats}
* Initializes table properties to their default values.
*/
protected void initializeLocalVars() {
updateSelectionOnSort = true;
setOpaque(true);
createDefaultRenderers();
createDefaultEditors();
setTableHeader(createDefaultTableHeader());
setShowGrid(true);
setAutoResizeMode(AUTO_RESIZE_SUBSEQUENT_COLUMNS);
setRowHeight(16);
isRowHeightSet = false;
setRowMargin(1);
setRowSelectionAllowed(true);
setCellEditor(null);
setEditingColumn(-1);
setEditingRow(-1);
setSurrendersFocusOnKeystroke(false);
setPreferredScrollableViewportSize(new Dimension(450, 400));
// I'm registered to do tool tips so we can draw tips for the renderers
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(this);
setAutoscrolls(true);
}
/** {@collect.stats}
* Returns the default table model object, which is
* a <code>DefaultTableModel</code>. A subclass can override this
* method to return a different table model object.
*
* @return the default table model object
* @see javax.swing.table.DefaultTableModel
*/
protected TableModel createDefaultDataModel() {
return new DefaultTableModel();
}
/** {@collect.stats}
* Returns the default column model object, which is
* a <code>DefaultTableColumnModel</code>. A subclass can override this
* method to return a different column model object.
*
* @return the default column model object
* @see javax.swing.table.DefaultTableColumnModel
*/
protected TableColumnModel createDefaultColumnModel() {
return new DefaultTableColumnModel();
}
/** {@collect.stats}
* Returns the default selection model object, which is
* a <code>DefaultListSelectionModel</code>. A subclass can override this
* method to return a different selection model object.
*
* @return the default selection model object
* @see javax.swing.DefaultListSelectionModel
*/
protected ListSelectionModel createDefaultSelectionModel() {
return new DefaultListSelectionModel();
}
/** {@collect.stats}
* Returns the default table header object, which is
* a <code>JTableHeader</code>. A subclass can override this
* method to return a different table header object.
*
* @return the default table header object
* @see javax.swing.table.JTableHeader
*/
protected JTableHeader createDefaultTableHeader() {
return new JTableHeader(columnModel);
}
/** {@collect.stats}
* Equivalent to <code>revalidate</code> followed by <code>repaint</code>.
*/
protected void resizeAndRepaint() {
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the active cell editor, which is {@code null} if the table
* is not currently editing.
*
* @return the {@code TableCellEditor} that does the editing,
* or {@code null} if the table is not currently editing.
* @see #cellEditor
* @see #getCellEditor(int, int)
*/
public TableCellEditor getCellEditor() {
return cellEditor;
}
/** {@collect.stats}
* Sets the active cell editor.
*
* @param anEditor the active cell editor
* @see #cellEditor
* @beaninfo
* bound: true
* description: The table's active cell editor.
*/
public void setCellEditor(TableCellEditor anEditor) {
TableCellEditor oldEditor = cellEditor;
cellEditor = anEditor;
firePropertyChange("tableCellEditor", oldEditor, anEditor);
}
/** {@collect.stats}
* Sets the <code>editingColumn</code> variable.
* @param aColumn the column of the cell to be edited
*
* @see #editingColumn
*/
public void setEditingColumn(int aColumn) {
editingColumn = aColumn;
}
/** {@collect.stats}
* Sets the <code>editingRow</code> variable.
* @param aRow the row of the cell to be edited
*
* @see #editingRow
*/
public void setEditingRow(int aRow) {
editingRow = aRow;
}
/** {@collect.stats}
* Returns an appropriate renderer for the cell specified by this row and
* column. If the <code>TableColumn</code> for this column has a non-null
* renderer, returns that. If not, finds the class of the data in
* this column (using <code>getColumnClass</code>)
* and returns the default renderer for this type of data.
* <p>
* <b>Note:</b>
* Throughout the table package, the internal implementations always
* use this method to provide renderers so that this default behavior
* can be safely overridden by a subclass.
*
* @param row the row of the cell to render, where 0 is the first row
* @param column the column of the cell to render,
* where 0 is the first column
* @return the assigned renderer; if <code>null</code>
* returns the default renderer
* for this type of object
* @see javax.swing.table.DefaultTableCellRenderer
* @see javax.swing.table.TableColumn#setCellRenderer
* @see #setDefaultRenderer
*/
public TableCellRenderer getCellRenderer(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = tableColumn.getCellRenderer();
if (renderer == null) {
renderer = getDefaultRenderer(getColumnClass(column));
}
return renderer;
}
/** {@collect.stats}
* Prepares the renderer by querying the data model for the
* value and selection state
* of the cell at <code>row</code>, <code>column</code>.
* Returns the component (may be a <code>Component</code>
* or a <code>JComponent</code>) under the event location.
* <p>
* During a printing operation, this method will configure the
* renderer without indicating selection or focus, to prevent
* them from appearing in the printed output. To do other
* customizations based on whether or not the table is being
* printed, you can check the value of
* {@link javax.swing.JComponent#isPaintingForPrint()}, either here
* or within custom renderers.
* <p>
* <b>Note:</b>
* Throughout the table package, the internal implementations always
* use this method to prepare renderers so that this default behavior
* can be safely overridden by a subclass.
*
* @param renderer the <code>TableCellRenderer</code> to prepare
* @param row the row of the cell to render, where 0 is the first row
* @param column the column of the cell to render,
* where 0 is the first column
* @return the <code>Component</code> under the event location
*/
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Object value = getValueAt(row, column);
boolean isSelected = false;
boolean hasFocus = false;
// Only indicate the selection and focused cell if not printing
if (!isPaintingForPrint()) {
isSelected = isCellSelected(row, column);
boolean rowIsLead =
(selectionModel.getLeadSelectionIndex() == row);
boolean colIsLead =
(columnModel.getSelectionModel().getLeadSelectionIndex() == column);
hasFocus = (rowIsLead && colIsLead) && isFocusOwner();
}
return renderer.getTableCellRendererComponent(this, value,
isSelected, hasFocus,
row, column);
}
/** {@collect.stats}
* Returns an appropriate editor for the cell specified by
* <code>row</code> and <code>column</code>. If the
* <code>TableColumn</code> for this column has a non-null editor,
* returns that. If not, finds the class of the data in this
* column (using <code>getColumnClass</code>)
* and returns the default editor for this type of data.
* <p>
* <b>Note:</b>
* Throughout the table package, the internal implementations always
* use this method to provide editors so that this default behavior
* can be safely overridden by a subclass.
*
* @param row the row of the cell to edit, where 0 is the first row
* @param column the column of the cell to edit,
* where 0 is the first column
* @return the editor for this cell;
* if <code>null</code> return the default editor for
* this type of cell
* @see DefaultCellEditor
*/
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn(column);
TableCellEditor editor = tableColumn.getCellEditor();
if (editor == null) {
editor = getDefaultEditor(getColumnClass(column));
}
return editor;
}
/** {@collect.stats}
* Prepares the editor by querying the data model for the value and
* selection state of the cell at <code>row</code>, <code>column</code>.
* <p>
* <b>Note:</b>
* Throughout the table package, the internal implementations always
* use this method to prepare editors so that this default behavior
* can be safely overridden by a subclass.
*
* @param editor the <code>TableCellEditor</code> to set up
* @param row the row of the cell to edit,
* where 0 is the first row
* @param column the column of the cell to edit,
* where 0 is the first column
* @return the <code>Component</code> being edited
*/
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Object value = getValueAt(row, column);
boolean isSelected = isCellSelected(row, column);
Component comp = editor.getTableCellEditorComponent(this, value, isSelected,
row, column);
if (comp instanceof JComponent) {
JComponent jComp = (JComponent)comp;
if (jComp.getNextFocusableComponent() == null) {
jComp.setNextFocusableComponent(this);
}
}
return comp;
}
/** {@collect.stats}
* Discards the editor object and frees the real estate it used for
* cell rendering.
*/
public void removeEditor() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
removePropertyChangeListener("permanentFocusOwner", editorRemover);
editorRemover = null;
TableCellEditor editor = getCellEditor();
if(editor != null) {
editor.removeCellEditorListener(this);
if (editorComp != null) {
Component focusOwner =
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
boolean isFocusOwnerInTheTable = focusOwner != null?
SwingUtilities.isDescendingFrom(focusOwner, this):false;
remove(editorComp);
if(isFocusOwnerInTheTable) {
requestFocusInWindow();
}
}
Rectangle cellRect = getCellRect(editingRow, editingColumn, false);
setCellEditor(null);
setEditingColumn(-1);
setEditingRow(-1);
editorComp = null;
repaint(cellRect);
}
}
//
// Serialization
//
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
if ((ui != null) && (getUIClassID().equals(uiClassID))) {
ui.installUI(this);
}
createDefaultRenderers();
createDefaultEditors();
// If ToolTipText != null, then the tooltip has already been
// registered by JComponent.readObject() and we don't want
// to re-register here
if (getToolTipText() == null) {
ToolTipManager.sharedInstance().registerComponent(this);
}
}
/* Called from the JComponent's EnableSerializationFocusListener to
* do any Swing-specific pre-serialization configuration.
*/
void compWriteObjectNotify() {
super.compWriteObjectNotify();
// If ToolTipText != null, then the tooltip has already been
// unregistered by JComponent.compWriteObjectNotify()
if (getToolTipText() == null) {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
/** {@collect.stats}
* Returns a string representation of this table. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this table
*/
protected String paramString() {
String gridColorString = (gridColor != null ?
gridColor.toString() : "");
String showHorizontalLinesString = (showHorizontalLines ?
"true" : "false");
String showVerticalLinesString = (showVerticalLines ?
"true" : "false");
String autoResizeModeString;
if (autoResizeMode == AUTO_RESIZE_OFF) {
autoResizeModeString = "AUTO_RESIZE_OFF";
} else if (autoResizeMode == AUTO_RESIZE_NEXT_COLUMN) {
autoResizeModeString = "AUTO_RESIZE_NEXT_COLUMN";
} else if (autoResizeMode == AUTO_RESIZE_SUBSEQUENT_COLUMNS) {
autoResizeModeString = "AUTO_RESIZE_SUBSEQUENT_COLUMNS";
} else if (autoResizeMode == AUTO_RESIZE_LAST_COLUMN) {
autoResizeModeString = "AUTO_RESIZE_LAST_COLUMN";
} else if (autoResizeMode == AUTO_RESIZE_ALL_COLUMNS) {
autoResizeModeString = "AUTO_RESIZE_ALL_COLUMNS";
} else autoResizeModeString = "";
String autoCreateColumnsFromModelString = (autoCreateColumnsFromModel ?
"true" : "false");
String preferredViewportSizeString = (preferredViewportSize != null ?
preferredViewportSize.toString()
: "");
String rowSelectionAllowedString = (rowSelectionAllowed ?
"true" : "false");
String cellSelectionEnabledString = (cellSelectionEnabled ?
"true" : "false");
String selectionForegroundString = (selectionForeground != null ?
selectionForeground.toString() :
"");
String selectionBackgroundString = (selectionBackground != null ?
selectionBackground.toString() :
"");
return super.paramString() +
",autoCreateColumnsFromModel=" + autoCreateColumnsFromModelString +
",autoResizeMode=" + autoResizeModeString +
",cellSelectionEnabled=" + cellSelectionEnabledString +
",editingColumn=" + editingColumn +
",editingRow=" + editingRow +
",gridColor=" + gridColorString +
",preferredViewportSize=" + preferredViewportSizeString +
",rowHeight=" + rowHeight +
",rowMargin=" + rowMargin +
",rowSelectionAllowed=" + rowSelectionAllowedString +
",selectionBackground=" + selectionBackgroundString +
",selectionForeground=" + selectionForegroundString +
",showHorizontalLines=" + showHorizontalLinesString +
",showVerticalLines=" + showVerticalLinesString;
}
// This class tracks changes in the keyboard focus state. It is used
// when the JTable is editing to determine when to cancel the edit.
// If focus switches to a component outside of the jtable, but in the
// same window, this will cancel editing.
class CellEditorRemover implements PropertyChangeListener {
KeyboardFocusManager focusManager;
public CellEditorRemover(KeyboardFocusManager fm) {
this.focusManager = fm;
}
public void propertyChange(PropertyChangeEvent ev) {
if (!isEditing() || getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) {
return;
}
Component c = focusManager.getPermanentFocusOwner();
while (c != null) {
if (c == JTable.this) {
// focus remains inside the table
return;
} else if ((c instanceof Window) ||
(c instanceof Applet && c.getParent() == null)) {
if (c == SwingUtilities.getRoot(JTable.this)) {
if (!getCellEditor().stopCellEditing()) {
getCellEditor().cancelCellEditing();
}
}
break;
}
c = c.getParent();
}
}
}
/////////////////
// Printing Support
/////////////////
/** {@collect.stats}
* A convenience method that displays a printing dialog, and then prints
* this <code>JTable</code> in mode <code>PrintMode.FIT_WIDTH</code>,
* with no header or footer text. A modal progress dialog, with an abort
* option, will be shown for the duration of printing.
* <p>
* Note: In headless mode, no dialogs are shown and printing
* occurs on the default printer.
*
* @return true, unless printing is cancelled by the user
* @throws SecurityException if this thread is not allowed to
* initiate a print job request
* @throws PrinterException if an error in the print system causes the job
* to be aborted
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean, PrintService)
* @see #getPrintable
*
* @since 1.5
*/
public boolean print() throws PrinterException {
return print(PrintMode.FIT_WIDTH);
}
/** {@collect.stats}
* A convenience method that displays a printing dialog, and then prints
* this <code>JTable</code> in the given printing mode,
* with no header or footer text. A modal progress dialog, with an abort
* option, will be shown for the duration of printing.
* <p>
* Note: In headless mode, no dialogs are shown and printing
* occurs on the default printer.
*
* @param printMode the printing mode that the printable should use
* @return true, unless printing is cancelled by the user
* @throws SecurityException if this thread is not allowed to
* initiate a print job request
* @throws PrinterException if an error in the print system causes the job
* to be aborted
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean, PrintService)
* @see #getPrintable
*
* @since 1.5
*/
public boolean print(PrintMode printMode) throws PrinterException {
return print(printMode, null, null);
}
/** {@collect.stats}
* A convenience method that displays a printing dialog, and then prints
* this <code>JTable</code> in the given printing mode,
* with the specified header and footer text. A modal progress dialog,
* with an abort option, will be shown for the duration of printing.
* <p>
* Note: In headless mode, no dialogs are shown and printing
* occurs on the default printer.
*
* @param printMode the printing mode that the printable should use
* @param headerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a header,
* or null for none
* @param footerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a footer,
* or null for none
* @return true, unless printing is cancelled by the user
* @throws SecurityException if this thread is not allowed to
* initiate a print job request
* @throws PrinterException if an error in the print system causes the job
* to be aborted
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean, PrintService)
* @see #getPrintable
*
* @since 1.5
*/
public boolean print(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat) throws PrinterException {
boolean showDialogs = !GraphicsEnvironment.isHeadless();
return print(printMode, headerFormat, footerFormat,
showDialogs, null, showDialogs);
}
/** {@collect.stats}
* Prints this table, as specified by the fully featured
* {@link #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean, PrintService) print}
* method, with the default printer specified as the print service.
*
* @param printMode the printing mode that the printable should use
* @param headerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a header,
* or <code>null</code> for none
* @param footerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a footer,
* or <code>null</code> for none
* @param showPrintDialog whether or not to display a print dialog
* @param attr a <code>PrintRequestAttributeSet</code>
* specifying any printing attributes,
* or <code>null</code> for none
* @param interactive whether or not to print in an interactive mode
* @return true, unless printing is cancelled by the user
* @throws HeadlessException if the method is asked to show a printing
* dialog or run interactively, and
* <code>GraphicsEnvironment.isHeadless</code>
* returns <code>true</code>
* @throws SecurityException if this thread is not allowed to
* initiate a print job request
* @throws PrinterException if an error in the print system causes the job
* to be aborted
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean, PrintService)
* @see #getPrintable
*
* @since 1.5
*/
public boolean print(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat,
boolean showPrintDialog,
PrintRequestAttributeSet attr,
boolean interactive) throws PrinterException,
HeadlessException {
return print(printMode,
headerFormat,
footerFormat,
showPrintDialog,
attr,
interactive,
null);
}
/** {@collect.stats}
* Prints this <code>JTable</code>. Takes steps that the majority of
* developers would take in order to print a <code>JTable</code>.
* In short, it prepares the table, calls <code>getPrintable</code> to
* fetch an appropriate <code>Printable</code>, and then sends it to the
* printer.
* <p>
* A <code>boolean</code> parameter allows you to specify whether or not
* a printing dialog is displayed to the user. When it is, the user may
* use the dialog to change the destination printer or printing attributes,
* or even to cancel the print. Another two parameters allow for a
* <code>PrintService</code> and printing attributes to be specified.
* These parameters can be used either to provide initial values for the
* print dialog, or to specify values when the dialog is not shown.
* <p>
* A second <code>boolean</code> parameter allows you to specify whether
* or not to perform printing in an interactive mode. If <code>true</code>,
* a modal progress dialog, with an abort option, is displayed for the
* duration of printing . This dialog also prevents any user action which
* may affect the table. However, it can not prevent the table from being
* modified by code (for example, another thread that posts updates using
* <code>SwingUtilities.invokeLater</code>). It is therefore the
* responsibility of the developer to ensure that no other code modifies
* the table in any way during printing (invalid modifications include
* changes in: size, renderers, or underlying data). Printing behavior is
* undefined when the table is changed during printing.
* <p>
* If <code>false</code> is specified for this parameter, no dialog will
* be displayed and printing will begin immediately on the event-dispatch
* thread. This blocks any other events, including repaints, from being
* processed until printing is complete. Although this effectively prevents
* the table from being changed, it doesn't provide a good user experience.
* For this reason, specifying <code>false</code> is only recommended when
* printing from an application with no visible GUI.
* <p>
* Note: Attempting to show the printing dialog or run interactively, while
* in headless mode, will result in a <code>HeadlessException</code>.
* <p>
* Before fetching the printable, this method will gracefully terminate
* editing, if necessary, to prevent an editor from showing in the printed
* result. Additionally, <code>JTable</code> will prepare its renderers
* during printing such that selection and focus are not indicated.
* As far as customizing further how the table looks in the printout,
* developers can provide custom renderers or paint code that conditionalize
* on the value of {@link javax.swing.JComponent#isPaintingForPrint()}.
* <p>
* See {@link #getPrintable} for more description on how the table is
* printed.
*
* @param printMode the printing mode that the printable should use
* @param headerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a header,
* or <code>null</code> for none
* @param footerFormat a <code>MessageFormat</code> specifying the text
* to be used in printing a footer,
* or <code>null</code> for none
* @param showPrintDialog whether or not to display a print dialog
* @param attr a <code>PrintRequestAttributeSet</code>
* specifying any printing attributes,
* or <code>null</code> for none
* @param interactive whether or not to print in an interactive mode
* @param service the destination <code>PrintService</code>,
* or <code>null</code> to use the default printer
* @return true, unless printing is cancelled by the user
* @throws HeadlessException if the method is asked to show a printing
* dialog or run interactively, and
* <code>GraphicsEnvironment.isHeadless</code>
* returns <code>true</code>
* @throws SecurityException if a security manager exists and its
* {@link java.lang.SecurityManager#checkPrintJobAccess}
* method disallows this thread from creating a print job request
* @throws PrinterException if an error in the print system causes the job
* to be aborted
* @see #getPrintable
* @see java.awt.GraphicsEnvironment#isHeadless
*
* @since 1.6
*/
public boolean print(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat,
boolean showPrintDialog,
PrintRequestAttributeSet attr,
boolean interactive,
PrintService service) throws PrinterException,
HeadlessException {
// complain early if an invalid parameter is specified for headless mode
boolean isHeadless = GraphicsEnvironment.isHeadless();
if (isHeadless) {
if (showPrintDialog) {
throw new HeadlessException("Can't show print dialog.");
}
if (interactive) {
throw new HeadlessException("Can't run interactively.");
}
}
// Get a PrinterJob.
// Do this before anything with side-effects since it may throw a
// security exception - in which case we don't want to do anything else.
final PrinterJob job = PrinterJob.getPrinterJob();
if (isEditing()) {
// try to stop cell editing, and failing that, cancel it
if (!getCellEditor().stopCellEditing()) {
getCellEditor().cancelCellEditing();
}
}
if (attr == null) {
attr = new HashPrintRequestAttributeSet();
}
final PrintingStatus printingStatus;
// fetch the Printable
Printable printable =
getPrintable(printMode, headerFormat, footerFormat);
if (interactive) {
// wrap the Printable so that we can print on another thread
printable = new ThreadSafePrintable(printable);
printingStatus = PrintingStatus.createPrintingStatus(this, job);
printable = printingStatus.createNotificationPrintable(printable);
} else {
// to please compiler
printingStatus = null;
}
// set the printable on the PrinterJob
job.setPrintable(printable);
// if specified, set the PrintService on the PrinterJob
if (service != null) {
job.setPrintService(service);
}
// if requested, show the print dialog
if (showPrintDialog && !job.printDialog(attr)) {
// the user cancelled the print dialog
return false;
}
// if not interactive, just print on this thread (no dialog)
if (!interactive) {
// do the printing
job.print(attr);
// we're done
return true;
}
// make sure this is clear since we'll check it after
printError = null;
// to synchronize on
final Object lock = new Object();
// copied so we can access from the inner class
final PrintRequestAttributeSet copyAttr = attr;
// this runnable will be used to do the printing
// (and save any throwables) on another thread
Runnable runnable = new Runnable() {
public void run() {
try {
// do the printing
job.print(copyAttr);
} catch (Throwable t) {
// save any Throwable to be rethrown
synchronized(lock) {
printError = t;
}
} finally {
// we're finished - hide the dialog
printingStatus.dispose();
}
}
};
// start printing on another thread
Thread th = new Thread(runnable);
th.start();
printingStatus.showModal(true);
// look for any error that the printing may have generated
Throwable pe;
synchronized(lock) {
pe = printError;
printError = null;
}
// check the type of error and handle it
if (pe != null) {
// a subclass of PrinterException meaning the job was aborted,
// in this case, by the user
if (pe instanceof PrinterAbortException) {
return false;
} else if (pe instanceof PrinterException) {
throw (PrinterException)pe;
} else if (pe instanceof RuntimeException) {
throw (RuntimeException)pe;
} else if (pe instanceof Error) {
throw (Error)pe;
}
// can not happen
throw new AssertionError(pe);
}
return true;
}
/** {@collect.stats}
* Return a <code>Printable</code> for use in printing this JTable.
* <p>
* This method is meant for those wishing to customize the default
* <code>Printable</code> implementation used by <code>JTable</code>'s
* <code>print</code> methods. Developers wanting simply to print the table
* should use one of those methods directly.
* <p>
* The <code>Printable</code> can be requested in one of two printing modes.
* In both modes, it spreads table rows naturally in sequence across
* multiple pages, fitting as many rows as possible per page.
* <code>PrintMode.NORMAL</code> specifies that the table be
* printed at its current size. In this mode, there may be a need to spread
* columns across pages in a similar manner to that of the rows. When the
* need arises, columns are distributed in an order consistent with the
* table's <code>ComponentOrientation</code>.
* <code>PrintMode.FIT_WIDTH</code> specifies that the output be
* scaled smaller, if necessary, to fit the table's entire width
* (and thereby all columns) on each page. Width and height are scaled
* equally, maintaining the aspect ratio of the output.
* <p>
* The <code>Printable</code> heads the portion of table on each page
* with the appropriate section from the table's <code>JTableHeader</code>,
* if it has one.
* <p>
* Header and footer text can be added to the output by providing
* <code>MessageFormat</code> arguments. The printing code requests
* Strings from the formats, providing a single item which may be included
* in the formatted string: an <code>Integer</code> representing the current
* page number.
* <p>
* You are encouraged to read the documentation for
* <code>MessageFormat</code> as some characters, such as single-quote,
* are special and need to be escaped.
* <p>
* Here's an example of creating a <code>MessageFormat</code> that can be
* used to print "Duke's Table: Page - " and the current page number:
* <p>
* <pre>
* // notice the escaping of the single quote
* // notice how the page number is included with "{0}"
* MessageFormat format = new MessageFormat("Duke''s Table: Page - {0}");
* </pre>
* <p>
* The <code>Printable</code> constrains what it draws to the printable
* area of each page that it prints. Under certain circumstances, it may
* find it impossible to fit all of a page's content into that area. In
* these cases the output may be clipped, but the implementation
* makes an effort to do something reasonable. Here are a few situations
* where this is known to occur, and how they may be handled by this
* particular implementation:
* <ul>
* <li>In any mode, when the header or footer text is too wide to fit
* completely in the printable area -- print as much of the text as
* possible starting from the beginning, as determined by the table's
* <code>ComponentOrientation</code>.
* <li>In any mode, when a row is too tall to fit in the
* printable area -- print the upper-most portion of the row
* and paint no lower border on the table.
* <li>In <code>PrintMode.NORMAL</code> when a column
* is too wide to fit in the printable area -- print the center
* portion of the column and leave the left and right borders
* off the table.
* </ul>
* <p>
* It is entirely valid for this <code>Printable</code> to be wrapped
* inside another in order to create complex reports and documents. You may
* even request that different pages be rendered into different sized
* printable areas. The implementation must be prepared to handle this
* (possibly by doing its layout calculations on the fly). However,
* providing different heights to each page will likely not work well
* with <code>PrintMode.NORMAL</code> when it has to spread columns
* across pages.
* <p>
* As far as customizing how the table looks in the printed result,
* <code>JTable</code> itself will take care of hiding the selection
* and focus during printing. For additional customizations, your
* renderers or painting code can customize the look based on the value
* of {@link javax.swing.JComponent#isPaintingForPrint()}
* <p>
* Also, <i>before</i> calling this method you may wish to <i>first</i>
* modify the state of the table, such as to cancel cell editing or
* have the user size the table appropriately. However, you must not
* modify the state of the table <i>after</i> this <code>Printable</code>
* has been fetched (invalid modifications include changes in size or
* underlying data). The behavior of the returned <code>Printable</code>
* is undefined once the table has been changed.
*
* @param printMode the printing mode that the printable should use
* @param headerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a header, or null for none
* @param footerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a footer, or null for none
* @return a <code>Printable</code> for printing this JTable
* @see #print(JTable.PrintMode, MessageFormat, MessageFormat,
* boolean, PrintRequestAttributeSet, boolean)
* @see Printable
* @see PrinterJob
*
* @since 1.5
*/
public Printable getPrintable(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat) {
return new TablePrintable(this, printMode, headerFormat, footerFormat);
}
/** {@collect.stats}
* A <code>Printable</code> implementation that wraps another
* <code>Printable</code>, making it safe for printing on another thread.
*/
private class ThreadSafePrintable implements Printable {
/** {@collect.stats} The delegate <code>Printable</code>. */
private Printable printDelegate;
/** {@collect.stats}
* To communicate any return value when delegating.
*/
private int retVal;
/** {@collect.stats}
* To communicate any <code>Throwable</code> when delegating.
*/
private Throwable retThrowable;
/** {@collect.stats}
* Construct a <code>ThreadSafePrintable</code> around the given
* delegate.
*
* @param printDelegate the <code>Printable</code> to delegate to
*/
public ThreadSafePrintable(Printable printDelegate) {
this.printDelegate = printDelegate;
}
/** {@collect.stats}
* Prints the specified page into the given {@link Graphics}
* context, in the specified format.
* <p>
* Regardless of what thread this method is called on, all calls into
* the delegate will be done on the event-dispatch thread.
*
* @param graphics the context into which the page is drawn
* @param pageFormat the size and orientation of the page being drawn
* @param pageIndex the zero based index of the page to be drawn
* @return PAGE_EXISTS if the page is rendered successfully, or
* NO_SUCH_PAGE if a non-existent page index is specified
* @throws PrinterException if an error causes printing to be aborted
*/
public int print(final Graphics graphics,
final PageFormat pageFormat,
final int pageIndex) throws PrinterException {
// We'll use this Runnable
Runnable runnable = new Runnable() {
public synchronized void run() {
try {
// call into the delegate and save the return value
retVal = printDelegate.print(graphics, pageFormat, pageIndex);
} catch (Throwable throwable) {
// save any Throwable to be rethrown
retThrowable = throwable;
} finally {
// notify the caller that we're done
notifyAll();
}
}
};
synchronized(runnable) {
// make sure these are initialized
retVal = -1;
retThrowable = null;
// call into the EDT
SwingUtilities.invokeLater(runnable);
// wait for the runnable to finish
while (retVal == -1 && retThrowable == null) {
try {
runnable.wait();
} catch (InterruptedException ie) {
// short process, safe to ignore interrupts
}
}
// if the delegate threw a throwable, rethrow it here
if (retThrowable != null) {
if (retThrowable instanceof PrinterException) {
throw (PrinterException)retThrowable;
} else if (retThrowable instanceof RuntimeException) {
throw (RuntimeException)retThrowable;
} else if (retThrowable instanceof Error) {
throw (Error)retThrowable;
}
// can not happen
throw new AssertionError(retThrowable);
}
return retVal;
}
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JTable.
* For tables, the AccessibleContext takes the form of an
* AccessibleJTable.
* A new AccessibleJTable instance is created if necessary.
*
* @return an AccessibleJTable that serves as the
* AccessibleContext of this JTable
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTable();
}
return accessibleContext;
}
//
// *** should also implement AccessibleSelection?
// *** and what's up with keyboard navigation/manipulation?
//
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTable</code> class. It provides an implementation of the
* Java Accessibility API appropriate to table user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJTable extends AccessibleJComponent
implements AccessibleSelection, ListSelectionListener, TableModelListener,
TableColumnModelListener, CellEditorListener, PropertyChangeListener,
AccessibleExtendedTable {
int lastSelectedRow;
int lastSelectedCol;
/** {@collect.stats}
* AccessibleJTable constructor
*
* @since 1.5
*/
protected AccessibleJTable() {
super();
JTable.this.addPropertyChangeListener(this);
JTable.this.getSelectionModel().addListSelectionListener(this);
TableColumnModel tcm = JTable.this.getColumnModel();
tcm.addColumnModelListener(this);
tcm.getSelectionModel().addListSelectionListener(this);
JTable.this.getModel().addTableModelListener(this);
lastSelectedRow = JTable.this.getSelectedRow();
lastSelectedCol = JTable.this.getSelectedColumn();
}
// Listeners to track model, etc. changes to as to re-place the other
// listeners
/** {@collect.stats}
* Track changes to selection model, column model, etc. so as to
* be able to re-place listeners on those in order to pass on
* information to the Accessibility PropertyChange mechanism
*/
public void propertyChange(PropertyChangeEvent e) {
String name = e.getPropertyName();
Object oldValue = e.getOldValue();
Object newValue = e.getNewValue();
// re-set tableModel listeners
if (name.compareTo("model") == 0) {
if (oldValue != null && oldValue instanceof TableModel) {
((TableModel) oldValue).removeTableModelListener(this);
}
if (newValue != null && newValue instanceof TableModel) {
((TableModel) newValue).addTableModelListener(this);
}
// re-set selectionModel listeners
} else if (name.compareTo("selectionModel") == 0) {
Object source = e.getSource();
if (source == JTable.this) { // row selection model
if (oldValue != null &&
oldValue instanceof ListSelectionModel) {
((ListSelectionModel) oldValue).removeListSelectionListener(this);
}
if (newValue != null &&
newValue instanceof ListSelectionModel) {
((ListSelectionModel) newValue).addListSelectionListener(this);
}
} else if (source == JTable.this.getColumnModel()) {
if (oldValue != null &&
oldValue instanceof ListSelectionModel) {
((ListSelectionModel) oldValue).removeListSelectionListener(this);
}
if (newValue != null &&
newValue instanceof ListSelectionModel) {
((ListSelectionModel) newValue).addListSelectionListener(this);
}
} else {
// System.out.println("!!! Bug in source of selectionModel propertyChangeEvent");
}
// re-set columnModel listeners
// and column's selection property listener as well
} else if (name.compareTo("columnModel") == 0) {
if (oldValue != null && oldValue instanceof TableColumnModel) {
TableColumnModel tcm = (TableColumnModel) oldValue;
tcm.removeColumnModelListener(this);
tcm.getSelectionModel().removeListSelectionListener(this);
}
if (newValue != null && newValue instanceof TableColumnModel) {
TableColumnModel tcm = (TableColumnModel) newValue;
tcm.addColumnModelListener(this);
tcm.getSelectionModel().addListSelectionListener(this);
}
// re-se cellEditor listeners
} else if (name.compareTo("tableCellEditor") == 0) {
if (oldValue != null && oldValue instanceof TableCellEditor) {
((TableCellEditor) oldValue).removeCellEditorListener((CellEditorListener) this);
}
if (newValue != null && newValue instanceof TableCellEditor) {
((TableCellEditor) newValue).addCellEditorListener((CellEditorListener) this);
}
}
}
// Listeners to echo changes to the AccessiblePropertyChange mechanism
/*
* Describes a change in the accessible table model.
*/
protected class AccessibleJTableModelChange
implements AccessibleTableModelChange {
protected int type;
protected int firstRow;
protected int lastRow;
protected int firstColumn;
protected int lastColumn;
protected AccessibleJTableModelChange(int type, int firstRow,
int lastRow, int firstColumn,
int lastColumn) {
this.type = type;
this.firstRow = firstRow;
this.lastRow = lastRow;
this.firstColumn = firstColumn;
this.lastColumn = lastColumn;
}
public int getType() {
return type;
}
public int getFirstRow() {
return firstRow;
}
public int getLastRow() {
return lastRow;
}
public int getFirstColumn() {
return firstColumn;
}
public int getLastColumn() {
return lastColumn;
}
}
/** {@collect.stats}
* Track changes to the table contents
*/
public void tableChanged(TableModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
if (e != null) {
int firstColumn = e.getColumn();
int lastColumn = e.getColumn();
if (firstColumn == TableModelEvent.ALL_COLUMNS) {
firstColumn = 0;
lastColumn = getColumnCount() - 1;
}
// Fire a property change event indicating the table model
// has changed.
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(e.getType(),
e.getFirstRow(),
e.getLastRow(),
firstColumn,
lastColumn);
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
}
}
/** {@collect.stats}
* Track changes to the table contents (row insertions)
*/
public void tableRowsInserted(TableModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
// Fire a property change event indicating the table model
// has changed.
int firstColumn = e.getColumn();
int lastColumn = e.getColumn();
if (firstColumn == TableModelEvent.ALL_COLUMNS) {
firstColumn = 0;
lastColumn = getColumnCount() - 1;
}
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(e.getType(),
e.getFirstRow(),
e.getLastRow(),
firstColumn,
lastColumn);
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
}
/** {@collect.stats}
* Track changes to the table contents (row deletions)
*/
public void tableRowsDeleted(TableModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
// Fire a property change event indicating the table model
// has changed.
int firstColumn = e.getColumn();
int lastColumn = e.getColumn();
if (firstColumn == TableModelEvent.ALL_COLUMNS) {
firstColumn = 0;
lastColumn = getColumnCount() - 1;
}
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(e.getType(),
e.getFirstRow(),
e.getLastRow(),
firstColumn,
lastColumn);
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
}
/** {@collect.stats}
* Track changes to the table contents (column insertions)
*/
public void columnAdded(TableColumnModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
// Fire a property change event indicating the table model
// has changed.
int type = AccessibleTableModelChange.INSERT;
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(type,
0,
0,
e.getFromIndex(),
e.getToIndex());
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
}
/** {@collect.stats}
* Track changes to the table contents (column deletions)
*/
public void columnRemoved(TableColumnModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
// Fire a property change event indicating the table model
// has changed.
int type = AccessibleTableModelChange.DELETE;
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(type,
0,
0,
e.getFromIndex(),
e.getToIndex());
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
}
/** {@collect.stats}
* Track changes of a column repositioning.
*
* @see TableColumnModelListener
*/
public void columnMoved(TableColumnModelEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
// Fire property change events indicating the table model
// has changed.
int type = AccessibleTableModelChange.DELETE;
AccessibleJTableModelChange change =
new AccessibleJTableModelChange(type,
0,
0,
e.getFromIndex(),
e.getFromIndex());
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change);
int type2 = AccessibleTableModelChange.INSERT;
AccessibleJTableModelChange change2 =
new AccessibleJTableModelChange(type2,
0,
0,
e.getToIndex(),
e.getToIndex());
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_MODEL_CHANGED,
null, change2);
}
/** {@collect.stats}
* Track changes of a column moving due to margin changes.
*
* @see TableColumnModelListener
*/
public void columnMarginChanged(ChangeEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
}
/** {@collect.stats}
* Track that the selection model of the TableColumnModel changed.
*
* @see TableColumnModelListener
*/
public void columnSelectionChanged(ListSelectionEvent e) {
// we should now re-place our TableColumn listener
}
/** {@collect.stats}
* Track changes to a cell's contents.
*
* Invoked when editing is finished. The changes are saved, the
* editor object is discarded, and the cell is rendered once again.
*
* @see CellEditorListener
*/
public void editingStopped(ChangeEvent e) {
// it'd be great if we could figure out which cell, and pass that
// somehow as a parameter
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, null);
}
/** {@collect.stats}
* Invoked when editing is canceled. The editor object is discarded
* and the cell is rendered once again.
*
* @see CellEditorListener
*/
public void editingCanceled(ChangeEvent e) {
// nothing to report, 'cause nothing changed
}
/** {@collect.stats}
* Track changes to table cell selections
*/
public void valueChanged(ListSelectionEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
int selectedRow = JTable.this.getSelectedRow();
int selectedCol = JTable.this.getSelectedColumn();
if (selectedRow != lastSelectedRow ||
selectedCol != lastSelectedCol) {
Accessible oldA = getAccessibleAt(lastSelectedRow,
lastSelectedCol);
Accessible newA = getAccessibleAt(selectedRow, selectedCol);
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldA, newA);
lastSelectedRow = selectedRow;
lastSelectedCol = selectedCol;
}
}
// AccessibleContext support
/** {@collect.stats}
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TABLE;
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child, if one exists,
* contained at the local coordinate <code>Point</code>.
*
* @param p the point defining the top-left corner of the
* <code>Accessible</code>, given in the coordinate space
* of the object's parent
* @return the <code>Accessible</code>, if it exists,
* at the specified location; else <code>null</code>
*/
public Accessible getAccessibleAt(Point p) {
int column = columnAtPoint(p);
int row = rowAtPoint(p);
if ((column != -1) && (row != -1)) {
TableColumn aColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = aColumn.getCellRenderer();
if (renderer == null) {
Class<?> columnClass = getColumnClass(column);
renderer = getDefaultRenderer(columnClass);
}
Component component = renderer.getTableCellRendererComponent(
JTable.this, null, false, false,
row, column);
return new AccessibleJTableCell(JTable.this, row, column,
getAccessibleIndexAt(row, column));
}
return null;
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement <code>Accessible</code>,
* then this method should return the number of children of this object.
*
* @return the number of accessible children in the object
*/
public int getAccessibleChildrenCount() {
return (JTable.this.getColumnCount() * JTable.this.getRowCount());
}
/** {@collect.stats}
* Returns the nth <code>Accessible</code> child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
// children increase across, and then down, for tables
// (arbitrary decision)
int column = getAccessibleColumnAtIndex(i);
int row = getAccessibleRowAtIndex(i);
TableColumn aColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = aColumn.getCellRenderer();
if (renderer == null) {
Class<?> columnClass = getColumnClass(column);
renderer = getDefaultRenderer(columnClass);
}
Component component = renderer.getTableCellRendererComponent(
JTable.this, null, false, false,
row, column);
return new AccessibleJTableCell(JTable.this, row, column,
getAccessibleIndexAt(row, column));
}
}
// AccessibleSelection support
/** {@collect.stats}
* Returns the number of <code>Accessible</code> children
* currently selected.
* If no children are selected, the return value will be 0.
*
* @return the number of items currently selected
*/
public int getAccessibleSelectionCount() {
int rowsSel = JTable.this.getSelectedRowCount();
int colsSel = JTable.this.getSelectedColumnCount();
if (JTable.this.cellSelectionEnabled) { // a contiguous block
return rowsSel * colsSel;
} else {
// a column swath and a row swath, with a shared block
if (JTable.this.getRowSelectionAllowed() &&
JTable.this.getColumnSelectionAllowed()) {
return rowsSel * JTable.this.getColumnCount() +
colsSel * JTable.this.getRowCount() -
rowsSel * colsSel;
// just one or more rows in selection
} else if (JTable.this.getRowSelectionAllowed()) {
return rowsSel * JTable.this.getColumnCount();
// just one or more rows in selection
} else if (JTable.this.getColumnSelectionAllowed()) {
return colsSel * JTable.this.getRowCount();
} else {
return 0; // JTable doesn't allow selections
}
}
}
/** {@collect.stats}
* Returns an <code>Accessible</code> representing the
* specified selected child in the object. If there
* isn't a selection, or there are fewer children selected
* than the integer passed in, the return
* value will be <code>null</code>.
* <p>Note that the index represents the i-th selected child, which
* is different from the i-th child.
*
* @param i the zero-based index of selected children
* @return the i-th selected child
* @see #getAccessibleSelectionCount
*/
public Accessible getAccessibleSelection(int i) {
if (i < 0 || i > getAccessibleSelectionCount()) {
return (Accessible) null;
}
int rowsSel = JTable.this.getSelectedRowCount();
int colsSel = JTable.this.getSelectedColumnCount();
int rowIndicies[] = getSelectedRows();
int colIndicies[] = getSelectedColumns();
int ttlCols = JTable.this.getColumnCount();
int ttlRows = JTable.this.getRowCount();
int r;
int c;
if (JTable.this.cellSelectionEnabled) { // a contiguous block
r = rowIndicies[i / colsSel];
c = colIndicies[i % colsSel];
return getAccessibleChild((r * ttlCols) + c);
} else {
// a column swath and a row swath, with a shared block
if (JTable.this.getRowSelectionAllowed() &&
JTable.this.getColumnSelectionAllowed()) {
// Situation:
// We have a table, like the 6x3 table below,
// wherein three colums and one row selected
// (selected cells marked with "*", unselected "0"):
//
// 0 * 0 * * 0
// * * * * * *
// 0 * 0 * * 0
//
// State machine below walks through the array of
// selected rows in two states: in a selected row,
// and not in one; continuing until we are in a row
// in which the ith selection exists. Then we return
// the appropriate cell. In the state machine, we
// always do rows above the "current" selected row first,
// then the cells in the selected row. If we're done
// with the state machine before finding the requested
// selected child, we handle the rows below the last
// selected row at the end.
//
int curIndex = i;
final int IN_ROW = 0;
final int NOT_IN_ROW = 1;
int state = (rowIndicies[0] == 0 ? IN_ROW : NOT_IN_ROW);
int j = 0;
int prevRow = -1;
while (j < rowIndicies.length) {
switch (state) {
case IN_ROW: // on individual row full of selections
if (curIndex < ttlCols) { // it's here!
c = curIndex % ttlCols;
r = rowIndicies[j];
return getAccessibleChild((r * ttlCols) + c);
} else { // not here
curIndex -= ttlCols;
}
// is the next row in table selected or not?
if (j + 1 == rowIndicies.length ||
rowIndicies[j] != rowIndicies[j+1] - 1) {
state = NOT_IN_ROW;
prevRow = rowIndicies[j];
}
j++; // we didn't return earlier, so go to next row
break;
case NOT_IN_ROW: // sparse bunch of rows of selections
if (curIndex <
(colsSel * (rowIndicies[j] -
(prevRow == -1 ? 0 : (prevRow + 1))))) {
// it's here!
c = colIndicies[curIndex % colsSel];
r = (j > 0 ? rowIndicies[j-1] + 1 : 0)
+ curIndex / colsSel;
return getAccessibleChild((r * ttlCols) + c);
} else { // not here
curIndex -= colsSel * (rowIndicies[j] -
(prevRow == -1 ? 0 : (prevRow + 1)));
}
state = IN_ROW;
break;
}
}
// we got here, so we didn't find it yet; find it in
// the last sparse bunch of rows
if (curIndex <
(colsSel * (ttlRows -
(prevRow == -1 ? 0 : (prevRow + 1))))) { // it's here!
c = colIndicies[curIndex % colsSel];
r = rowIndicies[j-1] + curIndex / colsSel + 1;
return getAccessibleChild((r * ttlCols) + c);
} else { // not here
// we shouldn't get to this spot in the code!
// System.out.println("Bug in AccessibleJTable.getAccessibleSelection()");
}
// one or more rows selected
} else if (JTable.this.getRowSelectionAllowed()) {
c = i % ttlCols;
r = rowIndicies[i / ttlCols];
return getAccessibleChild((r * ttlCols) + c);
// one or more columns selected
} else if (JTable.this.getColumnSelectionAllowed()) {
c = colIndicies[i % colsSel];
r = i / colsSel;
return getAccessibleChild((r * ttlCols) + c);
}
}
return (Accessible) null;
}
/** {@collect.stats}
* Determines if the current child of this object is selected.
*
* @param i the zero-based index of the child in this
* <code>Accessible</code> object
* @return true if the current child of this object is selected
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
int column = getAccessibleColumnAtIndex(i);
int row = getAccessibleRowAtIndex(i);
return JTable.this.isCellSelected(row, column);
}
/** {@collect.stats}
* Adds the specified <code>Accessible</code> child of the
* object to the object's selection. If the object supports
* multiple selections, the specified child is added to
* any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified child is already selected, this method has no effect.
* <p>
* This method only works on <code>JTable</code>s which have
* individual cell selection enabled.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
*/
public void addAccessibleSelection(int i) {
// TIGER - 4495286
int column = getAccessibleColumnAtIndex(i);
int row = getAccessibleRowAtIndex(i);
JTable.this.changeSelection(row, column, true, false);
}
/** {@collect.stats}
* Removes the specified child of the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
* <p>
* This method only works on <code>JTables</code> which have
* individual cell selection enabled.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
*/
public void removeAccessibleSelection(int i) {
if (JTable.this.cellSelectionEnabled) {
int column = getAccessibleColumnAtIndex(i);
int row = getAccessibleRowAtIndex(i);
JTable.this.removeRowSelectionInterval(row, row);
JTable.this.removeColumnSelectionInterval(column, column);
}
}
/** {@collect.stats}
* Clears the selection in the object, so that no children in the
* object are selected.
*/
public void clearAccessibleSelection() {
JTable.this.clearSelection();
}
/** {@collect.stats}
* Causes every child of the object to be selected, but only
* if the <code>JTable</code> supports multiple selections,
* and if individual cell selection is enabled.
*/
public void selectAllAccessibleSelection() {
if (JTable.this.cellSelectionEnabled) {
JTable.this.selectAll();
}
}
// begin AccessibleExtendedTable implementation -------------
/** {@collect.stats}
* Returns the row number of an index in the table.
*
* @param index the zero-based index in the table
* @return the zero-based row of the table if one exists;
* otherwise -1.
* @since 1.4
*/
public int getAccessibleRow(int index) {
return getAccessibleRowAtIndex(index);
}
/** {@collect.stats}
* Returns the column number of an index in the table.
*
* @param index the zero-based index in the table
* @return the zero-based column of the table if one exists;
* otherwise -1.
* @since 1.4
*/
public int getAccessibleColumn(int index) {
return getAccessibleColumnAtIndex(index);
}
/** {@collect.stats}
* Returns the index at a row and column in the table.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the zero-based index in the table if one exists;
* otherwise -1.
* @since 1.4
*/
public int getAccessibleIndex(int r, int c) {
return getAccessibleIndexAt(r, c);
}
// end of AccessibleExtendedTable implementation ------------
// start of AccessibleTable implementation ------------------
private Accessible caption;
private Accessible summary;
private Accessible [] rowDescription;
private Accessible [] columnDescription;
/** {@collect.stats}
* Gets the <code>AccessibleTable</code> associated with this
* object. In the implementation of the Java Accessibility
* API for this class, return this object, which is responsible
* for implementing the <code>AccessibleTables</code> interface
* on behalf of itself.
*
* @return this object
* @since 1.3
*/
public AccessibleTable getAccessibleTable() {
return this;
}
/** {@collect.stats}
* Returns the caption for the table.
*
* @return the caption for the table
* @since 1.3
*/
public Accessible getAccessibleCaption() {
return this.caption;
}
/** {@collect.stats}
* Sets the caption for the table.
*
* @param a the caption for the table
* @since 1.3
*/
public void setAccessibleCaption(Accessible a) {
Accessible oldCaption = caption;
this.caption = a;
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_CAPTION_CHANGED,
oldCaption, this.caption);
}
/** {@collect.stats}
* Returns the summary description of the table.
*
* @return the summary description of the table
* @since 1.3
*/
public Accessible getAccessibleSummary() {
return this.summary;
}
/** {@collect.stats}
* Sets the summary description of the table.
*
* @param a the summary description of the table
* @since 1.3
*/
public void setAccessibleSummary(Accessible a) {
Accessible oldSummary = summary;
this.summary = a;
firePropertyChange(AccessibleContext.ACCESSIBLE_TABLE_SUMMARY_CHANGED,
oldSummary, this.summary);
}
/*
* Returns the total number of rows in this table.
*
* @return the total number of rows in this table
*/
public int getAccessibleRowCount() {
return JTable.this.getRowCount();
}
/*
* Returns the total number of columns in the table.
*
* @return the total number of columns in the table
*/
public int getAccessibleColumnCount() {
return JTable.this.getColumnCount();
}
/*
* Returns the <code>Accessible</code> at a specified row
* and column in the table.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the <code>Accessible</code> at the specified row and column
* in the table
*/
public Accessible getAccessibleAt(int r, int c) {
return getAccessibleChild((r * getAccessibleColumnCount()) + c);
}
/** {@collect.stats}
* Returns the number of rows occupied by the <code>Accessible</code>
* at a specified row and column in the table.
*
* @return the number of rows occupied by the <code>Accessible</code>
* at a specified row and column in the table
* @since 1.3
*/
public int getAccessibleRowExtentAt(int r, int c) {
return 1;
}
/** {@collect.stats}
* Returns the number of columns occupied by the
* <code>Accessible</code> at a given (row, column).
*
* @return the number of columns occupied by the <code>Accessible</code>
* at a specified row and column in the table
* @since 1.3
*/
public int getAccessibleColumnExtentAt(int r, int c) {
return 1;
}
/** {@collect.stats}
* Returns the row headers as an <code>AccessibleTable</code>.
*
* @return an <code>AccessibleTable</code> representing the row
* headers
* @since 1.3
*/
public AccessibleTable getAccessibleRowHeader() {
// row headers are not supported
return null;
}
/** {@collect.stats}
* Sets the row headers as an <code>AccessibleTable</code>.
*
* @param a an <code>AccessibleTable</code> representing the row
* headers
* @since 1.3
*/
public void setAccessibleRowHeader(AccessibleTable a) {
// row headers are not supported
}
/** {@collect.stats}
* Returns the column headers as an <code>AccessibleTable</code>.
*
* @return an <code>AccessibleTable</code> representing the column
* headers, or <code>null</code> if the table header is
* <code>null</code>
* @since 1.3
*/
public AccessibleTable getAccessibleColumnHeader() {
JTableHeader header = JTable.this.getTableHeader();
return header == null ? null : new AccessibleTableHeader(header);
}
/*
* Private class representing a table column header
*/
private class AccessibleTableHeader implements AccessibleTable {
private JTableHeader header;
private TableColumnModel headerModel;
AccessibleTableHeader(JTableHeader header) {
this.header = header;
this.headerModel = header.getColumnModel();
}
/** {@collect.stats}
* Returns the caption for the table.
*
* @return the caption for the table
*/
public Accessible getAccessibleCaption() { return null; }
/** {@collect.stats}
* Sets the caption for the table.
*
* @param a the caption for the table
*/
public void setAccessibleCaption(Accessible a) {}
/** {@collect.stats}
* Returns the summary description of the table.
*
* @return the summary description of the table
*/
public Accessible getAccessibleSummary() { return null; }
/** {@collect.stats}
* Sets the summary description of the table
*
* @param a the summary description of the table
*/
public void setAccessibleSummary(Accessible a) {}
/** {@collect.stats}
* Returns the number of rows in the table.
*
* @return the number of rows in the table
*/
public int getAccessibleRowCount() { return 1; }
/** {@collect.stats}
* Returns the number of columns in the table.
*
* @return the number of columns in the table
*/
public int getAccessibleColumnCount() {
return headerModel.getColumnCount();
}
/** {@collect.stats}
* Returns the Accessible at a specified row and column
* in the table.
*
* @param row zero-based row of the table
* @param column zero-based column of the table
* @return the Accessible at the specified row and column
*/
public Accessible getAccessibleAt(int row, int column) {
// TIGER - 4715503
TableColumn aColumn = headerModel.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
renderer = header.getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(
header.getTable(),
aColumn.getHeaderValue(), false, false,
-1, column);
return new AccessibleJTableHeaderCell(row, column,
JTable.this.getTableHeader(),
component);
}
/** {@collect.stats}
* Returns the number of rows occupied by the Accessible at
* a specified row and column in the table.
*
* @return the number of rows occupied by the Accessible at a
* given specified (row, column)
*/
public int getAccessibleRowExtentAt(int r, int c) { return 1; }
/** {@collect.stats}
* Returns the number of columns occupied by the Accessible at
* a specified row and column in the table.
*
* @return the number of columns occupied by the Accessible at a
* given specified row and column
*/
public int getAccessibleColumnExtentAt(int r, int c) { return 1; }
/** {@collect.stats}
* Returns the row headers as an AccessibleTable.
*
* @return an AccessibleTable representing the row
* headers
*/
public AccessibleTable getAccessibleRowHeader() { return null; }
/** {@collect.stats}
* Sets the row headers.
*
* @param table an AccessibleTable representing the
* row headers
*/
public void setAccessibleRowHeader(AccessibleTable table) {}
/** {@collect.stats}
* Returns the column headers as an AccessibleTable.
*
* @return an AccessibleTable representing the column
* headers
*/
public AccessibleTable getAccessibleColumnHeader() { return null; }
/** {@collect.stats}
* Sets the column headers.
*
* @param table an AccessibleTable representing the
* column headers
* @since 1.3
*/
public void setAccessibleColumnHeader(AccessibleTable table) {}
/** {@collect.stats}
* Returns the description of the specified row in the table.
*
* @param r zero-based row of the table
* @return the description of the row
* @since 1.3
*/
public Accessible getAccessibleRowDescription(int r) { return null; }
/** {@collect.stats}
* Sets the description text of the specified row of the table.
*
* @param r zero-based row of the table
* @param a the description of the row
* @since 1.3
*/
public void setAccessibleRowDescription(int r, Accessible a) {}
/** {@collect.stats}
* Returns the description text of the specified column in the table.
*
* @param c zero-based column of the table
* @return the text description of the column
* @since 1.3
*/
public Accessible getAccessibleColumnDescription(int c) { return null; }
/** {@collect.stats}
* Sets the description text of the specified column in the table.
*
* @param c zero-based column of the table
* @param a the text description of the column
* @since 1.3
*/
public void setAccessibleColumnDescription(int c, Accessible a) {}
/** {@collect.stats}
* Returns a boolean value indicating whether the accessible at
* a specified row and column is selected.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the boolean value true if the accessible at the
* row and column is selected. Otherwise, the boolean value
* false
* @since 1.3
*/
public boolean isAccessibleSelected(int r, int c) { return false; }
/** {@collect.stats}
* Returns a boolean value indicating whether the specified row
* is selected.
*
* @param r zero-based row of the table
* @return the boolean value true if the specified row is selected.
* Otherwise, false.
* @since 1.3
*/
public boolean isAccessibleRowSelected(int r) { return false; }
/** {@collect.stats}
* Returns a boolean value indicating whether the specified column
* is selected.
*
* @param r zero-based column of the table
* @return the boolean value true if the specified column is selected.
* Otherwise, false.
* @since 1.3
*/
public boolean isAccessibleColumnSelected(int c) { return false; }
/** {@collect.stats}
* Returns the selected rows in a table.
*
* @return an array of selected rows where each element is a
* zero-based row of the table
* @since 1.3
*/
public int [] getSelectedAccessibleRows() { return new int[0]; }
/** {@collect.stats}
* Returns the selected columns in a table.
*
* @return an array of selected columns where each element is a
* zero-based column of the table
* @since 1.3
*/
public int [] getSelectedAccessibleColumns() { return new int[0]; }
}
/** {@collect.stats}
* Sets the column headers as an <code>AccessibleTable</code>.
*
* @param a an <code>AccessibleTable</code> representing the
* column headers
* @since 1.3
*/
public void setAccessibleColumnHeader(AccessibleTable a) {
// XXX not implemented
}
/** {@collect.stats}
* Returns the description of the specified row in the table.
*
* @param r zero-based row of the table
* @return the description of the row
* @since 1.3
*/
public Accessible getAccessibleRowDescription(int r) {
if (r < 0 || r >= getAccessibleRowCount()) {
throw new IllegalArgumentException(new Integer(r).toString());
}
if (rowDescription == null) {
return null;
} else {
return rowDescription[r];
}
}
/** {@collect.stats}
* Sets the description text of the specified row of the table.
*
* @param r zero-based row of the table
* @param a the description of the row
* @since 1.3
*/
public void setAccessibleRowDescription(int r, Accessible a) {
if (r < 0 || r >= getAccessibleRowCount()) {
throw new IllegalArgumentException(new Integer(r).toString());
}
if (rowDescription == null) {
int numRows = getAccessibleRowCount();
rowDescription = new Accessible[numRows];
}
rowDescription[r] = a;
}
/** {@collect.stats}
* Returns the description of the specified column in the table.
*
* @param c zero-based column of the table
* @return the description of the column
* @since 1.3
*/
public Accessible getAccessibleColumnDescription(int c) {
if (c < 0 || c >= getAccessibleColumnCount()) {
throw new IllegalArgumentException(new Integer(c).toString());
}
if (columnDescription == null) {
return null;
} else {
return columnDescription[c];
}
}
/** {@collect.stats}
* Sets the description text of the specified column of the table.
*
* @param c zero-based column of the table
* @param a the description of the column
* @since 1.3
*/
public void setAccessibleColumnDescription(int c, Accessible a) {
if (c < 0 || c >= getAccessibleColumnCount()) {
throw new IllegalArgumentException(new Integer(c).toString());
}
if (columnDescription == null) {
int numColumns = getAccessibleColumnCount();
columnDescription = new Accessible[numColumns];
}
columnDescription[c] = a;
}
/** {@collect.stats}
* Returns a boolean value indicating whether the accessible at a
* given (row, column) is selected.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the boolean value true if the accessible at (row, column)
* is selected; otherwise, the boolean value false
* @since 1.3
*/
public boolean isAccessibleSelected(int r, int c) {
return JTable.this.isCellSelected(r, c);
}
/** {@collect.stats}
* Returns a boolean value indicating whether the specified row
* is selected.
*
* @param r zero-based row of the table
* @return the boolean value true if the specified row is selected;
* otherwise, false
* @since 1.3
*/
public boolean isAccessibleRowSelected(int r) {
return JTable.this.isRowSelected(r);
}
/** {@collect.stats}
* Returns a boolean value indicating whether the specified column
* is selected.
*
* @param c zero-based column of the table
* @return the boolean value true if the specified column is selected;
* otherwise, false
* @since 1.3
*/
public boolean isAccessibleColumnSelected(int c) {
return JTable.this.isColumnSelected(c);
}
/** {@collect.stats}
* Returns the selected rows in a table.
*
* @return an array of selected rows where each element is a
* zero-based row of the table
* @since 1.3
*/
public int [] getSelectedAccessibleRows() {
return JTable.this.getSelectedRows();
}
/** {@collect.stats}
* Returns the selected columns in a table.
*
* @return an array of selected columns where each element is a
* zero-based column of the table
* @since 1.3
*/
public int [] getSelectedAccessibleColumns() {
return JTable.this.getSelectedColumns();
}
/** {@collect.stats}
* Returns the row at a given index into the table.
*
* @param i zero-based index into the table
* @return the row at a given index
* @since 1.3
*/
public int getAccessibleRowAtIndex(int i) {
int columnCount = getAccessibleColumnCount();
if (columnCount == 0) {
return -1;
} else {
return (i / columnCount);
}
}
/** {@collect.stats}
* Returns the column at a given index into the table.
*
* @param i zero-based index into the table
* @return the column at a given index
* @since 1.3
*/
public int getAccessibleColumnAtIndex(int i) {
int columnCount = getAccessibleColumnCount();
if (columnCount == 0) {
return -1;
} else {
return (i % columnCount);
}
}
/** {@collect.stats}
* Returns the index at a given (row, column) in the table.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the index into the table
* @since 1.3
*/
public int getAccessibleIndexAt(int r, int c) {
return ((r * getAccessibleColumnCount()) + c);
}
// end of AccessibleTable implementation --------------------
/** {@collect.stats}
* The class provides an implementation of the Java Accessibility
* API appropriate to table cells.
*/
protected class AccessibleJTableCell extends AccessibleContext
implements Accessible, AccessibleComponent {
private JTable parent;
private int row;
private int column;
private int index;
/** {@collect.stats}
* Constructs an <code>AccessibleJTableHeaderEntry</code>.
* @since 1.4
*/
public AccessibleJTableCell(JTable t, int r, int c, int i) {
parent = t;
row = r;
column = c;
index = i;
this.setAccessibleParent(parent);
}
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* component. In the implementation of the Java Accessibility
* API for this class, return this object, which is its own
* <code>AccessibleContext</code>.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
/** {@collect.stats}
* Gets the AccessibleContext for the table cell renderer.
*
* @return the <code>AccessibleContext</code> for the table
* cell renderer if one exists;
* otherwise, returns <code>null</code>.
* @since 1.6
*/
protected AccessibleContext getCurrentAccessibleContext() {
TableColumn aColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = aColumn.getCellRenderer();
if (renderer == null) {
Class<?> columnClass = getColumnClass(column);
renderer = getDefaultRenderer(columnClass);
}
Component component = renderer.getTableCellRendererComponent(
JTable.this, getValueAt(row, column),
false, false, row, column);
if (component instanceof Accessible) {
return ((Accessible) component).getAccessibleContext();
} else {
return null;
}
}
/** {@collect.stats}
* Gets the table cell renderer component.
*
* @return the table cell renderer component if one exists;
* otherwise, returns <code>null</code>.
* @since 1.6
*/
protected Component getCurrentComponent() {
TableColumn aColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = aColumn.getCellRenderer();
if (renderer == null) {
Class<?> columnClass = getColumnClass(column);
renderer = getDefaultRenderer(columnClass);
}
return renderer.getTableCellRendererComponent(
JTable.this, null, false, false,
row, column);
}
// AccessibleContext methods
/** {@collect.stats}
* Gets the accessible name of this object.
*
* @return the localized name of the object; <code>null</code>
* if this object does not have a name
*/
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
String name = ac.getAccessibleName();
if ((name != null) && (name != "")) {
// return the cell renderer's AccessibleName
return name;
}
}
if ((accessibleName != null) && (accessibleName != "")) {
return accessibleName;
} else {
// fall back to the client property
return (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
}
/** {@collect.stats}
* Sets the localized accessible name of this object.
*
* @param s the new localized name of the object
*/
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
} else {
super.setAccessibleName(s);
}
}
//
// *** should check toolTip text for desc. (needs MouseEvent)
//
/** {@collect.stats}
* Gets the accessible description of this object.
*
* @return the localized description of the object;
* <code>null</code> if this object does not have
* a description
*/
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return super.getAccessibleDescription();
}
}
/** {@collect.stats}
* Sets the accessible description of this object.
*
* @param s the new localized description of the object
*/
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
} else {
super.setAccessibleDescription(s);
}
}
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of <code>AccessibleRole</code>
* describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return AccessibleRole.UNKNOWN;
}
}
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of <code>AccessibleStateSet</code>
* containing the current state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet as = null;
if (ac != null) {
as = ac.getAccessibleStateSet();
}
if (as == null) {
as = new AccessibleStateSet();
}
Rectangle rjt = JTable.this.getVisibleRect();
Rectangle rcell = JTable.this.getCellRect(row, column, false);
if (rjt.intersects(rcell)) {
as.add(AccessibleState.SHOWING);
} else {
if (as.contains(AccessibleState.SHOWING)) {
as.remove(AccessibleState.SHOWING);
}
}
if (parent.isCellSelected(row, column)) {
as.add(AccessibleState.SELECTED);
} else if (as.contains(AccessibleState.SELECTED)) {
as.remove(AccessibleState.SELECTED);
}
if ((row == getSelectedRow()) && (column == getSelectedColumn())) {
as.add(AccessibleState.ACTIVE);
}
as.add(AccessibleState.TRANSIENT);
return as;
}
/** {@collect.stats}
* Gets the <code>Accessible</code> parent of this object.
*
* @return the Accessible parent of this object;
* <code>null</code> if this object does not
* have an <code>Accessible</code> parent
*/
public Accessible getAccessibleParent() {
return parent;
}
/** {@collect.stats}
* Gets the index of this object in its accessible parent.
*
* @return the index of this object in its parent; -1 if this
* object does not have an accessible parent
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
return index;
}
/** {@collect.stats}
* Returns the number of accessible children in the object.
*
* @return the number of accessible children in the object
*/
public int getAccessibleChildrenCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
} else {
return 0;
}
}
/** {@collect.stats}
* Returns the specified <code>Accessible</code> child of the
* object.
*
* @param i zero-based index of child
* @return the <code>Accessible</code> child of the object
*/
public Accessible getAccessibleChild(int i) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
Accessible accessibleChild = ac.getAccessibleChild(i);
ac.setAccessibleParent(this);
return accessibleChild;
} else {
return null;
}
}
/** {@collect.stats}
* Gets the locale of the component. If the component
* does not have a locale, then the locale of its parent
* is returned.
*
* @return this component's locale; if this component does
* not have a locale, the locale of its parent is returned
* @exception IllegalComponentStateException if the
* <code>Component</code> does not have its own locale
* and has not yet been added to a containment hierarchy
* such that the locale can be determined from the
* containing parent
* @see #setLocale
*/
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return null;
}
}
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
*
* @param l the <code>PropertyChangeListener</code>
* to be added
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
} else {
super.addPropertyChangeListener(l);
}
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the
* listener list. This removes a <code>PropertyChangeListener</code>
* that was registered for all properties.
*
* @param l the <code>PropertyChangeListener</code>
* to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
} else {
super.removePropertyChangeListener(l);
}
}
/** {@collect.stats}
* Gets the <code>AccessibleAction</code> associated with this
* object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleAction</code>, or <code>null</code>
*/
public AccessibleAction getAccessibleAction() {
return getCurrentAccessibleContext().getAccessibleAction();
}
/** {@collect.stats}
* Gets the <code>AccessibleComponent</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleComponent</code>, or
* <code>null</code>
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
/** {@collect.stats}
* Gets the <code>AccessibleSelection</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleSelection</code>, or
* <code>null</code>
*/
public AccessibleSelection getAccessibleSelection() {
return getCurrentAccessibleContext().getAccessibleSelection();
}
/** {@collect.stats}
* Gets the <code>AccessibleText</code> associated with this
* object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleText</code>, or <code>null</code>
*/
public AccessibleText getAccessibleText() {
return getCurrentAccessibleContext().getAccessibleText();
}
/** {@collect.stats}
* Gets the <code>AccessibleValue</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleValue</code>, or <code>null</code>
*/
public AccessibleValue getAccessibleValue() {
return getCurrentAccessibleContext().getAccessibleValue();
}
// AccessibleComponent methods
/** {@collect.stats}
* Gets the background color of this object.
*
* @return the background color, if supported, of the object;
* otherwise, <code>null</code>
*/
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the background color of this object.
*
* @param c the new <code>Color</code> for the background
*/
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
/** {@collect.stats}
* Gets the foreground color of this object.
*
* @return the foreground color, if supported, of the object;
* otherwise, <code>null</code>
*/
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the foreground color of this object.
*
* @param c the new <code>Color</code> for the foreground
*/
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
/** {@collect.stats}
* Gets the <code>Cursor</code> of this object.
*
* @return the <code>Cursor</code>, if supported,
* of the object; otherwise, <code>null</code>
*/
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
/** {@collect.stats}
* Sets the <code>Cursor</code> of this object.
*
* @param c the new <code>Cursor</code> for the object
*/
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
/** {@collect.stats}
* Gets the <code>Font</code> of this object.
*
* @return the <code>Font</code>,if supported,
* for the object; otherwise, <code>null</code>
*/
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the <code>Font</code> of this object.
*
* @param f the new <code>Font</code> for the object
*/
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
/** {@collect.stats}
* Gets the <code>FontMetrics</code> of this object.
*
* @param f the <code>Font</code>
* @return the <code>FontMetrics</code> object, if supported;
* otherwise <code>null</code>
* @see #getFont
*/
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
/** {@collect.stats}
* Determines if the object is enabled.
*
* @return true if object is enabled; otherwise, false
*/
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
/** {@collect.stats}
* Sets the enabled state of the object.
*
* @param b if true, enables this object; otherwise, disables it
*/
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
/** {@collect.stats}
* Determines if this object is visible. Note: this means that the
* object intends to be visible; however, it may not in fact be
* showing on the screen because one of the objects that this object
* is contained by is not visible. To determine if an object is
* showing on the screen, use <code>isShowing</code>.
*
* @return true if object is visible; otherwise, false
*/
public boolean isVisible() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isVisible();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isVisible();
} else {
return false;
}
}
}
/** {@collect.stats}
* Sets the visible state of the object.
*
* @param b if true, shows this object; otherwise, hides it
*/
public void setVisible(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setVisible(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setVisible(b);
}
}
}
/** {@collect.stats}
* Determines if the object is showing. This is determined
* by checking the visibility of the object and ancestors
* of the object. Note: this will return true even if the
* object is obscured by another (for example,
* it happens to be underneath a menu that was pulled down).
*
* @return true if the object is showing; otherwise, false
*/
public boolean isShowing() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
if (ac.getAccessibleParent() != null) {
return ((AccessibleComponent) ac).isShowing();
} else {
// Fixes 4529616 - AccessibleJTableCell.isShowing()
// returns false when the cell on the screen
// if no parent
return isVisible();
}
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isShowing();
} else {
return false;
}
}
}
/** {@collect.stats}
* Checks whether the specified point is within this
* object's bounds, where the point's x and y coordinates
* are defined to be relative to the coordinate system of
* the object.
*
* @param p the <code>Point</code> relative to the
* coordinate system of the object
* @return true if object contains <code>Point</code>;
* otherwise false
*/
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
/** {@collect.stats}
* Returns the location of the object on the screen.
*
* @return location of object on screen -- can be
* <code>null</code> if this object is not on the screen
*/
public Point getLocationOnScreen() {
if (parent != null) {
Point parentLocation = parent.getLocationOnScreen();
Point componentLocation = getLocation();
componentLocation.translate(parentLocation.x, parentLocation.y);
return componentLocation;
} else {
return null;
}
}
/** {@collect.stats}
* Gets the location of the object relative to the parent
* in the form of a point specifying the object's
* top-left corner in the screen's coordinate space.
*
* @return an instance of <code>Point</code> representing
* the top-left corner of the object's bounds in the
* coordinate space of the screen; <code>null</code> if
* this object or its parent are not on the screen
*/
public Point getLocation() {
if (parent != null) {
Rectangle r = parent.getCellRect(row, column, false);
if (r != null) {
return r.getLocation();
}
}
return null;
}
/** {@collect.stats}
* Sets the location of the object relative to the parent.
*/
public void setLocation(Point p) {
// if ((parent != null) && (parent.contains(p))) {
// ensureIndexIsVisible(indexInParent);
// }
}
public Rectangle getBounds() {
if (parent != null) {
return parent.getCellRect(row, column, false);
} else {
return null;
}
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
public Dimension getSize() {
if (parent != null) {
Rectangle r = parent.getCellRect(row, column, false);
if (r != null) {
return r.getSize();
}
}
return null;
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
} // inner class AccessibleJTableCell
// Begin AccessibleJTableHeader ========== // TIGER - 4715503
/** {@collect.stats}
* This class implements accessibility for JTable header cells.
*/
private class AccessibleJTableHeaderCell extends AccessibleContext
implements Accessible, AccessibleComponent {
private int row;
private int column;
private JTableHeader parent;
private Component rendererComponent;
/** {@collect.stats}
* Constructs an <code>AccessibleJTableHeaderEntry</code> instance.
*
* @param row header cell row index
* @param column header cell column index
* @param parent header cell parent
* @param rendererComponent component that renders the header cell
*/
public AccessibleJTableHeaderCell(int row, int column,
JTableHeader parent,
Component rendererComponent) {
this.row = row;
this.column = column;
this.parent = parent;
this.rendererComponent = rendererComponent;
this.setAccessibleParent(parent);
}
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* component. In the implementation of the Java Accessibility
* API for this class, return this object, which is its own
* <code>AccessibleContext</code>.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
/*
* Returns the AccessibleContext for the header cell
* renderer.
*/
private AccessibleContext getCurrentAccessibleContext() {
return rendererComponent.getAccessibleContext();
}
/*
* Returns the component that renders the header cell.
*/
private Component getCurrentComponent() {
return rendererComponent;
}
// AccessibleContext methods ==========
/** {@collect.stats}
* Gets the accessible name of this object.
*
* @return the localized name of the object; <code>null</code>
* if this object does not have a name
*/
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
String name = ac.getAccessibleName();
if ((name != null) && (name != "")) {
return ac.getAccessibleName();
}
}
if ((accessibleName != null) && (accessibleName != "")) {
return accessibleName;
} else {
return null;
}
}
/** {@collect.stats}
* Sets the localized accessible name of this object.
*
* @param s the new localized name of the object
*/
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
} else {
super.setAccessibleName(s);
}
}
/** {@collect.stats}
* Gets the accessible description of this object.
*
* @return the localized description of the object;
* <code>null</code> if this object does not have
* a description
*/
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return super.getAccessibleDescription();
}
}
/** {@collect.stats}
* Sets the accessible description of this object.
*
* @param s the new localized description of the object
*/
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
} else {
super.setAccessibleDescription(s);
}
}
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of <code>AccessibleRole</code>
* describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return AccessibleRole.UNKNOWN;
}
}
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of <code>AccessibleStateSet</code>
* containing the current state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet as = null;
if (ac != null) {
as = ac.getAccessibleStateSet();
}
if (as == null) {
as = new AccessibleStateSet();
}
Rectangle rjt = JTable.this.getVisibleRect();
Rectangle rcell = JTable.this.getCellRect(row, column, false);
if (rjt.intersects(rcell)) {
as.add(AccessibleState.SHOWING);
} else {
if (as.contains(AccessibleState.SHOWING)) {
as.remove(AccessibleState.SHOWING);
}
}
if (JTable.this.isCellSelected(row, column)) {
as.add(AccessibleState.SELECTED);
} else if (as.contains(AccessibleState.SELECTED)) {
as.remove(AccessibleState.SELECTED);
}
if ((row == getSelectedRow()) && (column == getSelectedColumn())) {
as.add(AccessibleState.ACTIVE);
}
as.add(AccessibleState.TRANSIENT);
return as;
}
/** {@collect.stats}
* Gets the <code>Accessible</code> parent of this object.
*
* @return the Accessible parent of this object;
* <code>null</code> if this object does not
* have an <code>Accessible</code> parent
*/
public Accessible getAccessibleParent() {
return parent;
}
/** {@collect.stats}
* Gets the index of this object in its accessible parent.
*
* @return the index of this object in its parent; -1 if this
* object does not have an accessible parent
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
return column;
}
/** {@collect.stats}
* Returns the number of accessible children in the object.
*
* @return the number of accessible children in the object
*/
public int getAccessibleChildrenCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
} else {
return 0;
}
}
/** {@collect.stats}
* Returns the specified <code>Accessible</code> child of the
* object.
*
* @param i zero-based index of child
* @return the <code>Accessible</code> child of the object
*/
public Accessible getAccessibleChild(int i) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
Accessible accessibleChild = ac.getAccessibleChild(i);
ac.setAccessibleParent(this);
return accessibleChild;
} else {
return null;
}
}
/** {@collect.stats}
* Gets the locale of the component. If the component
* does not have a locale, then the locale of its parent
* is returned.
*
* @return this component's locale; if this component does
* not have a locale, the locale of its parent is returned
* @exception IllegalComponentStateException if the
* <code>Component</code> does not have its own locale
* and has not yet been added to a containment hierarchy
* such that the locale can be determined from the
* containing parent
* @see #setLocale
*/
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return null;
}
}
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
*
* @param l the <code>PropertyChangeListener</code>
* to be added
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
} else {
super.addPropertyChangeListener(l);
}
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the
* listener list. This removes a <code>PropertyChangeListener</code>
* that was registered for all properties.
*
* @param l the <code>PropertyChangeListener</code>
* to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
} else {
super.removePropertyChangeListener(l);
}
}
/** {@collect.stats}
* Gets the <code>AccessibleAction</code> associated with this
* object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleAction</code>, or <code>null</code>
*/
public AccessibleAction getAccessibleAction() {
return getCurrentAccessibleContext().getAccessibleAction();
}
/** {@collect.stats}
* Gets the <code>AccessibleComponent</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleComponent</code>, or
* <code>null</code>
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
/** {@collect.stats}
* Gets the <code>AccessibleSelection</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleSelection</code>, or
* <code>null</code>
*/
public AccessibleSelection getAccessibleSelection() {
return getCurrentAccessibleContext().getAccessibleSelection();
}
/** {@collect.stats}
* Gets the <code>AccessibleText</code> associated with this
* object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleText</code>, or <code>null</code>
*/
public AccessibleText getAccessibleText() {
return getCurrentAccessibleContext().getAccessibleText();
}
/** {@collect.stats}
* Gets the <code>AccessibleValue</code> associated with
* this object if one exists. Otherwise returns <code>null</code>.
*
* @return the <code>AccessibleValue</code>, or <code>null</code>
*/
public AccessibleValue getAccessibleValue() {
return getCurrentAccessibleContext().getAccessibleValue();
}
// AccessibleComponent methods ==========
/** {@collect.stats}
* Gets the background color of this object.
*
* @return the background color, if supported, of the object;
* otherwise, <code>null</code>
*/
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the background color of this object.
*
* @param c the new <code>Color</code> for the background
*/
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
/** {@collect.stats}
* Gets the foreground color of this object.
*
* @return the foreground color, if supported, of the object;
* otherwise, <code>null</code>
*/
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the foreground color of this object.
*
* @param c the new <code>Color</code> for the foreground
*/
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
/** {@collect.stats}
* Gets the <code>Cursor</code> of this object.
*
* @return the <code>Cursor</code>, if supported,
* of the object; otherwise, <code>null</code>
*/
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
/** {@collect.stats}
* Sets the <code>Cursor</code> of this object.
*
* @param c the new <code>Cursor</code> for the object
*/
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
/** {@collect.stats}
* Gets the <code>Font</code> of this object.
*
* @return the <code>Font</code>,if supported,
* for the object; otherwise, <code>null</code>
*/
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the <code>Font</code> of this object.
*
* @param f the new <code>Font</code> for the object
*/
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
/** {@collect.stats}
* Gets the <code>FontMetrics</code> of this object.
*
* @param f the <code>Font</code>
* @return the <code>FontMetrics</code> object, if supported;
* otherwise <code>null</code>
* @see #getFont
*/
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
/** {@collect.stats}
* Determines if the object is enabled.
*
* @return true if object is enabled; otherwise, false
*/
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
/** {@collect.stats}
* Sets the enabled state of the object.
*
* @param b if true, enables this object; otherwise, disables it
*/
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
/** {@collect.stats}
* Determines if this object is visible. Note: this means that the
* object intends to be visible; however, it may not in fact be
* showing on the screen because one of the objects that this object
* is contained by is not visible. To determine if an object is
* showing on the screen, use <code>isShowing</code>.
*
* @return true if object is visible; otherwise, false
*/
public boolean isVisible() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isVisible();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isVisible();
} else {
return false;
}
}
}
/** {@collect.stats}
* Sets the visible state of the object.
*
* @param b if true, shows this object; otherwise, hides it
*/
public void setVisible(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setVisible(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setVisible(b);
}
}
}
/** {@collect.stats}
* Determines if the object is showing. This is determined
* by checking the visibility of the object and ancestors
* of the object. Note: this will return true even if the
* object is obscured by another (for example,
* it happens to be underneath a menu that was pulled down).
*
* @return true if the object is showing; otherwise, false
*/
public boolean isShowing() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
if (ac.getAccessibleParent() != null) {
return ((AccessibleComponent) ac).isShowing();
} else {
// Fixes 4529616 - AccessibleJTableCell.isShowing()
// returns false when the cell on the screen
// if no parent
return isVisible();
}
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isShowing();
} else {
return false;
}
}
}
/** {@collect.stats}
* Checks whether the specified point is within this
* object's bounds, where the point's x and y coordinates
* are defined to be relative to the coordinate system of
* the object.
*
* @param p the <code>Point</code> relative to the
* coordinate system of the object
* @return true if object contains <code>Point</code>;
* otherwise false
*/
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
/** {@collect.stats}
* Returns the location of the object on the screen.
*
* @return location of object on screen -- can be
* <code>null</code> if this object is not on the screen
*/
public Point getLocationOnScreen() {
if (parent != null) {
Point parentLocation = parent.getLocationOnScreen();
Point componentLocation = getLocation();
componentLocation.translate(parentLocation.x, parentLocation.y);
return componentLocation;
} else {
return null;
}
}
/** {@collect.stats}
* Gets the location of the object relative to the parent
* in the form of a point specifying the object's
* top-left corner in the screen's coordinate space.
*
* @return an instance of <code>Point</code> representing
* the top-left corner of the object's bounds in the
* coordinate space of the screen; <code>null</code> if
* this object or its parent are not on the screen
*/
public Point getLocation() {
if (parent != null) {
Rectangle r = parent.getHeaderRect(column);
if (r != null) {
return r.getLocation();
}
}
return null;
}
/** {@collect.stats}
* Sets the location of the object relative to the parent.
* @param p the new position for the top-left corner
* @see #getLocation
*/
public void setLocation(Point p) {
}
/** {@collect.stats}
* Gets the bounds of this object in the form of a Rectangle object.
* The bounds specify this object's width, height, and location
* relative to its parent.
*
* @return A rectangle indicating this component's bounds; null if
* this object is not on the screen.
* @see #contains
*/
public Rectangle getBounds() {
if (parent != null) {
return parent.getHeaderRect(column);
} else {
return null;
}
}
/** {@collect.stats}
* Sets the bounds of this object in the form of a Rectangle object.
* The bounds specify this object's width, height, and location
* relative to its parent.
*
* @param r rectangle indicating this component's bounds
* @see #getBounds
*/
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
/** {@collect.stats}
* Returns the size of this object in the form of a Dimension object.
* The height field of the Dimension object contains this object's
* height, and the width field of the Dimension object contains this
* object's width.
*
* @return A Dimension object that indicates the size of this component;
* null if this object is not on the screen
* @see #setSize
*/
public Dimension getSize() {
if (parent != null) {
Rectangle r = parent.getHeaderRect(column);
if (r != null) {
return r.getSize();
}
}
return null;
}
/** {@collect.stats}
* Resizes this object so that it has width and height.
*
* @param d The dimension specifying the new size of the object.
* @see #getSize
*/
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
/** {@collect.stats}
* Returns the Accessible child, if one exists, contained at the local
* coordinate Point.
*
* @param p The point relative to the coordinate system of this object.
* @return the Accessible, if it exists, at the specified location;
* otherwise null
*/
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
/** {@collect.stats}
* Returns whether this object can accept focus or not. Objects that
* can accept focus will also have the AccessibleState.FOCUSABLE state
* set in their AccessibleStateSets.
*
* @return true if object can accept focus; otherwise false
* @see AccessibleContext#getAccessibleStateSet
* @see AccessibleState#FOCUSABLE
* @see AccessibleState#FOCUSED
* @see AccessibleStateSet
*/
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
/** {@collect.stats}
* Requests focus for this object. If this object cannot accept focus,
* nothing will happen. Otherwise, the object will attempt to take
* focus.
* @see #isFocusTraversable
*/
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
/** {@collect.stats}
* Adds the specified focus listener to receive focus events from this
* component.
*
* @param l the focus listener
* @see #removeFocusListener
*/
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
/** {@collect.stats}
* Removes the specified focus listener so it no longer receives focus
* events from this component.
*
* @param l the focus listener
* @see #addFocusListener
*/
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
} // inner class AccessibleJTableHeaderCell
} // inner class AccessibleJTable
} // End of Class JTable
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.text.*;
import java.awt.geom.*;
import java.beans.*;
import java.util.Enumeration;
import java.util.Vector;
import java.io.Serializable;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.plaf.basic.*;
import java.util.*;
/** {@collect.stats}
* Defines common behaviors for buttons and menu items.
* <p>
* Buttons can be configured, and to some degree controlled, by
* <code><a href="Action.html">Action</a></code>s. Using an
* <code>Action</code> with a button has many benefits beyond directly
* configuring a button. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details, and you can find more information in <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html">How
* to Use Actions</a>, a section in <em>The Java Tutorial</em>.
* <p>
* For further information see
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html">How to Use Buttons, Check Boxes, and Radio Buttons</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Jeff Dinkins
*/
public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants {
// *********************************
// ******* Button properties *******
// *********************************
/** {@collect.stats} Identifies a change in the button model. */
public static final String MODEL_CHANGED_PROPERTY = "model";
/** {@collect.stats} Identifies a change in the button's text. */
public static final String TEXT_CHANGED_PROPERTY = "text";
/** {@collect.stats} Identifies a change to the button's mnemonic. */
public static final String MNEMONIC_CHANGED_PROPERTY = "mnemonic";
// Text positioning and alignment
/** {@collect.stats} Identifies a change in the button's margins. */
public static final String MARGIN_CHANGED_PROPERTY = "margin";
/** {@collect.stats} Identifies a change in the button's vertical alignment. */
public static final String VERTICAL_ALIGNMENT_CHANGED_PROPERTY = "verticalAlignment";
/** {@collect.stats} Identifies a change in the button's horizontal alignment. */
public static final String HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY = "horizontalAlignment";
/** {@collect.stats} Identifies a change in the button's vertical text position. */
public static final String VERTICAL_TEXT_POSITION_CHANGED_PROPERTY = "verticalTextPosition";
/** {@collect.stats} Identifies a change in the button's horizontal text position. */
public static final String HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY = "horizontalTextPosition";
// Paint options
/** {@collect.stats}
* Identifies a change to having the border drawn,
* or having it not drawn.
*/
public static final String BORDER_PAINTED_CHANGED_PROPERTY = "borderPainted";
/** {@collect.stats}
* Identifies a change to having the border highlighted when focused,
* or not.
*/
public static final String FOCUS_PAINTED_CHANGED_PROPERTY = "focusPainted";
/** {@collect.stats}
* Identifies a change from rollover enabled to disabled or back
* to enabled.
*/
public static final String ROLLOVER_ENABLED_CHANGED_PROPERTY = "rolloverEnabled";
/** {@collect.stats}
* Identifies a change to having the button paint the content area.
*/
public static final String CONTENT_AREA_FILLED_CHANGED_PROPERTY = "contentAreaFilled";
// Icons
/** {@collect.stats} Identifies a change to the icon that represents the button. */
public static final String ICON_CHANGED_PROPERTY = "icon";
/** {@collect.stats}
* Identifies a change to the icon used when the button has been
* pressed.
*/
public static final String PRESSED_ICON_CHANGED_PROPERTY = "pressedIcon";
/** {@collect.stats}
* Identifies a change to the icon used when the button has
* been selected.
*/
public static final String SELECTED_ICON_CHANGED_PROPERTY = "selectedIcon";
/** {@collect.stats}
* Identifies a change to the icon used when the cursor is over
* the button.
*/
public static final String ROLLOVER_ICON_CHANGED_PROPERTY = "rolloverIcon";
/** {@collect.stats}
* Identifies a change to the icon used when the cursor is
* over the button and it has been selected.
*/
public static final String ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY = "rolloverSelectedIcon";
/** {@collect.stats}
* Identifies a change to the icon used when the button has
* been disabled.
*/
public static final String DISABLED_ICON_CHANGED_PROPERTY = "disabledIcon";
/** {@collect.stats}
* Identifies a change to the icon used when the button has been
* disabled and selected.
*/
public static final String DISABLED_SELECTED_ICON_CHANGED_PROPERTY = "disabledSelectedIcon";
/** {@collect.stats} The data model that determines the button's state. */
protected ButtonModel model = null;
private String text = ""; // for BeanBox
private Insets margin = null;
private Insets defaultMargin = null;
// Button icons
// PENDING(jeff) - hold icons in an array
private Icon defaultIcon = null;
private Icon pressedIcon = null;
private Icon disabledIcon = null;
private Icon selectedIcon = null;
private Icon disabledSelectedIcon = null;
private Icon rolloverIcon = null;
private Icon rolloverSelectedIcon = null;
// Display properties
private boolean paintBorder = true;
private boolean paintFocus = true;
private boolean rolloverEnabled = false;
private boolean contentAreaFilled = true;
// Icon/Label Alignment
private int verticalAlignment = CENTER;
private int horizontalAlignment = CENTER;
private int verticalTextPosition = CENTER;
private int horizontalTextPosition = TRAILING;
private int iconTextGap = 4;
private int mnemonic;
private int mnemonicIndex = -1;
private long multiClickThreshhold = 0;
private boolean borderPaintedSet = false;
private boolean rolloverEnabledSet = false;
private boolean iconTextGapSet = false;
private boolean contentAreaFilledSet = false;
// Whether or not we've set the LayoutManager.
private boolean setLayout = false;
// This is only used by JButton, promoted to avoid an extra
// boolean field in JButton
boolean defaultCapable = true;
/** {@collect.stats}
* Combined listeners: ActionListener, ChangeListener, ItemListener.
*/
private Handler handler;
/** {@collect.stats}
* The button model's <code>changeListener</code>.
*/
protected ChangeListener changeListener = null;
/** {@collect.stats}
* The button model's <code>ActionListener</code>.
*/
protected ActionListener actionListener = null;
/** {@collect.stats}
* The button model's <code>ItemListener</code>.
*/
protected ItemListener itemListener = null;
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per button
* instance since the
* event's only state is the source property. The source of events
* generated is always "this".
*/
protected transient ChangeEvent changeEvent;
private boolean hideActionText = false;
/** {@collect.stats}
* Sets the <code>hideActionText</code> property, which determines
* whether the button displays text from the <code>Action</code>.
* This is useful only if an <code>Action</code> has been
* installed on the button.
*
* @param hideActionText <code>true</code> if the button's
* <code>text</code> property should not reflect
* that of the <code>Action</code>; the default is
* <code>false</code>
* @see <a href="Action.html#buttonActions">Swing Components Supporting
* <code>Action</code></a>
* @since 1.6
* @beaninfo
* bound: true
* expert: true
* description: Whether the text of the button should come from
* the <code>Action</code>.
*/
public void setHideActionText(boolean hideActionText) {
if (hideActionText != this.hideActionText) {
this.hideActionText = hideActionText;
if (getAction() != null) {
setTextFromAction(getAction(), false);
}
firePropertyChange("hideActionText", !hideActionText,
hideActionText);
}
}
/** {@collect.stats}
* Returns the value of the <code>hideActionText</code> property, which
* determines whether the button displays text from the
* <code>Action</code>. This is useful only if an <code>Action</code>
* has been installed on the button.
*
* @return <code>true</code> if the button's <code>text</code>
* property should not reflect that of the
* <code>Action</code>; the default is <code>false</code>
* @since 1.6
*/
public boolean getHideActionText() {
return hideActionText;
}
/** {@collect.stats}
* Returns the button's text.
* @return the buttons text
* @see #setText
*/
public String getText() {
return text;
}
/** {@collect.stats}
* Sets the button's text.
* @param text the string used to set the text
* @see #getText
* @beaninfo
* bound: true
* preferred: true
* attribute: visualUpdate true
* description: The button's text.
*/
public void setText(String text) {
String oldValue = this.text;
this.text = text;
firePropertyChange(TEXT_CHANGED_PROPERTY, oldValue, text);
updateDisplayedMnemonicIndex(text, getMnemonic());
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, text);
}
if (text == null || oldValue == null || !text.equals(oldValue)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the state of the button. True if the
* toggle button is selected, false if it's not.
* @return true if the toggle button is selected, otherwise false
*/
public boolean isSelected() {
return model.isSelected();
}
/** {@collect.stats}
* Sets the state of the button. Note that this method does not
* trigger an <code>actionEvent</code>.
* Call <code>doClick</code> to perform a programatic action change.
*
* @param b true if the button is selected, otherwise false
*/
public void setSelected(boolean b) {
boolean oldValue = isSelected();
// TIGER - 4840653
// Removed code which fired an AccessibleState.SELECTED
// PropertyChangeEvent since this resulted in two
// identical events being fired since
// AbstractButton.fireItemStateChanged also fires the
// same event. This caused screen readers to speak the
// name of the item twice.
model.setSelected(b);
}
/** {@collect.stats}
* Programmatically perform a "click". This does the same
* thing as if the user had pressed and released the button.
*/
public void doClick() {
doClick(68);
}
/** {@collect.stats}
* Programmatically perform a "click". This does the same
* thing as if the user had pressed and released the button.
* The button stays visually "pressed" for <code>pressTime</code>
* milliseconds.
*
* @param pressTime the time to "hold down" the button, in milliseconds
*/
public void doClick(int pressTime) {
Dimension size = getSize();
model.setArmed(true);
model.setPressed(true);
paintImmediately(new Rectangle(0,0, size.width, size.height));
try {
Thread.currentThread().sleep(pressTime);
} catch(InterruptedException ie) {
}
model.setPressed(false);
model.setArmed(false);
}
/** {@collect.stats}
* Sets space for margin between the button's border and
* the label. Setting to <code>null</code> will cause the button to
* use the default margin. The button's default <code>Border</code>
* object will use this value to create the proper margin.
* However, if a non-default border is set on the button,
* it is that <code>Border</code> object's responsibility to create the
* appropriate margin space (else this property will
* effectively be ignored).
*
* @param m the space between the border and the label
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The space between the button's border and the label.
*/
public void setMargin(Insets m) {
// Cache the old margin if it comes from the UI
if(m instanceof UIResource) {
defaultMargin = m;
} else if(margin instanceof UIResource) {
defaultMargin = margin;
}
// If the client passes in a null insets, restore the margin
// from the UI if possible
if(m == null && defaultMargin != null) {
m = defaultMargin;
}
Insets old = margin;
margin = m;
firePropertyChange(MARGIN_CHANGED_PROPERTY, old, m);
if (old == null || !old.equals(m)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the margin between the button's border and
* the label.
*
* @return an <code>Insets</code> object specifying the margin
* between the botton's border and the label
* @see #setMargin
*/
public Insets getMargin() {
return (margin == null) ? null : (Insets) margin.clone();
}
/** {@collect.stats}
* Returns the default icon.
* @return the default <code>Icon</code>
* @see #setIcon
*/
public Icon getIcon() {
return defaultIcon;
}
/** {@collect.stats}
* Sets the button's default icon. This icon is
* also used as the "pressed" and "disabled" icon if
* there is no explicitly set pressed icon.
*
* @param defaultIcon the icon used as the default image
* @see #getIcon
* @see #setPressedIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The button's default icon
*/
public void setIcon(Icon defaultIcon) {
Icon oldValue = this.defaultIcon;
this.defaultIcon = defaultIcon;
/* If the default icon has really changed and we had
* generated the disabled icon for this component,
* (i.e. setDisabledIcon() was never called) then
* clear the disabledIcon field.
*/
if (defaultIcon != oldValue && (disabledIcon instanceof UIResource)) {
disabledIcon = null;
}
firePropertyChange(ICON_CHANGED_PROPERTY, oldValue, defaultIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, defaultIcon);
}
if (defaultIcon != oldValue) {
if (defaultIcon == null || oldValue == null ||
defaultIcon.getIconWidth() != oldValue.getIconWidth() ||
defaultIcon.getIconHeight() != oldValue.getIconHeight()) {
revalidate();
}
repaint();
}
}
/** {@collect.stats}
* Returns the pressed icon for the button.
* @return the <code>pressedIcon</code> property
* @see #setPressedIcon
*/
public Icon getPressedIcon() {
return pressedIcon;
}
/** {@collect.stats}
* Sets the pressed icon for the button.
* @param pressedIcon the icon used as the "pressed" image
* @see #getPressedIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The pressed icon for the button.
*/
public void setPressedIcon(Icon pressedIcon) {
Icon oldValue = this.pressedIcon;
this.pressedIcon = pressedIcon;
firePropertyChange(PRESSED_ICON_CHANGED_PROPERTY, oldValue, pressedIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, pressedIcon);
}
if (pressedIcon != oldValue) {
if (getModel().isPressed()) {
repaint();
}
}
}
/** {@collect.stats}
* Returns the selected icon for the button.
* @return the <code>selectedIcon</code> property
* @see #setSelectedIcon
*/
public Icon getSelectedIcon() {
return selectedIcon;
}
/** {@collect.stats}
* Sets the selected icon for the button.
* @param selectedIcon the icon used as the "selected" image
* @see #getSelectedIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The selected icon for the button.
*/
public void setSelectedIcon(Icon selectedIcon) {
Icon oldValue = this.selectedIcon;
this.selectedIcon = selectedIcon;
/* If the default selected icon has really changed and we had
* generated the disabled selected icon for this component,
* (i.e. setDisabledSelectedIcon() was never called) then
* clear the disabledSelectedIcon field.
*/
if (selectedIcon != oldValue &&
disabledSelectedIcon instanceof UIResource) {
disabledSelectedIcon = null;
}
firePropertyChange(SELECTED_ICON_CHANGED_PROPERTY, oldValue, selectedIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, selectedIcon);
}
if (selectedIcon != oldValue) {
if (isSelected()) {
repaint();
}
}
}
/** {@collect.stats}
* Returns the rollover icon for the button.
* @return the <code>rolloverIcon</code> property
* @see #setRolloverIcon
*/
public Icon getRolloverIcon() {
return rolloverIcon;
}
/** {@collect.stats}
* Sets the rollover icon for the button.
* @param rolloverIcon the icon used as the "rollover" image
* @see #getRolloverIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The rollover icon for the button.
*/
public void setRolloverIcon(Icon rolloverIcon) {
Icon oldValue = this.rolloverIcon;
this.rolloverIcon = rolloverIcon;
firePropertyChange(ROLLOVER_ICON_CHANGED_PROPERTY, oldValue, rolloverIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, rolloverIcon);
}
setRolloverEnabled(true);
if (rolloverIcon != oldValue) {
// No way to determine whether we are currently in
// a rollover state, so repaint regardless
repaint();
}
}
/** {@collect.stats}
* Returns the rollover selection icon for the button.
* @return the <code>rolloverSelectedIcon</code> property
* @see #setRolloverSelectedIcon
*/
public Icon getRolloverSelectedIcon() {
return rolloverSelectedIcon;
}
/** {@collect.stats}
* Sets the rollover selected icon for the button.
* @param rolloverSelectedIcon the icon used as the
* "selected rollover" image
* @see #getRolloverSelectedIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The rollover selected icon for the button.
*/
public void setRolloverSelectedIcon(Icon rolloverSelectedIcon) {
Icon oldValue = this.rolloverSelectedIcon;
this.rolloverSelectedIcon = rolloverSelectedIcon;
firePropertyChange(ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, oldValue, rolloverSelectedIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, rolloverSelectedIcon);
}
setRolloverEnabled(true);
if (rolloverSelectedIcon != oldValue) {
// No way to determine whether we are currently in
// a rollover state, so repaint regardless
if (isSelected()) {
repaint();
}
}
}
/** {@collect.stats}
* Returns the icon used by the button when it's disabled.
* If no disabled icon has been set this will forward the call to
* the look and feel to construct an appropriate disabled Icon.
* <p>
* Some look and feels might not render the disabled Icon, in which
* case they will ignore this.
*
* @return the <code>disabledIcon</code> property
* @see #getPressedIcon
* @see #setDisabledIcon
* @see javax.swing.LookAndFeel#getDisabledIcon
*/
public Icon getDisabledIcon() {
if (disabledIcon == null) {
disabledIcon = UIManager.getLookAndFeel().getDisabledIcon(this, getIcon());
if (disabledIcon != null) {
firePropertyChange(DISABLED_ICON_CHANGED_PROPERTY, null, disabledIcon);
}
}
return disabledIcon;
}
/** {@collect.stats}
* Sets the disabled icon for the button.
* @param disabledIcon the icon used as the disabled image
* @see #getDisabledIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The disabled icon for the button.
*/
public void setDisabledIcon(Icon disabledIcon) {
Icon oldValue = this.disabledIcon;
this.disabledIcon = disabledIcon;
firePropertyChange(DISABLED_ICON_CHANGED_PROPERTY, oldValue, disabledIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, disabledIcon);
}
if (disabledIcon != oldValue) {
if (!isEnabled()) {
repaint();
}
}
}
/** {@collect.stats}
* Returns the icon used by the button when it's disabled and selected.
* If no disabled selection icon has been set, this will forward
* the call to the LookAndFeel to construct an appropriate disabled
* Icon from the selection icon if it has been set and to
* <code>getDisabledIcon()</code> otherwise.
* <p>
* Some look and feels might not render the disabled selected Icon, in
* which case they will ignore this.
*
* @return the <code>disabledSelectedIcon</code> property
* @see #getDisabledIcon
* @see #setDisabledSelectedIcon
* @see javax.swing.LookAndFeel#getDisabledSelectedIcon
*/
public Icon getDisabledSelectedIcon() {
if (disabledSelectedIcon == null) {
if (selectedIcon != null) {
disabledSelectedIcon = UIManager.getLookAndFeel().
getDisabledSelectedIcon(this, getSelectedIcon());
} else {
return getDisabledIcon();
}
}
return disabledSelectedIcon;
}
/** {@collect.stats}
* Sets the disabled selection icon for the button.
* @param disabledSelectedIcon the icon used as the disabled
* selection image
* @see #getDisabledSelectedIcon
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The disabled selection icon for the button.
*/
public void setDisabledSelectedIcon(Icon disabledSelectedIcon) {
Icon oldValue = this.disabledSelectedIcon;
this.disabledSelectedIcon = disabledSelectedIcon;
firePropertyChange(DISABLED_SELECTED_ICON_CHANGED_PROPERTY, oldValue, disabledSelectedIcon);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldValue, disabledSelectedIcon);
}
if (disabledSelectedIcon != oldValue) {
if (disabledSelectedIcon == null || oldValue == null ||
disabledSelectedIcon.getIconWidth() != oldValue.getIconWidth() ||
disabledSelectedIcon.getIconHeight() != oldValue.getIconHeight()) {
revalidate();
}
if (!isEnabled() && isSelected()) {
repaint();
}
}
}
/** {@collect.stats}
* Returns the vertical alignment of the text and icon.
*
* @return the <code>verticalAlignment</code> property, one of the
* following values:
* <ul>
* <li>{@code SwingConstants.CENTER} (the default)
* <li>{@code SwingConstants.TOP}
* <li>{@code SwingConstants.BOTTOM}
* </ul>
*/
public int getVerticalAlignment() {
return verticalAlignment;
}
/** {@collect.stats}
* Sets the vertical alignment of the icon and text.
* @param alignment one of the following values:
* <ul>
* <li>{@code SwingConstants.CENTER} (the default)
* <li>{@code SwingConstants.TOP}
* <li>{@code SwingConstants.BOTTOM}
* </ul>
* @throws IllegalArgumentException if the alignment is not one of the legal
* values listed above
* @beaninfo
* bound: true
* enum: TOP SwingConstants.TOP
* CENTER SwingConstants.CENTER
* BOTTOM SwingConstants.BOTTOM
* attribute: visualUpdate true
* description: The vertical alignment of the icon and text.
*/
public void setVerticalAlignment(int alignment) {
if (alignment == verticalAlignment) return;
int oldValue = verticalAlignment;
verticalAlignment = checkVerticalKey(alignment, "verticalAlignment");
firePropertyChange(VERTICAL_ALIGNMENT_CHANGED_PROPERTY, oldValue, verticalAlignment); repaint();
}
/** {@collect.stats}
* Returns the horizontal alignment of the icon and text.
* {@code AbstractButton}'s default is {@code SwingConstants.CENTER},
* but subclasses such as {@code JCheckBox} may use a different default.
*
* @return the <code>horizontalAlignment</code> property,
* one of the following values:
* <ul>
* <li>{@code SwingConstants.RIGHT}
* <li>{@code SwingConstants.LEFT}
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.LEADING}
* <li>{@code SwingConstants.TRAILING}
* </ul>
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
/** {@collect.stats}
* Sets the horizontal alignment of the icon and text.
* {@code AbstractButton}'s default is {@code SwingConstants.CENTER},
* but subclasses such as {@code JCheckBox} may use a different default.
*
* @param alignment the alignment value, one of the following values:
* <ul>
* <li>{@code SwingConstants.RIGHT}
* <li>{@code SwingConstants.LEFT}
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.LEADING}
* <li>{@code SwingConstants.TRAILING}
* </ul>
* @throws IllegalArgumentException if the alignment is not one of the
* valid values
* @beaninfo
* bound: true
* enum: LEFT SwingConstants.LEFT
* CENTER SwingConstants.CENTER
* RIGHT SwingConstants.RIGHT
* LEADING SwingConstants.LEADING
* TRAILING SwingConstants.TRAILING
* attribute: visualUpdate true
* description: The horizontal alignment of the icon and text.
*/
public void setHorizontalAlignment(int alignment) {
if (alignment == horizontalAlignment) return;
int oldValue = horizontalAlignment;
horizontalAlignment = checkHorizontalKey(alignment,
"horizontalAlignment");
firePropertyChange(HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY,
oldValue, horizontalAlignment);
repaint();
}
/** {@collect.stats}
* Returns the vertical position of the text relative to the icon.
* @return the <code>verticalTextPosition</code> property,
* one of the following values:
* <ul>
* <li>{@code SwingConstants.CENTER} (the default)
* <li>{@code SwingConstants.TOP}
* <li>{@code SwingConstants.BOTTOM}
* </ul>
*/
public int getVerticalTextPosition() {
return verticalTextPosition;
}
/** {@collect.stats}
* Sets the vertical position of the text relative to the icon.
* @param textPosition one of the following values:
* <ul>
* <li>{@code SwingConstants.CENTER} (the default)
* <li>{@code SwingConstants.TOP}
* <li>{@code SwingConstants.BOTTOM}
* </ul>
* @beaninfo
* bound: true
* enum: TOP SwingConstants.TOP
* CENTER SwingConstants.CENTER
* BOTTOM SwingConstants.BOTTOM
* attribute: visualUpdate true
* description: The vertical position of the text relative to the icon.
*/
public void setVerticalTextPosition(int textPosition) {
if (textPosition == verticalTextPosition) return;
int oldValue = verticalTextPosition;
verticalTextPosition = checkVerticalKey(textPosition, "verticalTextPosition");
firePropertyChange(VERTICAL_TEXT_POSITION_CHANGED_PROPERTY, oldValue, verticalTextPosition);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the horizontal position of the text relative to the icon.
* @return the <code>horizontalTextPosition</code> property,
* one of the following values:
* <ul>
* <li>{@code SwingConstants.RIGHT}
* <li>{@code SwingConstants.LEFT}
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.LEADING}
* <li>{@code SwingConstants.TRAILING} (the default)
* </ul>
*/
public int getHorizontalTextPosition() {
return horizontalTextPosition;
}
/** {@collect.stats}
* Sets the horizontal position of the text relative to the icon.
* @param textPosition one of the following values:
* <ul>
* <li>{@code SwingConstants.RIGHT}
* <li>{@code SwingConstants.LEFT}
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.LEADING}
* <li>{@code SwingConstants.TRAILING} (the default)
* </ul>
* @exception IllegalArgumentException if <code>textPosition</code>
* is not one of the legal values listed above
* @beaninfo
* bound: true
* enum: LEFT SwingConstants.LEFT
* CENTER SwingConstants.CENTER
* RIGHT SwingConstants.RIGHT
* LEADING SwingConstants.LEADING
* TRAILING SwingConstants.TRAILING
* attribute: visualUpdate true
* description: The horizontal position of the text relative to the icon.
*/
public void setHorizontalTextPosition(int textPosition) {
if (textPosition == horizontalTextPosition) return;
int oldValue = horizontalTextPosition;
horizontalTextPosition = checkHorizontalKey(textPosition,
"horizontalTextPosition");
firePropertyChange(HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY,
oldValue,
horizontalTextPosition);
revalidate();
repaint();
}
/** {@collect.stats}
* Returns the amount of space between the text and the icon
* displayed in this button.
*
* @return an int equal to the number of pixels between the text
* and the icon.
* @since 1.4
* @see #setIconTextGap
*/
public int getIconTextGap() {
return iconTextGap;
}
/** {@collect.stats}
* If both the icon and text properties are set, this property
* defines the space between them.
* <p>
* The default value of this property is 4 pixels.
* <p>
* This is a JavaBeans bound property.
*
* @since 1.4
* @see #getIconTextGap
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: If both the icon and text properties are set, this
* property defines the space between them.
*/
public void setIconTextGap(int iconTextGap) {
int oldValue = this.iconTextGap;
this.iconTextGap = iconTextGap;
iconTextGapSet = true;
firePropertyChange("iconTextGap", oldValue, iconTextGap);
if (iconTextGap != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Verify that the {@code key} argument is a legal value for the
* {@code horizontalAlignment} and {@code horizontalTextPosition}
* properties. Valid values are:
* <ul>
* <li>{@code SwingConstants.RIGHT}
* <li>{@code SwingConstants.LEFT}
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.LEADING}
* <li>{@code SwingConstants.TRAILING}
* </ul>
*
* @param key the property value to check
* @param exception the message to use in the
* {@code IllegalArgumentException} that is thrown for an invalid
* value
* @exception IllegalArgumentException if key is not one of the legal
* values listed above
* @see #setHorizontalTextPosition
* @see #setHorizontalAlignment
*/
protected int checkHorizontalKey(int key, String exception) {
if ((key == LEFT) ||
(key == CENTER) ||
(key == RIGHT) ||
(key == LEADING) ||
(key == TRAILING)) {
return key;
} else {
throw new IllegalArgumentException(exception);
}
}
/** {@collect.stats}
* Verify that the {@code key} argument is a legal value for the
* vertical properties. Valid values are:
* <ul>
* <li>{@code SwingConstants.CENTER}
* <li>{@code SwingConstants.TOP}
* <li>{@code SwingConstants.BOTTOM}
* </ul>
*
* @param key the property value to check
* @param exception the message to use in the
* {@code IllegalArgumentException} that is thrown for an invalid
* value
* @exception IllegalArgumentException if key is not one of the legal
* values listed above
*/
protected int checkVerticalKey(int key, String exception) {
if ((key == TOP) || (key == CENTER) || (key == BOTTOM)) {
return key;
} else {
throw new IllegalArgumentException(exception);
}
}
/** {@collect.stats}
*{@inheritDoc}
*
* @since 1.6
*/
public void removeNotify() {
super.removeNotify();
if(isRolloverEnabled()) {
getModel().setRollover(false);
}
}
/** {@collect.stats}
* Sets the action command for this button.
* @param actionCommand the action command for this button
*/
public void setActionCommand(String actionCommand) {
getModel().setActionCommand(actionCommand);
}
/** {@collect.stats}
* Returns the action command for this button.
* @return the action command for this button
*/
public String getActionCommand() {
String ac = getModel().getActionCommand();
if(ac == null) {
ac = getText();
}
return ac;
}
private Action action;
private PropertyChangeListener actionPropertyChangeListener;
/** {@collect.stats}
* Sets the <code>Action</code>.
* The new <code>Action</code> replaces any previously set
* <code>Action</code> but does not affect <code>ActionListeners</code>
* independently added with <code>addActionListener</code>.
* If the <code>Action</code> is already a registered
* <code>ActionListener</code> for the button, it is not re-registered.
* <p>
* Setting the <code>Action</code> results in immediately changing
* all the properties described in <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a>.
* Subsequently, the button's properties are automatically updated
* as the <code>Action</code>'s properties change.
* <p>
* This method uses three other methods to set
* and help track the <code>Action</code>'s property values.
* It uses the <code>configurePropertiesFromAction</code> method
* to immediately change the button's properties.
* To track changes in the <code>Action</code>'s property values,
* this method registers the <code>PropertyChangeListener</code>
* returned by <code>createActionPropertyChangeListener</code>. The
* default {@code PropertyChangeListener} invokes the
* {@code actionPropertyChanged} method when a property in the
* {@code Action} changes.
*
* @param a the <code>Action</code> for the <code>AbstractButton</code>,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #getAction
* @see #configurePropertiesFromAction
* @see #createActionPropertyChangeListener
* @see #actionPropertyChanged
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the Action instance connected with this ActionEvent source
*/
public void setAction(Action a) {
Action oldValue = getAction();
if (action==null || !action.equals(a)) {
action = a;
if (oldValue!=null) {
removeActionListener(oldValue);
oldValue.removePropertyChangeListener(actionPropertyChangeListener);
actionPropertyChangeListener = null;
}
configurePropertiesFromAction(action);
if (action!=null) {
// Don't add if it is already a listener
if (!isListener(ActionListener.class, action)) {
addActionListener(action);
}
// Reverse linkage:
actionPropertyChangeListener = createActionPropertyChangeListener(action);
action.addPropertyChangeListener(actionPropertyChangeListener);
}
firePropertyChange("action", oldValue, action);
}
}
private boolean isListener(Class c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==c && listeners[i+1]==a) {
isListener=true;
}
}
return isListener;
}
/** {@collect.stats}
* Returns the currently set <code>Action</code> for this
* <code>ActionEvent</code> source, or <code>null</code>
* if no <code>Action</code> is set.
*
* @return the <code>Action</code> for this <code>ActionEvent</code>
* source, or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
public Action getAction() {
return action;
}
/** {@collect.stats}
* Sets the properties on this button to match those in the specified
* <code>Action</code>. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details as to which properties this sets.
*
* @param a the <code>Action</code> from which to get the properties,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
protected void configurePropertiesFromAction(Action a) {
setMnemonicFromAction(a);
setTextFromAction(a, false);
AbstractAction.setToolTipTextFromAction(this, a);
setIconFromAction(a);
setActionCommandFromAction(a);
AbstractAction.setEnabledFromAction(this, a);
if (AbstractAction.hasSelectedKey(a) &&
shouldUpdateSelectedStateFromAction()) {
setSelectedFromAction(a);
}
setDisplayedMnemonicIndexFromAction(a, false);
}
void clientPropertyChanged(Object key, Object oldValue,
Object newValue) {
if (key == "hideActionText") {
boolean current = (newValue instanceof Boolean) ?
(Boolean)newValue : false;
if (getHideActionText() != current) {
setHideActionText(current);
}
}
}
/** {@collect.stats}
* Button subclasses that support mirroring the selected state from
* the action should override this to return true. AbstractButton's
* implementation returns false.
*/
boolean shouldUpdateSelectedStateFromAction() {
return false;
}
/** {@collect.stats}
* Updates the button's state in response to property changes in the
* associated action. This method is invoked from the
* {@code PropertyChangeListener} returned from
* {@code createActionPropertyChangeListener}. Subclasses do not normally
* need to invoke this. Subclasses that support additional {@code Action}
* properties should override this and
* {@code configurePropertiesFromAction}.
* <p>
* Refer to the table at <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for a list of
* the properties this method sets.
*
* @param action the <code>Action</code> associated with this button
* @param propertyName the name of the property that changed
* @since 1.6
* @see Action
* @see #configurePropertiesFromAction
*/
protected void actionPropertyChanged(Action action, String propertyName) {
if (propertyName == Action.NAME) {
setTextFromAction(action, true);
} else if (propertyName == "enabled") {
AbstractAction.setEnabledFromAction(this, action);
} else if (propertyName == Action.SHORT_DESCRIPTION) {
AbstractAction.setToolTipTextFromAction(this, action);
} else if (propertyName == Action.SMALL_ICON) {
smallIconChanged(action);
} else if (propertyName == Action.MNEMONIC_KEY) {
setMnemonicFromAction(action);
} else if (propertyName == Action.ACTION_COMMAND_KEY) {
setActionCommandFromAction(action);
} else if (propertyName == Action.SELECTED_KEY &&
AbstractAction.hasSelectedKey(action) &&
shouldUpdateSelectedStateFromAction()) {
setSelectedFromAction(action);
} else if (propertyName == Action.DISPLAYED_MNEMONIC_INDEX_KEY) {
setDisplayedMnemonicIndexFromAction(action, true);
} else if (propertyName == Action.LARGE_ICON_KEY) {
largeIconChanged(action);
}
}
private void setDisplayedMnemonicIndexFromAction(
Action a, boolean fromPropertyChange) {
Integer iValue = (a == null) ? null :
(Integer)a.getValue(Action.DISPLAYED_MNEMONIC_INDEX_KEY);
if (fromPropertyChange || iValue != null) {
int value;
if (iValue == null) {
value = -1;
} else {
value = iValue;
String text = getText();
if (text == null || value >= text.length()) {
value = -1;
}
}
setDisplayedMnemonicIndex(value);
}
}
private void setMnemonicFromAction(Action a) {
Integer n = (a == null) ? null :
(Integer)a.getValue(Action.MNEMONIC_KEY);
setMnemonic((n == null) ? '\0' : n);
}
private void setTextFromAction(Action a, boolean propertyChange) {
boolean hideText = getHideActionText();
if (!propertyChange) {
setText((a != null && !hideText) ?
(String)a.getValue(Action.NAME) : null);
}
else if (!hideText) {
setText((String)a.getValue(Action.NAME));
}
}
void setIconFromAction(Action a) {
Icon icon = null;
if (a != null) {
icon = (Icon)a.getValue(Action.LARGE_ICON_KEY);
if (icon == null) {
icon = (Icon)a.getValue(Action.SMALL_ICON);
}
}
setIcon(icon);
}
void smallIconChanged(Action a) {
if (a.getValue(Action.LARGE_ICON_KEY) == null) {
setIconFromAction(a);
}
}
void largeIconChanged(Action a) {
setIconFromAction(a);
}
private void setActionCommandFromAction(Action a) {
setActionCommand((a != null) ?
(String)a.getValue(Action.ACTION_COMMAND_KEY) :
null);
}
/** {@collect.stats}
* Sets the seleted state of the button from the action. This is defined
* here, but not wired up. Subclasses like JToggleButton and
* JCheckBoxMenuItem make use of it.
*
* @param a the Action
*/
private void setSelectedFromAction(Action a) {
boolean selected = false;
if (a != null) {
selected = AbstractAction.isSelected(a);
}
if (selected != isSelected()) {
// This won't notify ActionListeners, but that should be
// ok as the change is coming from the Action.
setSelected(selected);
// Make sure the change actually took effect
if (!selected && isSelected()) {
if (getModel() instanceof DefaultButtonModel) {
ButtonGroup group = (ButtonGroup)
((DefaultButtonModel)getModel()).getGroup();
if (group != null) {
group.clearSelection();
}
}
}
}
}
/** {@collect.stats}
* Creates and returns a <code>PropertyChangeListener</code> that is
* responsible for listening for changes from the specified
* <code>Action</code> and updating the appropriate properties.
* <p>
* <b>Warning:</b> If you subclass this do not create an anonymous
* inner class. If you do the lifetime of the button will be tied to
* that of the <code>Action</code>.
*
* @param a the button's action
* @since 1.3
* @see <a href="#actions">Actions</a>
* @see Action
* @see #setAction
*/
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
return createActionPropertyChangeListener0(a);
}
PropertyChangeListener createActionPropertyChangeListener0(Action a) {
return new ButtonActionPropertyChangeListener(this, a);
}
private static class ButtonActionPropertyChangeListener
extends ActionPropertyChangeListener<AbstractButton> {
ButtonActionPropertyChangeListener(AbstractButton b, Action a) {
super(b, a);
}
protected void actionPropertyChanged(AbstractButton button,
Action action,
PropertyChangeEvent e) {
if (AbstractAction.shouldReconfigure(e)) {
button.configurePropertiesFromAction(action);
} else {
button.actionPropertyChanged(action, e.getPropertyName());
}
}
}
/** {@collect.stats}
* Gets the <code>borderPainted</code> property.
*
* @return the value of the <code>borderPainted</code> property
* @see #setBorderPainted
*/
public boolean isBorderPainted() {
return paintBorder;
}
/** {@collect.stats}
* Sets the <code>borderPainted</code> property.
* If <code>true</code> and the button has a border,
* the border is painted. The default value for the
* <code>borderPainted</code> property is <code>true</code>.
*
* @param b if true and border property is not <code>null</code>,
* the border is painted
* @see #isBorderPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the border should be painted.
*/
public void setBorderPainted(boolean b) {
boolean oldValue = paintBorder;
paintBorder = b;
borderPaintedSet = true;
firePropertyChange(BORDER_PAINTED_CHANGED_PROPERTY, oldValue, paintBorder);
if (b != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Paint the button's border if <code>BorderPainted</code>
* property is true and the button has a border.
* @param g the <code>Graphics</code> context in which to paint
*
* @see #paint
* @see #setBorder
*/
protected void paintBorder(Graphics g) {
if (isBorderPainted()) {
super.paintBorder(g);
}
}
/** {@collect.stats}
* Gets the <code>paintFocus</code> property.
*
* @return the <code>paintFocus</code> property
* @see #setFocusPainted
*/
public boolean isFocusPainted() {
return paintFocus;
}
/** {@collect.stats}
* Sets the <code>paintFocus</code> property, which must
* be <code>true</code> for the focus state to be painted.
* The default value for the <code>paintFocus</code> property
* is <code>true</code>.
* Some look and feels might not paint focus state;
* they will ignore this property.
*
* @param b if <code>true</code>, the focus state should be painted
* @see #isFocusPainted
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether focus should be painted
*/
public void setFocusPainted(boolean b) {
boolean oldValue = paintFocus;
paintFocus = b;
firePropertyChange(FOCUS_PAINTED_CHANGED_PROPERTY, oldValue, paintFocus);
if (b != oldValue && isFocusOwner()) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Gets the <code>contentAreaFilled</code> property.
*
* @return the <code>contentAreaFilled</code> property
* @see #setContentAreaFilled
*/
public boolean isContentAreaFilled() {
return contentAreaFilled;
}
/** {@collect.stats}
* Sets the <code>contentAreaFilled</code> property.
* If <code>true</code> the button will paint the content
* area. If you wish to have a transparent button, such as
* an icon only button, for example, then you should set
* this to <code>false</code>. Do not call <code>setOpaque(false)</code>.
* The default value for the the <code>contentAreaFilled</code>
* property is <code>true</code>.
* <p>
* This function may cause the component's opaque property to change.
* <p>
* The exact behavior of calling this function varies on a
* component-by-component and L&F-by-L&F basis.
*
* @param b if true, the content should be filled; if false
* the content area is not filled
* @see #isContentAreaFilled
* @see #setOpaque
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether the button should paint the content area
* or leave it transparent.
*/
public void setContentAreaFilled(boolean b) {
boolean oldValue = contentAreaFilled;
contentAreaFilled = b;
contentAreaFilledSet = true;
firePropertyChange(CONTENT_AREA_FILLED_CHANGED_PROPERTY, oldValue, contentAreaFilled);
if (b != oldValue) {
repaint();
}
}
/** {@collect.stats}
* Gets the <code>rolloverEnabled</code> property.
*
* @return the value of the <code>rolloverEnabled</code> property
* @see #setRolloverEnabled
*/
public boolean isRolloverEnabled() {
return rolloverEnabled;
}
/** {@collect.stats}
* Sets the <code>rolloverEnabled</code> property, which
* must be <code>true</code> for rollover effects to occur.
* The default value for the <code>rolloverEnabled</code>
* property is <code>false</code>.
* Some look and feels might not implement rollover effects;
* they will ignore this property.
*
* @param b if <code>true</code>, rollover effects should be painted
* @see #isRolloverEnabled
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Whether rollover effects should be enabled.
*/
public void setRolloverEnabled(boolean b) {
boolean oldValue = rolloverEnabled;
rolloverEnabled = b;
rolloverEnabledSet = true;
firePropertyChange(ROLLOVER_ENABLED_CHANGED_PROPERTY, oldValue, rolloverEnabled);
if (b != oldValue) {
repaint();
}
}
/** {@collect.stats}
* Returns the keyboard mnemonic from the the current model.
* @return the keyboard mnemonic from the model
*/
public int getMnemonic() {
return mnemonic;
}
/** {@collect.stats}
* Sets the keyboard mnemonic on the current model.
* The mnemonic is the key which when combined with the look and feel's
* mouseless modifier (usually Alt) will activate this button
* if focus is contained somewhere within this button's ancestor
* window.
* <p>
* A mnemonic must correspond to a single key on the keyboard
* and should be specified using one of the <code>VK_XXX</code>
* keycodes defined in <code>java.awt.event.KeyEvent</code>.
* Mnemonics are case-insensitive, therefore a key event
* with the corresponding keycode would cause the button to be
* activated whether or not the Shift modifier was pressed.
* <p>
* If the character defined by the mnemonic is found within
* the button's label string, the first occurrence of it
* will be underlined to indicate the mnemonic to the user.
*
* @param mnemonic the key code which represents the mnemonic
* @see java.awt.event.KeyEvent
* @see #setDisplayedMnemonicIndex
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the keyboard character mnemonic
*/
public void setMnemonic(int mnemonic) {
int oldValue = getMnemonic();
model.setMnemonic(mnemonic);
updateMnemonicProperties();
}
/** {@collect.stats}
* This method is now obsolete, please use <code>setMnemonic(int)</code>
* to set the mnemonic for a button. This method is only designed
* to handle character values which fall between 'a' and 'z' or
* 'A' and 'Z'.
*
* @param mnemonic a char specifying the mnemonic value
* @see #setMnemonic(int)
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the keyboard character mnemonic
*/
public void setMnemonic(char mnemonic) {
int vk = (int) mnemonic;
if(vk >= 'a' && vk <='z')
vk -= ('a' - 'A');
setMnemonic(vk);
}
/** {@collect.stats}
* Provides a hint to the look and feel as to which character in the
* text should be decorated to represent the mnemonic. Not all look and
* feels may support this. A value of -1 indicates either there is no
* mnemonic, the mnemonic character is not contained in the string, or
* the developer does not wish the mnemonic to be displayed.
* <p>
* The value of this is updated as the properties relating to the
* mnemonic change (such as the mnemonic itself, the text...).
* You should only ever have to call this if
* you do not wish the default character to be underlined. For example, if
* the text was 'Save As', with a mnemonic of 'a', and you wanted the 'A'
* to be decorated, as 'Save <u>A</u>s', you would have to invoke
* <code>setDisplayedMnemonicIndex(5)</code> after invoking
* <code>setMnemonic(KeyEvent.VK_A)</code>.
*
* @since 1.4
* @param index Index into the String to underline
* @exception IllegalArgumentException will be thrown if <code>index</code>
* is >= length of the text, or < -1
* @see #getDisplayedMnemonicIndex
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the index into the String to draw the keyboard character
* mnemonic at
*/
public void setDisplayedMnemonicIndex(int index)
throws IllegalArgumentException {
int oldValue = mnemonicIndex;
if (index == -1) {
mnemonicIndex = -1;
} else {
String text = getText();
int textLength = (text == null) ? 0 : text.length();
if (index < -1 || index >= textLength) { // index out of range
throw new IllegalArgumentException("index == " + index);
}
}
mnemonicIndex = index;
firePropertyChange("displayedMnemonicIndex", oldValue, index);
if (index != oldValue) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the character, as an index, that the look and feel should
* provide decoration for as representing the mnemonic character.
*
* @since 1.4
* @return index representing mnemonic character
* @see #setDisplayedMnemonicIndex
*/
public int getDisplayedMnemonicIndex() {
return mnemonicIndex;
}
/** {@collect.stats}
* Update the displayedMnemonicIndex property. This method
* is called when either text or mnemonic changes. The new
* value of the displayedMnemonicIndex property is the index
* of the first occurrence of mnemonic in text.
*/
private void updateDisplayedMnemonicIndex(String text, int mnemonic) {
setDisplayedMnemonicIndex(
SwingUtilities.findDisplayedMnemonicIndex(text, mnemonic));
}
/** {@collect.stats}
* Brings the mnemonic property in accordance with model's mnemonic.
* This is called when model's mnemonic changes. Also updates the
* displayedMnemonicIndex property.
*/
private void updateMnemonicProperties() {
int newMnemonic = model.getMnemonic();
if (mnemonic != newMnemonic) {
int oldValue = mnemonic;
mnemonic = newMnemonic;
firePropertyChange(MNEMONIC_CHANGED_PROPERTY,
oldValue, mnemonic);
updateDisplayedMnemonicIndex(getText(), mnemonic);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the amount of time (in milliseconds) required between
* mouse press events for the button to generate the corresponding
* action events. After the initial mouse press occurs (and action
* event generated) any subsequent mouse press events which occur
* on intervals less than the threshhold will be ignored and no
* corresponding action event generated. By default the threshhold is 0,
* which means that for each mouse press, an action event will be
* fired, no matter how quickly the mouse clicks occur. In buttons
* where this behavior is not desirable (for example, the "OK" button
* in a dialog), this threshhold should be set to an appropriate
* positive value.
*
* @see #getMultiClickThreshhold
* @param threshhold the amount of time required between mouse
* press events to generate corresponding action events
* @exception IllegalArgumentException if threshhold < 0
* @since 1.4
*/
public void setMultiClickThreshhold(long threshhold) {
if (threshhold < 0) {
throw new IllegalArgumentException("threshhold must be >= 0");
}
this.multiClickThreshhold = threshhold;
}
/** {@collect.stats}
* Gets the amount of time (in milliseconds) required between
* mouse press events for the button to generate the corresponding
* action events.
*
* @see #setMultiClickThreshhold
* @return the amount of time required between mouse press events
* to generate corresponding action events
* @since 1.4
*/
public long getMultiClickThreshhold() {
return multiClickThreshhold;
}
/** {@collect.stats}
* Returns the model that this button represents.
* @return the <code>model</code> property
* @see #setModel
*/
public ButtonModel getModel() {
return model;
}
/** {@collect.stats}
* Sets the model that this button represents.
* @param newModel the new <code>ButtonModel</code>
* @see #getModel
* @beaninfo
* bound: true
* description: Model that the Button uses.
*/
public void setModel(ButtonModel newModel) {
ButtonModel oldModel = getModel();
if (oldModel != null) {
oldModel.removeChangeListener(changeListener);
oldModel.removeActionListener(actionListener);
oldModel.removeItemListener(itemListener);
changeListener = null;
actionListener = null;
itemListener = null;
}
model = newModel;
if (newModel != null) {
changeListener = createChangeListener();
actionListener = createActionListener();
itemListener = createItemListener();
newModel.addChangeListener(changeListener);
newModel.addActionListener(actionListener);
newModel.addItemListener(itemListener);
updateMnemonicProperties();
//We invoke setEnabled() from JComponent
//because setModel() can be called from a constructor
//when the button is not fully initialized
super.setEnabled(newModel.isEnabled());
} else {
mnemonic = '\0';
}
updateDisplayedMnemonicIndex(getText(), mnemonic);
firePropertyChange(MODEL_CHANGED_PROPERTY, oldModel, newModel);
if (newModel != oldModel) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
* @return the ButtonUI object
* @see #setUI
*/
public ButtonUI getUI() {
return (ButtonUI) ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
* @param ui the <code>ButtonUI</code> L&F object
* @see #getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the LookAndFeel.
*/
public void setUI(ButtonUI ui) {
super.setUI(ui);
// disabled icons are generated by the LF so they should be unset here
if (disabledIcon instanceof UIResource) {
setDisabledIcon(null);
}
if (disabledSelectedIcon instanceof UIResource) {
setDisabledSelectedIcon(null);
}
}
/** {@collect.stats}
* Resets the UI property to a value from the current look
* and feel. Subtypes of <code>AbstractButton</code>
* should override this to update the UI. For
* example, <code>JButton</code> might do the following:
* <pre>
* setUI((ButtonUI)UIManager.getUI(
* "ButtonUI", "javax.swing.plaf.basic.BasicButtonUI", this));
* </pre>
*/
public void updateUI() {
}
/** {@collect.stats}
* Adds the specified component to this container at the specified
* index, refer to
* {@link java.awt.Container#addImpl(Component, Object, int)}
* for a complete description of this method.
*
* @param comp the component to be added
* @param constraints an object expressing layout constraints
* for this component
* @param index the position in the container's list at which to
* insert the component, where <code>-1</code>
* means append to the end
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
* @since 1.5
*/
protected void addImpl(Component comp, Object constraints, int index) {
if (!setLayout) {
setLayout(new OverlayLayout(this));
}
super.addImpl(comp, constraints, index);
}
/** {@collect.stats}
* Sets the layout manager for this container, refer to
* {@link java.awt.Container#setLayout(LayoutManager)}
* for a complete description of this method.
*
* @param mgr the specified layout manager
* @since 1.5
*/
public void setLayout(LayoutManager mgr) {
setLayout = true;
super.setLayout(mgr);
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the button.
* @param l the listener to be added
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a ChangeListener from the button.
* @param l the listener to be removed
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this AbstractButton with addChangeListener().
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])(listenerList.getListeners(
ChangeListener.class));
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created.
* @see EventListenerList
*/
protected void fireStateChanged() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Adds an <code>ActionListener</code> to the button.
* @param l the <code>ActionListener</code> to be added
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
/** {@collect.stats}
* Removes an <code>ActionListener</code> from the button.
* If the listener is the currently set <code>Action</code>
* for the button, then the <code>Action</code>
* is set to <code>null</code>.
*
* @param l the listener to be removed
*/
public void removeActionListener(ActionListener l) {
if ((l != null) && (getAction() == l)) {
setAction(null);
} else {
listenerList.remove(ActionListener.class, l);
}
}
/** {@collect.stats}
* Returns an array of all the <code>ActionListener</code>s added
* to this AbstractButton with addActionListener().
*
* @return all of the <code>ActionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ActionListener[] getActionListeners() {
return (ActionListener[])(listenerList.getListeners(
ActionListener.class));
}
/** {@collect.stats}
* Subclasses that want to handle <code>ChangeEvents</code> differently
* can override this to return another <code>ChangeListener</code>
* implementation.
*
* @return the new <code>ChangeListener</code>
*/
protected ChangeListener createChangeListener() {
return getHandler();
}
/** {@collect.stats}
* Extends <code>ChangeListener</code> to be serializable.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class ButtonChangeListener implements ChangeListener, Serializable {
// NOTE: This class is NOT used, instead the functionality has
// been moved to Handler.
ButtonChangeListener() {
}
public void stateChanged(ChangeEvent e) {
getHandler().stateChanged(e);
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>event</code>
* parameter.
*
* @param event the <code>ActionEvent</code> object
* @see EventListenerList
*/
protected void fireActionPerformed(ActionEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
String actionCommand = event.getActionCommand();
if(actionCommand == null) {
actionCommand = getActionCommand();
}
e = new ActionEvent(AbstractButton.this,
ActionEvent.ACTION_PERFORMED,
actionCommand,
event.getWhen(),
event.getModifiers());
}
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>event</code> parameter.
*
* @param event the <code>ItemEvent</code> object
* @see EventListenerList
*/
protected void fireItemStateChanged(ItemEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ItemEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ItemListener.class) {
// Lazily create the event:
if (e == null) {
e = new ItemEvent(AbstractButton.this,
ItemEvent.ITEM_STATE_CHANGED,
AbstractButton.this,
event.getStateChange());
}
((ItemListener)listeners[i+1]).itemStateChanged(e);
}
}
if (accessibleContext != null) {
if (event.getStateChange() == ItemEvent.SELECTED) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.SELECTED);
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(0), new Integer(1));
} else {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.SELECTED, null);
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(1), new Integer(0));
}
}
}
protected ActionListener createActionListener() {
return getHandler();
}
protected ItemListener createItemListener() {
return getHandler();
}
/** {@collect.stats}
* Enables (or disables) the button.
* @param b true to enable the button, otherwise false
*/
public void setEnabled(boolean b) {
if (!b && model.isRollover()) {
model.setRollover(false);
}
super.setEnabled(b);
model.setEnabled(b);
}
// *** Deprecated java.awt.Button APIs below *** //
/** {@collect.stats}
* Returns the label text.
*
* @return a <code>String</code> containing the label
* @deprecated - Replaced by <code>getText</code>
*/
@Deprecated
public String getLabel() {
return getText();
}
/** {@collect.stats}
* Sets the label text.
*
* @param label a <code>String</code> containing the text
* @deprecated - Replaced by <code>setText(text)</code>
* @beaninfo
* bound: true
* description: Replace by setText(text)
*/
@Deprecated
public void setLabel(String label) {
setText(label);
}
/** {@collect.stats}
* Adds an <code>ItemListener</code> to the <code>checkbox</code>.
* @param l the <code>ItemListener</code> to be added
*/
public void addItemListener(ItemListener l) {
listenerList.add(ItemListener.class, l);
}
/** {@collect.stats}
* Removes an <code>ItemListener</code> from the button.
* @param l the <code>ItemListener</code> to be removed
*/
public void removeItemListener(ItemListener l) {
listenerList.remove(ItemListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ItemListener</code>s added
* to this AbstractButton with addItemListener().
*
* @return all of the <code>ItemListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ItemListener[] getItemListeners() {
return (ItemListener[])listenerList.getListeners(ItemListener.class);
}
/** {@collect.stats}
* Returns an array (length 1) containing the label or
* <code>null</code> if the button is not selected.
*
* @return an array containing 1 Object: the text of the button,
* if the item is selected; otherwise <code>null</code>
*/
public Object[] getSelectedObjects() {
if (isSelected() == false) {
return null;
}
Object[] selectedObjects = new Object[1];
selectedObjects[0] = getText();
return selectedObjects;
}
protected void init(String text, Icon icon) {
if(text != null) {
setText(text);
}
if(icon != null) {
setIcon(icon);
}
// Set the UI
updateUI();
setAlignmentX(LEFT_ALIGNMENT);
setAlignmentY(CENTER_ALIGNMENT);
}
/** {@collect.stats}
* This is overridden to return false if the current <code>Icon</code>'s
* <code>Image</code> is not equal to the
* passed in <code>Image</code> <code>img</code>.
*
* @param img the <code>Image</code> to be compared
* @param infoflags flags used to repaint the button when the image
* is updated and which determine how much is to be painted
* @param x the x coordinate
* @param y the y coordinate
* @param w the width
* @param h the height
* @see java.awt.image.ImageObserver
* @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public boolean imageUpdate(Image img, int infoflags,
int x, int y, int w, int h) {
Icon iconDisplayed = getIcon();
if (iconDisplayed == null) {
return false;
}
if (!model.isEnabled()) {
if (model.isSelected()) {
iconDisplayed = getDisabledSelectedIcon();
} else {
iconDisplayed = getDisabledIcon();
}
} else if (model.isPressed() && model.isArmed()) {
iconDisplayed = getPressedIcon();
} else if (isRolloverEnabled() && model.isRollover()) {
if (model.isSelected()) {
iconDisplayed = getRolloverSelectedIcon();
} else {
iconDisplayed = getRolloverIcon();
}
} else if (model.isSelected()) {
iconDisplayed = getSelectedIcon();
}
if (!SwingUtilities.doesIconReferenceImage(iconDisplayed, img)) {
// We don't know about this image, disable the notification so
// we don't keep repainting.
return false;
}
return super.imageUpdate(img, infoflags, x, y, w, h);
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "borderPainted") {
if (!borderPaintedSet) {
setBorderPainted(((Boolean)value).booleanValue());
borderPaintedSet = false;
}
} else if (propertyName == "rolloverEnabled") {
if (!rolloverEnabledSet) {
setRolloverEnabled(((Boolean)value).booleanValue());
rolloverEnabledSet = false;
}
} else if (propertyName == "iconTextGap") {
if (!iconTextGapSet) {
setIconTextGap(((Number)value).intValue());
iconTextGapSet = false;
}
} else if (propertyName == "contentAreaFilled") {
if (!contentAreaFilledSet) {
setContentAreaFilled(((Boolean)value).booleanValue());
contentAreaFilledSet = false;
}
} else {
super.setUIProperty(propertyName, value);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>AbstractButton</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
* <P>
* Overriding <code>paramString</code> to provide information about the
* specific new aspects of the JFC components.
*
* @return a string representation of this <code>AbstractButton</code>
*/
protected String paramString() {
String defaultIconString = ((defaultIcon != null)
&& (defaultIcon != this) ?
defaultIcon.toString() : "");
String pressedIconString = ((pressedIcon != null)
&& (pressedIcon != this) ?
pressedIcon.toString() : "");
String disabledIconString = ((disabledIcon != null)
&& (disabledIcon != this) ?
disabledIcon.toString() : "");
String selectedIconString = ((selectedIcon != null)
&& (selectedIcon != this) ?
selectedIcon.toString() : "");
String disabledSelectedIconString = ((disabledSelectedIcon != null) &&
(disabledSelectedIcon != this) ?
disabledSelectedIcon.toString()
: "");
String rolloverIconString = ((rolloverIcon != null)
&& (rolloverIcon != this) ?
rolloverIcon.toString() : "");
String rolloverSelectedIconString = ((rolloverSelectedIcon != null) &&
(rolloverSelectedIcon != this) ?
rolloverSelectedIcon.toString()
: "");
String paintBorderString = (paintBorder ? "true" : "false");
String paintFocusString = (paintFocus ? "true" : "false");
String rolloverEnabledString = (rolloverEnabled ? "true" : "false");
return super.paramString() +
",defaultIcon=" + defaultIconString +
",disabledIcon=" + disabledIconString +
",disabledSelectedIcon=" + disabledSelectedIconString +
",margin=" + margin +
",paintBorder=" + paintBorderString +
",paintFocus=" + paintFocusString +
",pressedIcon=" + pressedIconString +
",rolloverEnabled=" + rolloverEnabledString +
",rolloverIcon=" + rolloverIconString +
",rolloverSelectedIcon=" + rolloverSelectedIconString +
",selectedIcon=" + selectedIconString +
",text=" + text;
}
private Handler getHandler() {
if (handler == null) {
handler = new Handler();
}
return handler;
}
//
// Listeners that are added to model
//
class Handler implements ActionListener, ChangeListener, ItemListener,
Serializable {
//
// ChangeListener
//
public void stateChanged(ChangeEvent e) {
Object source = e.getSource();
updateMnemonicProperties();
if (isEnabled() != model.isEnabled()) {
setEnabled(model.isEnabled());
}
fireStateChanged();
repaint();
}
//
// ActionListener
//
public void actionPerformed(ActionEvent event) {
fireActionPerformed(event);
}
//
// ItemListener
//
public void itemStateChanged(ItemEvent event) {
fireItemStateChanged(event);
if (shouldUpdateSelectedStateFromAction()) {
Action action = getAction();
if (action != null && AbstractAction.hasSelectedKey(action)) {
boolean selected = isSelected();
boolean isActionSelected = AbstractAction.isSelected(
action);
if (isActionSelected != selected) {
action.putValue(Action.SELECTED_KEY, selected);
}
}
}
}
}
///////////////////
// Accessibility support
///////////////////
/** {@collect.stats}
* This class implements accessibility support for the
* <code>AbstractButton</code> class. It provides an implementation of the
* Java Accessibility API appropriate to button and menu item
* user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
* @since 1.4
*/
protected abstract class AccessibleAbstractButton
extends AccessibleJComponent implements AccessibleAction,
AccessibleValue, AccessibleText, AccessibleExtendedComponent {
/** {@collect.stats}
* Returns the accessible name of this object.
*
* @return the localized name of the object -- can be
* <code>null</code> if this
* object does not have a name
*/
public String getAccessibleName() {
String name = accessibleName;
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
if (name == null) {
name = AbstractButton.this.getText();
}
if (name == null) {
name = super.getAccessibleName();
}
return name;
}
/** {@collect.stats}
* Get the AccessibleIcons associated with this object if one
* or more exist. Otherwise return null.
* @since 1.3
*/
public AccessibleIcon [] getAccessibleIcon() {
Icon defaultIcon = getIcon();
if (defaultIcon instanceof Accessible) {
AccessibleContext ac =
((Accessible)defaultIcon).getAccessibleContext();
if (ac != null && ac instanceof AccessibleIcon) {
return new AccessibleIcon[] { (AccessibleIcon)ac };
}
}
return null;
}
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getModel().isArmed()) {
states.add(AccessibleState.ARMED);
}
if (isFocusOwner()) {
states.add(AccessibleState.FOCUSED);
}
if (getModel().isPressed()) {
states.add(AccessibleState.PRESSED);
}
if (isSelected()) {
states.add(AccessibleState.CHECKED);
}
return states;
}
/** {@collect.stats}
* Get the AccessibleRelationSet associated with this object if one
* exists. Otherwise return null.
* @see AccessibleRelation
* @since 1.3
*/
public AccessibleRelationSet getAccessibleRelationSet() {
// Check where the AccessibleContext's relation
// set already contains a MEMBER_OF relation.
AccessibleRelationSet relationSet
= super.getAccessibleRelationSet();
if (!relationSet.contains(AccessibleRelation.MEMBER_OF)) {
// get the members of the button group if one exists
ButtonModel model = getModel();
if (model != null && model instanceof DefaultButtonModel) {
ButtonGroup group = ((DefaultButtonModel)model).getGroup();
if (group != null) {
// set the target of the MEMBER_OF relation to be
// the members of the button group.
int len = group.getButtonCount();
Object [] target = new Object[len];
Enumeration elem = group.getElements();
for (int i = 0; i < len; i++) {
if (elem.hasMoreElements()) {
target[i] = elem.nextElement();
}
}
AccessibleRelation relation =
new AccessibleRelation(AccessibleRelation.MEMBER_OF);
relation.setTarget(target);
relationSet.add(relation);
}
}
}
return relationSet;
}
/** {@collect.stats}
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Returns the number of Actions available in this object. The
* default behavior of a button is to have one action - toggle
* the button.
*
* @return 1, the number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/** {@collect.stats}
* Return a description of the specified action of the object.
*
* @param i zero-based index of the actions
*/
public String getAccessibleActionDescription(int i) {
if (i == 0) {
return UIManager.getString("AbstractButton.clickText");
} else {
return null;
}
}
/** {@collect.stats}
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
*/
public boolean doAccessibleAction(int i) {
if (i == 0) {
doClick();
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Get the value of this object as a Number.
*
* @return An Integer of 0 if this isn't selected or an Integer of 1 if
* this is selected.
* @see AbstractButton#isSelected
*/
public Number getCurrentAccessibleValue() {
if (isSelected()) {
return new Integer(1);
} else {
return new Integer(0);
}
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
int i = n.intValue();
if (i == 0) {
setSelected(false);
} else {
setSelected(true);
}
return true;
}
/** {@collect.stats}
* Get the minimum value of this object as a Number.
*
* @return an Integer of 0.
*/
public Number getMinimumAccessibleValue() {
return new Integer(0);
}
/** {@collect.stats}
* Get the maximum value of this object as a Number.
*
* @return An Integer of 1.
*/
public Number getMaximumAccessibleValue() {
return new Integer(1);
}
/* AccessibleText ---------- */
public AccessibleText getAccessibleText() {
View view = (View)AbstractButton.this.getClientProperty("html");
if (view != null) {
return this;
} else {
return null;
}
}
/** {@collect.stats}
* Given a point in local coordinates, return the zero-based index
* of the character under that Point. If the point is invalid,
* this method returns -1.
*
* Note: the AbstractButton must have a valid size (e.g. have
* been added to a parent container whose ancestor container
* is a valid top-level window) for this method to be able
* to return a meaningful value.
*
* @param p the Point in local coordinates
* @return the zero-based index of the character under Point p; if
* Point is invalid returns -1.
* @since 1.3
*/
public int getIndexAtPoint(Point p) {
View view = (View) AbstractButton.this.getClientProperty("html");
if (view != null) {
Rectangle r = getTextRectangle();
if (r == null) {
return -1;
}
Rectangle2D.Float shape =
new Rectangle2D.Float(r.x, r.y, r.width, r.height);
Position.Bias bias[] = new Position.Bias[1];
return view.viewToModel(p.x, p.y, shape, bias);
} else {
return -1;
}
}
/** {@collect.stats}
* Determine the bounding box of the character at the given
* index into the string. The bounds are returned in local
* coordinates. If the index is invalid an empty rectangle is
* returned.
*
* Note: the AbstractButton must have a valid size (e.g. have
* been added to a parent container whose ancestor container
* is a valid top-level window) for this method to be able
* to return a meaningful value.
*
* @param i the index into the String
* @return the screen coordinates of the character's the bounding box,
* if index is invalid returns an empty rectangle.
* @since 1.3
*/
public Rectangle getCharacterBounds(int i) {
View view = (View) AbstractButton.this.getClientProperty("html");
if (view != null) {
Rectangle r = getTextRectangle();
if (r == null) {
return null;
}
Rectangle2D.Float shape =
new Rectangle2D.Float(r.x, r.y, r.width, r.height);
try {
Shape charShape =
view.modelToView(i, shape, Position.Bias.Forward);
return charShape.getBounds();
} catch (BadLocationException e) {
return null;
}
} else {
return null;
}
}
/** {@collect.stats}
* Return the number of characters (valid indicies)
*
* @return the number of characters
* @since 1.3
*/
public int getCharCount() {
View view = (View) AbstractButton.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
return doc.getLength();
}
}
return accessibleContext.getAccessibleName().length();
}
/** {@collect.stats}
* Return the zero-based offset of the caret.
*
* Note: That to the right of the caret will have the same index
* value as the offset (the caret is between two characters).
* @return the zero-based offset of the caret.
* @since 1.3
*/
public int getCaretPosition() {
// There is no caret.
return -1;
}
/** {@collect.stats}
* Returns the String at a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence,
* null for an invalid index or part
* @since 1.3
*/
public String getAtIndex(int part, int index) {
if (index < 0 || index >= getCharCount()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
try {
return getText(index, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int end = words.following(index);
return s.substring(words.previous(), end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int end = sentence.following(index);
return s.substring(sentence.previous(), end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Returns the String after a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid
* index or part
* @since 1.3
*/
public String getAfterIndex(int part, int index) {
if (index < 0 || index >= getCharCount()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index+1 >= getCharCount()) {
return null;
}
try {
return getText(index+1, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int start = words.following(index);
if (start == BreakIterator.DONE || start >= s.length()) {
return null;
}
int end = words.following(start);
if (end == BreakIterator.DONE || end >= s.length()) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int start = sentence.following(index);
if (start == BreakIterator.DONE || start > s.length()) {
return null;
}
int end = sentence.following(start);
if (end == BreakIterator.DONE || end > s.length()) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Returns the String before a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid index
* or part
* @since 1.3
*/
public String getBeforeIndex(int part, int index) {
if (index < 0 || index > getCharCount()-1) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index == 0) {
return null;
}
try {
return getText(index-1, 1);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.WORD:
try {
String s = getText(0, getCharCount());
BreakIterator words = BreakIterator.getWordInstance(getLocale());
words.setText(s);
int end = words.following(index);
end = words.previous();
int start = words.previous();
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
case AccessibleText.SENTENCE:
try {
String s = getText(0, getCharCount());
BreakIterator sentence =
BreakIterator.getSentenceInstance(getLocale());
sentence.setText(s);
int end = sentence.following(index);
end = sentence.previous();
int start = sentence.previous();
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
} catch (BadLocationException e) {
return null;
}
default:
return null;
}
}
/** {@collect.stats}
* Return the AttributeSet for a given character at a given index
*
* @param i the zero-based index into the text
* @return the AttributeSet of the character
* @since 1.3
*/
public AttributeSet getCharacterAttribute(int i) {
View view = (View) AbstractButton.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
Element elem = doc.getCharacterElement(i);
if (elem != null) {
return elem.getAttributes();
}
}
}
return null;
}
/** {@collect.stats}
* Returns the start offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into the text of the start of the selection
* @since 1.3
*/
public int getSelectionStart() {
// Text cannot be selected.
return -1;
}
/** {@collect.stats}
* Returns the end offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
*
* @return the index into teh text of the end of the selection
* @since 1.3
*/
public int getSelectionEnd() {
// Text cannot be selected.
return -1;
}
/** {@collect.stats}
* Returns the portion of the text that is selected.
*
* @return the String portion of the text that is selected
* @since 1.3
*/
public String getSelectedText() {
// Text cannot be selected.
return null;
}
/*
* Returns the text substring starting at the specified
* offset with the specified length.
*/
private String getText(int offset, int length)
throws BadLocationException {
View view = (View) AbstractButton.this.getClientProperty("html");
if (view != null) {
Document d = view.getDocument();
if (d instanceof StyledDocument) {
StyledDocument doc = (StyledDocument)d;
return doc.getText(offset, length);
}
}
return null;
}
/*
* Returns the bounding rectangle for the component text.
*/
private Rectangle getTextRectangle() {
String text = AbstractButton.this.getText();
Icon icon = (AbstractButton.this.isEnabled()) ? AbstractButton.this.getIcon() : AbstractButton.this.getDisabledIcon();
if ((icon == null) && (text == null)) {
return null;
}
Rectangle paintIconR = new Rectangle();
Rectangle paintTextR = new Rectangle();
Rectangle paintViewR = new Rectangle();
Insets paintViewInsets = new Insets(0, 0, 0, 0);
paintViewInsets = AbstractButton.this.getInsets(paintViewInsets);
paintViewR.x = paintViewInsets.left;
paintViewR.y = paintViewInsets.top;
paintViewR.width = AbstractButton.this.getWidth() - (paintViewInsets.left + paintViewInsets.right);
paintViewR.height = AbstractButton.this.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
String clippedText = SwingUtilities.layoutCompoundLabel(
(JComponent)AbstractButton.this,
getFontMetrics(getFont()),
text,
icon,
AbstractButton.this.getVerticalAlignment(),
AbstractButton.this.getHorizontalAlignment(),
AbstractButton.this.getVerticalTextPosition(),
AbstractButton.this.getHorizontalTextPosition(),
paintViewR,
paintIconR,
paintTextR,
0);
return paintTextR;
}
// ----- AccessibleExtendedComponent
/** {@collect.stats}
* Returns the AccessibleExtendedComponent
*
* @return the AccessibleExtendedComponent
*/
AccessibleExtendedComponent getAccessibleExtendedComponent() {
return this;
}
/** {@collect.stats}
* Returns the tool tip text
*
* @return the tool tip text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getToolTipText() {
return AbstractButton.this.getToolTipText();
}
/** {@collect.stats}
* Returns the titled border text
*
* @return the titled border text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getTitledBorderText() {
return super.getTitledBorderText();
}
/** {@collect.stats}
* Returns key bindings associated with this object
*
* @return the key bindings, if supported, of the object;
* otherwise, null
* @see AccessibleKeyBinding
* @since 1.4
*/
public AccessibleKeyBinding getAccessibleKeyBinding() {
int mnemonic = AbstractButton.this.getMnemonic();
if (mnemonic == 0) {
return null;
}
return new ButtonKeyBinding(mnemonic);
}
class ButtonKeyBinding implements AccessibleKeyBinding {
int mnemonic;
ButtonKeyBinding(int mnemonic) {
this.mnemonic = mnemonic;
}
/** {@collect.stats}
* Returns the number of key bindings for this object
*
* @return the zero-based number of key bindings for this object
*/
public int getAccessibleKeyBindingCount() {
return 1;
}
/** {@collect.stats}
* Returns a key binding for this object. The value returned is an
* java.lang.Object which must be cast to appropriate type depending
* on the underlying implementation of the key. For example, if the
* Object returned is a javax.swing.KeyStroke, the user of this
* method should do the following:
* <nf><code>
* Component c = <get the component that has the key bindings>
* AccessibleContext ac = c.getAccessibleContext();
* AccessibleKeyBinding akb = ac.getAccessibleKeyBinding();
* for (int i = 0; i < akb.getAccessibleKeyBindingCount(); i++) {
* Object o = akb.getAccessibleKeyBinding(i);
* if (o instanceof javax.swing.KeyStroke) {
* javax.swing.KeyStroke keyStroke = (javax.swing.KeyStroke)o;
* <do something with the key binding>
* }
* }
* </code></nf>
*
* @param i zero-based index of the key bindings
* @return a javax.lang.Object which specifies the key binding
* @exception IllegalArgumentException if the index is
* out of bounds
* @see #getAccessibleKeyBindingCount
*/
public java.lang.Object getAccessibleKeyBinding(int i) {
if (i != 0) {
throw new IllegalArgumentException();
}
return KeyStroke.getKeyStroke(mnemonic, 0);
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.text.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.*;
import java.util.Arrays;
/** {@collect.stats}
* <code>JPasswordField</code> is a lightweight component that allows
* the editing of a single line of text where the view indicates
* something was typed, but does not show the original characters.
* You can find further information and examples in
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html">How to Use Text Fields</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* <code>JPasswordField</code> is intended
* to be source-compatible with <code>java.awt.TextField</code>
* used with <code>echoChar</code> set. It is provided separately
* to make it easier to safely change the UI for the
* <code>JTextField</code> without affecting password entries.
* <p>
* <strong>NOTE:</strong>
* By default, JPasswordField disables input methods; otherwise, input
* characters could be visible while they were composed using input methods.
* If an application needs the input methods support, please use the
* inherited method, <code>enableInputMethods(true)</code>.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: Allows the editing of a line of text but doesn't show the characters.
*
* @author Timothy Prinzing
*/
public class JPasswordField extends JTextField {
/** {@collect.stats}
* Constructs a new <code>JPasswordField</code>,
* with a default document, <code>null</code> starting
* text string, and 0 column width.
*/
public JPasswordField() {
this(null,null,0);
}
/** {@collect.stats}
* Constructs a new <code>JPasswordField</code> initialized
* with the specified text. The document model is set to the
* default, and the number of columns to 0.
*
* @param text the text to be displayed, <code>null</code> if none
*/
public JPasswordField(String text) {
this(null, text, 0);
}
/** {@collect.stats}
* Constructs a new empty <code>JPasswordField</code> with the specified
* number of columns. A default model is created, and the initial string
* is set to <code>null</code>.
*
* @param columns the number of columns >= 0
*/
public JPasswordField(int columns) {
this(null, null, columns);
}
/** {@collect.stats}
* Constructs a new <code>JPasswordField</code> initialized with
* the specified text and columns. The document model is set to
* the default.
*
* @param text the text to be displayed, <code>null</code> if none
* @param columns the number of columns >= 0
*/
public JPasswordField(String text, int columns) {
this(null, text, columns);
}
/** {@collect.stats}
* Constructs a new <code>JPasswordField</code> that uses the
* given text storage model and the given number of columns.
* This is the constructor through which the other constructors feed.
* The echo character is set to '*', but may be changed by the current
* Look and Feel. If the document model is
* <code>null</code>, a default one will be created.
*
* @param doc the text storage to use
* @param txt the text to be displayed, <code>null</code> if none
* @param columns the number of columns to use to calculate
* the preferred width >= 0; if columns is set to zero, the
* preferred width will be whatever naturally results from
* the component implementation
*/
public JPasswordField(Document doc, String txt, int columns) {
super(doc, txt, columns);
// We could either leave this on, which wouldn't be secure,
// or obscure the composted text, which essentially makes displaying
// it useless. Therefore, we turn off input methods.
enableInputMethods(false);
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "PasswordFieldUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void updateUI() {
if(!echoCharSet) {
echoChar = '*';
}
super.updateUI();
}
/** {@collect.stats}
* Returns the character to be used for echoing. The default is '*'.
* The default may be different depending on the currently running Look
* and Feel. For example, Metal/Ocean's default is a bullet character.
*
* @return the echo character, 0 if unset
* @see #setEchoChar
* @see #echoCharIsSet
*/
public char getEchoChar() {
return echoChar;
}
/** {@collect.stats}
* Sets the echo character for this <code>JPasswordField</code>.
* Note that this is largely a suggestion, since the
* view that gets installed can use whatever graphic techniques
* it desires to represent the field. Setting a value of 0 indicates
* that you wish to see the text as it is typed, similar to
* the behavior of a standard <code>JTextField</code>.
*
* @param c the echo character to display
* @see #echoCharIsSet
* @see #getEchoChar
* @beaninfo
* description: character to display in place of the real characters
* attribute: visualUpdate true
*/
public void setEchoChar(char c) {
echoChar = c;
echoCharSet = true;
repaint();
revalidate();
}
/** {@collect.stats}
* Returns true if this <code>JPasswordField</code> has a character
* set for echoing. A character is considered to be set if the echo
* character is not 0.
*
* @return true if a character is set for echoing
* @see #setEchoChar
* @see #getEchoChar
*/
public boolean echoCharIsSet() {
return echoChar != 0;
}
// --- JTextComponent methods ----------------------------------
/** {@collect.stats}
* Invokes <code>provideErrorFeedback</code> on the current
* look and feel, which typically initiates an error beep.
* The normal behavior of transferring the
* currently selected range in the associated text model
* to the system clipboard, and removing the contents from
* the model, is not acceptable for a password field.
*/
public void cut() {
if (getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) {
UIManager.getLookAndFeel().provideErrorFeedback(this);
} else {
super.cut();
}
}
/** {@collect.stats}
* Invokes <code>provideErrorFeedback</code> on the current
* look and feel, which typically initiates an error beep.
* The normal behavior of transferring the
* currently selected range in the associated text model
* to the system clipboard, and leaving the contents from
* the model, is not acceptable for a password field.
*/
public void copy() {
if (getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) {
UIManager.getLookAndFeel().provideErrorFeedback(this);
} else {
super.copy();
}
}
/** {@collect.stats}
* Returns the text contained in this <code>TextComponent</code>.
* If the underlying document is <code>null</code>, will give a
* <code>NullPointerException</code>.
* <p>
* For security reasons, this method is deprecated. Use the
<code>* getPassword</code> method instead.
* @deprecated As of Java 2 platform v1.2,
* replaced by <code>getPassword</code>.
* @return the text
*/
@Deprecated
public String getText() {
return super.getText();
}
/** {@collect.stats}
* Fetches a portion of the text represented by the
* component. Returns an empty string if length is 0.
* <p>
* For security reasons, this method is deprecated. Use the
* <code>getPassword</code> method instead.
* @deprecated As of Java 2 platform v1.2,
* replaced by <code>getPassword</code>.
* @param offs the offset >= 0
* @param len the length >= 0
* @return the text
* @exception BadLocationException if the offset or length are invalid
*/
@Deprecated
public String getText(int offs, int len) throws BadLocationException {
return super.getText(offs, len);
}
/** {@collect.stats}
* Returns the text contained in this <code>TextComponent</code>.
* If the underlying document is <code>null</code>, will give a
* <code>NullPointerException</code>. For stronger
* security, it is recommended that the returned character array be
* cleared after use by setting each character to zero.
*
* @return the text
*/
public char[] getPassword() {
Document doc = getDocument();
Segment txt = new Segment();
try {
doc.getText(0, doc.getLength(), txt); // use the non-String API
} catch (BadLocationException e) {
return null;
}
char[] retValue = new char[txt.count];
System.arraycopy(txt.array, txt.offset, retValue, 0, txt.count);
return retValue;
}
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
// --- variables -----------------------------------------------
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "PasswordFieldUI";
private char echoChar;
private boolean echoCharSet = false;
/** {@collect.stats}
* Returns a string representation of this <code>JPasswordField</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JPasswordField</code>
*/
protected String paramString() {
return super.paramString() +
",echoChar=" + echoChar;
}
/** {@collect.stats}
* This method is a hack to get around the fact that we cannot
* directly override setUIProperty because part of the inheritance heirarchy
* goes outside of the javax.swing package, and therefore calling a package
* private method isn't allowed. This method should return true if the property
* was handled, and false otherwise.
*/
boolean customSetUIProperty(String propertyName, Object value) {
if (propertyName == "echoChar") {
if (!echoCharSet) {
setEchoChar((Character)value);
echoCharSet = false;
}
return true;
}
return false;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Returns the <code>AccessibleContext</code> associated with this
* <code>JPasswordField</code>. For password fields, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleJPasswordField</code>.
* A new <code>AccessibleJPasswordField</code> instance is created
* if necessary.
*
* @return an <code>AccessibleJPasswordField</code> that serves as the
* <code>AccessibleContext</code> of this
* <code>JPasswordField</code>
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJPasswordField();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JPasswordField</code> class. It provides an implementation of the
* Java Accessibility API appropriate to password field user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJPasswordField extends AccessibleJTextField {
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object (AccessibleRole.PASSWORD_TEXT)
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PASSWORD_TEXT;
}
/** {@collect.stats}
* Gets the <code>AccessibleText</code> for the <code>JPasswordField</code>.
* The returned object also implements the
* <code>AccessibleExtendedText</code> interface.
*
* @return <code>AccessibleText</code> for the JPasswordField
* @see javax.accessibility.AccessibleContext
* @see javax.accessibility.AccessibleContext#getAccessibleText
* @see javax.accessibility.AccessibleText
* @see javax.accessibility.AccessibleExtendedText
*
* @since 1.6
*/
public AccessibleText getAccessibleText() {
return this;
}
/*
* Returns a String filled with password echo characters. The String
* contains one echo character for each character (including whitespace)
* that the user entered in the JPasswordField.
*/
private String getEchoString(String str) {
if (str == null) {
return null;
}
char[] buffer = new char[str.length()];
Arrays.fill(buffer, getEchoChar());
return new String(buffer);
}
/** {@collect.stats}
* Returns the <code>String</code> at a given <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code> or
* <code>SENTENCE</code> to retrieve
* @param index an index within the text
* @return a <code>String</code> if <code>part</code> and
* <code>index</code> are valid.
* Otherwise, <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
*
* @since 1.6
*/
public String getAtIndex(int part, int index) {
String str = null;
if (part == AccessibleText.CHARACTER) {
str = super.getAtIndex(part, index);
} else {
// Treat the text displayed in the JPasswordField
// as one word and sentence.
char password[] = getPassword();
if (password == null ||
index < 0 || index >= password.length) {
return null;
}
str = new String(password);
}
return getEchoString(str);
}
/** {@collect.stats}
* Returns the <code>String</code> after a given <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code> or
* <code>SENTENCE</code> to retrieve
* @param index an index within the text
* @return a <code>String</code> if <code>part</code> and
* <code>index</code> are valid.
* Otherwise, <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
*
* @since 1.6
*/
public String getAfterIndex(int part, int index) {
if (part == AccessibleText.CHARACTER) {
String str = super.getAfterIndex(part, index);
return getEchoString(str);
} else {
// There is no word or sentence after the text
// displayed in the JPasswordField.
return null;
}
}
/** {@collect.stats}
* Returns the <code>String</code> before a given <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code> or
* <code>SENTENCE</code> to retrieve
* @param index an index within the text
* @return a <code>String</code> if <code>part</code> and
* <code>index</code> are valid.
* Otherwise, <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
*
* @since 1.6
*/
public String getBeforeIndex(int part, int index) {
if (part == AccessibleText.CHARACTER) {
String str = super.getBeforeIndex(part, index);
return getEchoString(str);
} else {
// There is no word or sentence before the text
// displayed in the JPasswordField.
return null;
}
}
/** {@collect.stats}
* Returns the text between two <code>indices</code>.
*
* @param startIndex the start index in the text
* @param endIndex the end index in the text
* @return the text string if the indices are valid.
* Otherwise, <code>null</code> is returned
*
* @since 1.6
*/
public String getTextRange(int startIndex, int endIndex) {
String str = super.getTextRange(startIndex, endIndex);
return getEchoString(str);
}
/** {@collect.stats}
* Returns the <code>AccessibleTextSequence</code> at a given
* <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code>,
* <code>SENTENCE</code>, <code>LINE</code> or <code>ATTRIBUTE_RUN</code> to
* retrieve
* @param index an index within the text
* @return an <code>AccessibleTextSequence</code> specifying the text if
* <code>part</code> and <code>index</code> are valid. Otherwise,
* <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
* @see javax.accessibility.AccessibleExtendedText#LINE
* @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
*
* @since 1.6
*/
public AccessibleTextSequence getTextSequenceAt(int part, int index) {
if (part == AccessibleText.CHARACTER) {
AccessibleTextSequence seq = super.getTextSequenceAt(part, index);
if (seq == null) {
return null;
}
return new AccessibleTextSequence(seq.startIndex, seq.endIndex,
getEchoString(seq.text));
} else {
// Treat the text displayed in the JPasswordField
// as one word, sentence, line and attribute run
char password[] = getPassword();
if (password == null ||
index < 0 || index >= password.length) {
return null;
}
String text = new String(password);
return new AccessibleTextSequence(0, password.length - 1,
getEchoString(text));
}
}
/** {@collect.stats}
* Returns the <code>AccessibleTextSequence</code> after a given
* <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code>,
* <code>SENTENCE</code>, <code>LINE</code> or <code>ATTRIBUTE_RUN</code> to
* retrieve
* @param index an index within the text
* @return an <code>AccessibleTextSequence</code> specifying the text if
* <code>part</code> and <code>index</code> are valid. Otherwise,
* <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
* @see javax.accessibility.AccessibleExtendedText#LINE
* @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
*
* @since 1.6
*/
public AccessibleTextSequence getTextSequenceAfter(int part, int index) {
if (part == AccessibleText.CHARACTER) {
AccessibleTextSequence seq = super.getTextSequenceAfter(part, index);
if (seq == null) {
return null;
}
return new AccessibleTextSequence(seq.startIndex, seq.endIndex,
getEchoString(seq.text));
} else {
// There is no word, sentence, line or attribute run
// after the text displayed in the JPasswordField.
return null;
}
}
/** {@collect.stats}
* Returns the <code>AccessibleTextSequence</code> before a given
* <code>index</code>.
*
* @param part the <code>CHARACTER</code>, <code>WORD</code>,
* <code>SENTENCE</code>, <code>LINE</code> or <code>ATTRIBUTE_RUN</code> to
* retrieve
* @param index an index within the text
* @return an <code>AccessibleTextSequence</code> specifying the text if
* <code>part</code> and <code>index</code> are valid. Otherwise,
* <code>null</code> is returned
*
* @see javax.accessibility.AccessibleText#CHARACTER
* @see javax.accessibility.AccessibleText#WORD
* @see javax.accessibility.AccessibleText#SENTENCE
* @see javax.accessibility.AccessibleExtendedText#LINE
* @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
*
* @since 1.6
*/
public AccessibleTextSequence getTextSequenceBefore(int part, int index) {
if (part == AccessibleText.CHARACTER) {
AccessibleTextSequence seq = super.getTextSequenceBefore(part, index);
if (seq == null) {
return null;
}
return new AccessibleTextSequence(seq.startIndex, seq.endIndex,
getEchoString(seq.text));
} else {
// There is no word, sentence, line or attribute run
// before the text displayed in the JPasswordField.
return null;
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.event.*;
import java.awt.*;
import java.util.Vector;
import java.util.Locale;
import java.beans.*;
import javax.swing.event.*;
import javax.accessibility.*;
import javax.swing.plaf.*;
import javax.swing.text.Position;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.Serializable;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
import static sun.swing.SwingUtilities2.Section.*;
/** {@collect.stats}
* A component that displays a list of objects and allows the user to select
* one or more items. A separate model, {@code ListModel}, maintains the
* contents of the list.
* <p>
* It's easy to display an array or Vector of objects, using the {@code JList}
* constructor that automatically builds a read-only {@code ListModel} instance
* for you:
* <pre>
* // Create a JList that displays strings from an array
*
* String[] data = {"one", "two", "three", "four"};
* JList myList = new JList(data);
*
* // Create a JList that displays the superclasses of JList.class, by
* // creating it with a Vector populated with this data
*
* Vector superClasses = new Vector();
* Class rootClass = javax.swing.JList.class;
* for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) {
* superClasses.addElement(cls);
* }
* JList myList = new JList(superClasses);
*
* // The automatically created model is stored in JList's "model"
* // property, which you can retrieve
*
* ListModel model = myList.getModel();
* for(int i = 0; i < model.getSize(); i++) {
* System.out.println(model.getElementAt(i));
* }
* </pre>
* <p>
* A {@code ListModel} can be supplied directly to a {@code JList} by way of a
* constructor or the {@code setModel} method. The contents need not be static -
* the number of items, and the values of items can change over time. A correct
* {@code ListModel} implementation notifies the set of
* {@code javax.swing.event.ListDataListener}s that have been added to it, each
* time a change occurs. These changes are characterized by a
* {@code javax.swing.event.ListDataEvent}, which identifies the range of list
* indices that have been modified, added, or removed. {@code JList}'s
* {@code ListUI} is responsible for keeping the visual representation up to
* date with changes, by listening to the model.
* <p>
* Simple, dynamic-content, {@code JList} applications can use the
* {@code DefaultListModel} class to maintain list elements. This class
* implements the {@code ListModel} interface and also provides a
* <code>java.util.Vector</code>-like API. Applications that need a more
* custom <code>ListModel</code> implementation may instead wish to subclass
* {@code AbstractListModel}, which provides basic support for managing and
* notifying listeners. For example, a read-only implementation of
* {@code AbstractListModel}:
* <pre>
* // This list model has about 2^16 elements. Enjoy scrolling.
*
* ListModel bigData = new AbstractListModel() {
* public int getSize() { return Short.MAX_VALUE; }
* public Object getElementAt(int index) { return "Index " + index; }
* };
* </pre>
* <p>
* The selection state of a {@code JList} is managed by another separate
* model, an instance of {@code ListSelectionModel}. {@code JList} is
* initialized with a selection model on construction, and also contains
* methods to query or set this selection model. Additionally, {@code JList}
* provides convenient methods for easily managing the selection. These methods,
* such as {@code setSelectedIndex} and {@code getSelectedValue}, are cover
* methods that take care of the details of interacting with the selection
* model. By default, {@code JList}'s selection model is configured to allow any
* combination of items to be selected at a time; selection mode
* {@code MULTIPLE_INTERVAL_SELECTION}. The selection mode can be changed
* on the selection model directly, or via {@code JList}'s cover method.
* Responsibility for updating the selection model in response to user gestures
* lies with the list's {@code ListUI}.
* <p>
* A correct {@code ListSelectionModel} implementation notifies the set of
* {@code javax.swing.event.ListSelectionListener}s that have been added to it
* each time a change to the selection occurs. These changes are characterized
* by a {@code javax.swing.event.ListSelectionEvent}, which identifies the range
* of the selection change.
* <p>
* The preferred way to listen for changes in list selection is to add
* {@code ListSelectionListener}s directly to the {@code JList}. {@code JList}
* then takes care of listening to the the selection model and notifying your
* listeners of change.
* <p>
* Responsibility for listening to selection changes in order to keep the list's
* visual representation up to date lies with the list's {@code ListUI}.
* <p>
* <a name="renderer">
* Painting of cells in a {@code JList} is handled by a delegate called a
* cell renderer, installed on the list as the {@code cellRenderer} property.
* The renderer provides a {@code java.awt.Component} that is used
* like a "rubber stamp" to paint the cells. Each time a cell needs to be
* painted, the list's {@code ListUI} asks the cell renderer for the component,
* moves it into place, and has it paint the contents of the cell by way of its
* {@code paint} method. A default cell renderer, which uses a {@code JLabel}
* component to render, is installed by the lists's {@code ListUI}. You can
* substitute your own renderer using code like this:
* <pre>
* // Display an icon and a string for each object in the list.
*
* class MyCellRenderer extends JLabel implements ListCellRenderer {
* final static ImageIcon longIcon = new ImageIcon("long.gif");
* final static ImageIcon shortIcon = new ImageIcon("short.gif");
*
* // This is the only method defined by ListCellRenderer.
* // We just reconfigure the JLabel each time we're called.
*
* public Component getListCellRendererComponent(
* JList list, // the list
* Object value, // value to display
* int index, // cell index
* boolean isSelected, // is the cell selected
* boolean cellHasFocus) // does the cell have focus
* {
* String s = value.toString();
* setText(s);
* setIcon((s.length() > 10) ? longIcon : shortIcon);
* if (isSelected) {
* setBackground(list.getSelectionBackground());
* setForeground(list.getSelectionForeground());
* } else {
* setBackground(list.getBackground());
* setForeground(list.getForeground());
* }
* setEnabled(list.isEnabled());
* setFont(list.getFont());
* setOpaque(true);
* return this;
* }
* }
*
* myList.setCellRenderer(new MyCellRenderer());
* </pre>
* <p>
* Another job for the cell renderer is in helping to determine sizing
* information for the list. By default, the list's {@code ListUI} determines
* the size of cells by asking the cell renderer for its preferred
* size for each list item. This can be expensive for large lists of items.
* To avoid these calculations, you can set a {@code fixedCellWidth} and
* {@code fixedCellHeight} on the list, or have these values calculated
* automatically based on a single prototype value:
* <a name="prototype_example">
* <pre>
* JList bigDataList = new JList(bigData);
*
* // We don't want the JList implementation to compute the width
* // or height of all of the list cells, so we give it a string
* // that's as big as we'll need for any cell. It uses this to
* // compute values for the fixedCellWidth and fixedCellHeight
* // properties.
*
* bigDataList.setPrototypeCellValue("Index 1234567890");
* </pre>
* <p>
* {@code JList} doesn't implement scrolling directly. To create a list that
* scrolls, make it the viewport view of a {@code JScrollPane}. For example:
* <pre>
* JScrollPane scrollPane = new JScrollPane(myList);
*
* // Or in two steps:
* JScrollPane scrollPane = new JScrollPane();
* scrollPane.getViewport().setView(myList);
* </pre>
* <p>
* {@code JList} doesn't provide any special handling of double or triple
* (or N) mouse clicks, but it's easy to add a {@code MouseListener} if you
* wish to take action on these events. Use the {@code locationToIndex}
* method to determine what cell was clicked. For example:
* <pre>
* MouseListener mouseListener = new MouseAdapter() {
* public void mouseClicked(MouseEvent e) {
* if (e.getClickCount() == 2) {
* int index = list.locationToIndex(e.getPoint());
* System.out.println("Double clicked on Item " + index);
* }
* }
* };
* list.addMouseListener(mouseListener);
* </pre>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/list.html">How to Use Lists</a>
* in <a href="http://java.sun.com/Series/Tutorial/index.html"><em>The Java Tutorial</em></a>
* for further documentation.
* Also see the article <a href="http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html">Advanced JList Programming</a>
* in <a href="http://java.sun.com/products/jfc/tsc"><em>The Swing Connection</em></a>.
* <p>
* @see ListModel
* @see AbstractListModel
* @see DefaultListModel
* @see ListSelectionModel
* @see DefaultListSelectionModel
* @see ListCellRenderer
* @see DefaultListCellRenderer
*
* @beaninfo
* attribute: isContainer false
* description: A component which allows for the selection of one or more objects from a list.
*
* @author Hans Muller
*/
public class JList extends JComponent implements Scrollable, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ListUI";
/** {@collect.stats}
* Indicates a vertical layout of cells, in a single column;
* the default layout.
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int VERTICAL = 0;
/** {@collect.stats}
* Indicates a "newspaper style" layout with cells flowing vertically
* then horizontally.
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int VERTICAL_WRAP = 1;
/** {@collect.stats}
* Indicates a "newspaper style" layout with cells flowing horizontally
* then vertically.
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int HORIZONTAL_WRAP = 2;
private int fixedCellWidth = -1;
private int fixedCellHeight = -1;
private int horizontalScrollIncrement = -1;
private Object prototypeCellValue;
private int visibleRowCount = 8;
private Color selectionForeground;
private Color selectionBackground;
private boolean dragEnabled;
private ListSelectionModel selectionModel;
private ListModel dataModel;
private ListCellRenderer cellRenderer;
private ListSelectionListener selectionListener;
/** {@collect.stats}
* How to lay out the cells; defaults to <code>VERTICAL</code>.
*/
private int layoutOrientation;
/** {@collect.stats}
* The drop mode for this component.
*/
private DropMode dropMode = DropMode.USE_SELECTION;
/** {@collect.stats}
* The drop location.
*/
private transient DropLocation dropLocation;
/** {@collect.stats}
* A subclass of <code>TransferHandler.DropLocation</code> representing
* a drop location for a <code>JList</code>.
*
* @see #getDropLocation
* @since 1.6
*/
public static final class DropLocation extends TransferHandler.DropLocation {
private final int index;
private final boolean isInsert;
private DropLocation(Point p, int index, boolean isInsert) {
super(p);
this.index = index;
this.isInsert = isInsert;
}
/** {@collect.stats}
* Returns the index where dropped data should be placed in the
* list. Interpretation of the value depends on the drop mode set on
* the associated component. If the drop mode is either
* <code>DropMode.USE_SELECTION</code> or <code>DropMode.ON</code>,
* the return value is an index of a row in the list. If the drop mode is
* <code>DropMode.INSERT</code>, the return value refers to the index
* where the data should be inserted. If the drop mode is
* <code>DropMode.ON_OR_INSERT</code>, the value of
* <code>isInsert()</code> indicates whether the index is an index
* of a row, or an insert index.
* <p>
* <code>-1</code> indicates that the drop occurred over empty space,
* and no index could be calculated.
*
* @return the drop index
*/
public int getIndex() {
return index;
}
/** {@collect.stats}
* Returns whether or not this location represents an insert
* location.
*
* @return whether or not this is an insert location
*/
public boolean isInsert() {
return isInsert;
}
/** {@collect.stats}
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName()
+ "[dropPoint=" + getDropPoint() + ","
+ "index=" + index + ","
+ "insert=" + isInsert + "]";
}
}
/** {@collect.stats}
* Constructs a {@code JList} that displays elements from the specified,
* {@code non-null}, model. All {@code JList} constructors delegate to
* this one.
* <p>
* This constructor registers the list with the {@code ToolTipManager},
* allowing for tooltips to be provided by the cell renderers.
*
* @param dataModel the model for the list
* @exception IllegalArgumentException if the model is {@code null}
*/
public JList(ListModel dataModel)
{
if (dataModel == null) {
throw new IllegalArgumentException("dataModel must be non null");
}
// Register with the ToolTipManager so that tooltips from the
// renderer show through.
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(this);
layoutOrientation = VERTICAL;
this.dataModel = dataModel;
selectionModel = createSelectionModel();
setAutoscrolls(true);
setOpaque(true);
updateUI();
}
/** {@collect.stats}
* Constructs a <code>JList</code> that displays the elements in
* the specified array. This constructor creates a read-only model
* for the given array, and then delegates to the constructor that
* takes a {@code ListModel}.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given array directly. Attempts to modify the array
* after constructing the list results in undefined behavior.
*
* @param listData the array of Objects to be loaded into the data model,
* {@code non-null}
*/
public JList(final Object[] listData)
{
this (
new AbstractListModel() {
public int getSize() { return listData.length; }
public Object getElementAt(int i) { return listData[i]; }
}
);
}
/** {@collect.stats}
* Constructs a <code>JList</code> that displays the elements in
* the specified <code>Vector</code>. This constructor creates a read-only
* model for the given {@code Vector}, and then delegates to the constructor
* that takes a {@code ListModel}.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given {@code Vector} directly. Attempts to modify the
* {@code Vector} after constructing the list results in undefined behavior.
*
* @param listData the <code>Vector</code> to be loaded into the
* data model, {@code non-null}
*/
public JList(final Vector<?> listData) {
this (
new AbstractListModel() {
public int getSize() { return listData.size(); }
public Object getElementAt(int i) { return listData.elementAt(i); }
}
);
}
/** {@collect.stats}
* Constructs a <code>JList</code> with an empty, read-only, model.
*/
public JList() {
this (
new AbstractListModel() {
public int getSize() { return 0; }
public Object getElementAt(int i) { return "No Data Model"; }
}
);
}
/** {@collect.stats}
* Returns the {@code ListUI}, the look and feel object that
* renders this component.
*
* @return the <code>ListUI</code> object that renders this component
*/
public ListUI getUI() {
return (ListUI)ui;
}
/** {@collect.stats}
* Sets the {@code ListUI}, the look and feel object that
* renders this component.
*
* @param ui the <code>ListUI</code> object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(ListUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Resets the {@code ListUI} property by setting it to the value provided
* by the current look and feel. If the current cell renderer was installed
* by the developer (rather than the look and feel itself), this also causes
* the cell renderer and its children to be updated, by calling
* {@code SwingUtilities.updateComponentTreeUI} on it.
*
* @see UIManager#getUI
* @see SwingUtilities#updateComponentTreeUI
*/
public void updateUI() {
setUI((ListUI)UIManager.getUI(this));
ListCellRenderer renderer = getCellRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
}
/** {@collect.stats}
* Returns {@code "ListUI"}, the <code>UIDefaults</code> key used to look
* up the name of the {@code javax.swing.plaf.ListUI} class that defines
* the look and feel for this component.
*
* @return the string "ListUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/* -----private-----
* This method is called by setPrototypeCellValue and setCellRenderer
* to update the fixedCellWidth and fixedCellHeight properties from the
* current value of prototypeCellValue (if it's non null).
* <p>
* This method sets fixedCellWidth and fixedCellHeight but does <b>not</b>
* generate PropertyChangeEvents for them.
*
* @see #setPrototypeCellValue
* @see #setCellRenderer
*/
private void updateFixedCellSize()
{
ListCellRenderer cr = getCellRenderer();
Object value = getPrototypeCellValue();
if ((cr != null) && (value != null)) {
Component c = cr.getListCellRendererComponent(this, value, 0, false, false);
/* The ListUI implementation will add Component c to its private
* CellRendererPane however we can't assume that's already
* been done here. So we temporarily set the one "inherited"
* property that may affect the renderer components preferred size:
* its font.
*/
Font f = c.getFont();
c.setFont(getFont());
Dimension d = c.getPreferredSize();
fixedCellWidth = d.width;
fixedCellHeight = d.height;
c.setFont(f);
}
}
/** {@collect.stats}
* Returns the "prototypical" cell value -- a value used to calculate a
* fixed width and height for cells. This can be {@code null} if there
* is no such value.
*
* @return the value of the {@code prototypeCellValue} property
* @see #setPrototypeCellValue
*/
public Object getPrototypeCellValue() {
return prototypeCellValue;
}
/** {@collect.stats}
* Sets the {@code prototypeCellValue} property, and then (if the new value
* is {@code non-null}), computes the {@code fixedCellWidth} and
* {@code fixedCellHeight} properties by requesting the cell renderer
* component for the given value (and index 0) from the cell renderer, and
* using that component's preferred size.
* <p>
* This method is useful when the list is too long to allow the
* {@code ListUI} to compute the width/height of each cell, and there is a
* single cell value that is known to occupy as much space as any of the
* others, a so-called prototype.
* <p>
* While all three of the {@code prototypeCellValue},
* {@code fixedCellHeight}, and {@code fixedCellWidth} properties may be
* modified by this method, {@code PropertyChangeEvent} notifications are
* only sent when the {@code prototypeCellValue} property changes.
* <p>
* To see an example which sets this property, see the
* <a href="#prototype_example">class description</a> above.
* <p>
* The default value of this property is <code>null</code>.
* <p>
* This is a JavaBeans bound property.
*
* @param prototypeCellValue the value on which to base
* <code>fixedCellWidth</code> and
* <code>fixedCellHeight</code>
* @see #getPrototypeCellValue
* @see #setFixedCellWidth
* @see #setFixedCellHeight
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The cell prototype value, used to compute cell width and height.
*/
public void setPrototypeCellValue(Object prototypeCellValue) {
Object oldValue = this.prototypeCellValue;
this.prototypeCellValue = prototypeCellValue;
/* If the prototypeCellValue has changed and is non-null,
* then recompute fixedCellWidth and fixedCellHeight.
*/
if ((prototypeCellValue != null) && !prototypeCellValue.equals(oldValue)) {
updateFixedCellSize();
}
firePropertyChange("prototypeCellValue", oldValue, prototypeCellValue);
}
/** {@collect.stats}
* Returns the value of the {@code fixedCellWidth} property.
*
* @return the fixed cell width
* @see #setFixedCellWidth
*/
public int getFixedCellWidth() {
return fixedCellWidth;
}
/** {@collect.stats}
* Sets a fixed value to be used for the width of every cell in the list.
* If {@code width} is -1, cell widths are computed in the {@code ListUI}
* by applying <code>getPreferredSize</code> to the cell renderer component
* for each list element.
* <p>
* The default value of this property is {@code -1}.
* <p>
* This is a JavaBeans bound property.
*
* @param width the width to be used for all cells in the list
* @see #setPrototypeCellValue
* @see #setFixedCellWidth
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines a fixed cell width when greater than zero.
*/
public void setFixedCellWidth(int width) {
int oldValue = fixedCellWidth;
fixedCellWidth = width;
firePropertyChange("fixedCellWidth", oldValue, fixedCellWidth);
}
/** {@collect.stats}
* Returns the value of the {@code fixedCellHeight} property.
*
* @return the fixed cell height
* @see #setFixedCellHeight
*/
public int getFixedCellHeight() {
return fixedCellHeight;
}
/** {@collect.stats}
* Sets a fixed value to be used for the height of every cell in the list.
* If {@code height} is -1, cell heights are computed in the {@code ListUI}
* by applying <code>getPreferredSize</code> to the cell renderer component
* for each list element.
* <p>
* The default value of this property is {@code -1}.
* <p>
* This is a JavaBeans bound property.
*
* @param height the height to be used for for all cells in the list
* @see #setPrototypeCellValue
* @see #setFixedCellWidth
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines a fixed cell height when greater than zero.
*/
public void setFixedCellHeight(int height) {
int oldValue = fixedCellHeight;
fixedCellHeight = height;
firePropertyChange("fixedCellHeight", oldValue, fixedCellHeight);
}
/** {@collect.stats}
* Returns the object responsible for painting list items.
*
* @return the value of the {@code cellRenderer} property
* @see #setCellRenderer
*/
public ListCellRenderer getCellRenderer() {
return cellRenderer;
}
/** {@collect.stats}
* Sets the delegate that is used to paint each cell in the list.
* The job of a cell renderer is discussed in detail in the
* <a href="#renderer">class level documentation</a>.
* <p>
* If the {@code prototypeCellValue} property is {@code non-null},
* setting the cell renderer also causes the {@code fixedCellWidth} and
* {@code fixedCellHeight} properties to be re-calculated. Only one
* <code>PropertyChangeEvent</code> is generated however -
* for the <code>cellRenderer</code> property.
* <p>
* The default value of this property is provided by the {@code ListUI}
* delegate, i.e. by the look and feel implementation.
* <p>
* This is a JavaBeans bound property.
*
* @param cellRenderer the <code>ListCellRenderer</code>
* that paints list cells
* @see #getCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The component used to draw the cells.
*/
public void setCellRenderer(ListCellRenderer cellRenderer) {
ListCellRenderer oldValue = this.cellRenderer;
this.cellRenderer = cellRenderer;
/* If the cellRenderer has changed and prototypeCellValue
* was set, then recompute fixedCellWidth and fixedCellHeight.
*/
if ((cellRenderer != null) && !cellRenderer.equals(oldValue)) {
updateFixedCellSize();
}
firePropertyChange("cellRenderer", oldValue, cellRenderer);
}
/** {@collect.stats}
* Returns the color used to draw the foreground of selected items.
* {@code DefaultListCellRenderer} uses this color to draw the foreground
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
*
* @return the color to draw the foreground of selected items
* @see #setSelectionForeground
* @see DefaultListCellRenderer
*/
public Color getSelectionForeground() {
return selectionForeground;
}
/** {@collect.stats}
* Sets the color used to draw the foreground of selected items, which
* cell renderers can use to render text and graphics.
* {@code DefaultListCellRenderer} uses this color to draw the foreground
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
* <p>
* The default value of this property is defined by the look and feel
* implementation.
* <p>
* This is a JavaBeans bound property.
*
* @param selectionForeground the {@code Color} to use in the foreground
* for selected list items
* @see #getSelectionForeground
* @see #setSelectionBackground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @see DefaultListCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The foreground color of selected cells.
*/
public void setSelectionForeground(Color selectionForeground) {
Color oldValue = this.selectionForeground;
this.selectionForeground = selectionForeground;
firePropertyChange("selectionForeground", oldValue, selectionForeground);
}
/** {@collect.stats}
* Returns the color used to draw the background of selected items.
* {@code DefaultListCellRenderer} uses this color to draw the background
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
*
* @return the color to draw the background of selected items
* @see #setSelectionBackground
* @see DefaultListCellRenderer
*/
public Color getSelectionBackground() {
return selectionBackground;
}
/** {@collect.stats}
* Sets the color used to draw the background of selected items, which
* cell renderers can use fill selected cells.
* {@code DefaultListCellRenderer} uses this color to fill the background
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
* <p>
* The default value of this property is defined by the look
* and feel implementation.
* <p>
* This is a JavaBeans bound property.
*
* @param selectionBackground the {@code Color} to use for the
* background of selected cells
* @see #getSelectionBackground
* @see #setSelectionForeground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @see DefaultListCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The background color of selected cells.
*/
public void setSelectionBackground(Color selectionBackground) {
Color oldValue = this.selectionBackground;
this.selectionBackground = selectionBackground;
firePropertyChange("selectionBackground", oldValue, selectionBackground);
}
/** {@collect.stats}
* Returns the value of the {@code visibleRowCount} property. See the
* documentation for {@link #setVisibleRowCount} for details on how to
* interpret this value.
*
* @return the value of the {@code visibleRowCount} property.
* @see #setVisibleRowCount
*/
public int getVisibleRowCount() {
return visibleRowCount;
}
/** {@collect.stats}
* Sets the {@code visibleRowCount} property, which has different meanings
* depending on the layout orientation: For a {@code VERTICAL} layout
* orientation, this sets the preferred number of rows to display without
* requiring scrolling; for other orientations, it affects the wrapping of
* cells.
* <p>
* In {@code VERTICAL} orientation:<br>
* Setting this property affects the return value of the
* {@link #getPreferredScrollableViewportSize} method, which is used to
* calculate the preferred size of an enclosing viewport. See that method's
* documentation for more details.
* <p>
* In {@code HORIZONTAL_WRAP} and {@code VERTICAL_WRAP} orientations:<br>
* This affects how cells are wrapped. See the documentation of
* {@link #setLayoutOrientation} for more details.
* <p>
* The default value of this property is {@code 8}.
* <p>
* Calling this method with a negative value results in the property
* being set to {@code 0}.
* <p>
* This is a JavaBeans bound property.
*
* @param visibleRowCount an integer specifying the preferred number of
* rows to display without requiring scrolling
* @see #getVisibleRowCount
* @see #getPreferredScrollableViewportSize
* @see #setLayoutOrientation
* @see JComponent#getVisibleRect
* @see JViewport
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The preferred number of rows to display without
* requiring scrolling
*/
public void setVisibleRowCount(int visibleRowCount) {
int oldValue = this.visibleRowCount;
this.visibleRowCount = Math.max(0, visibleRowCount);
firePropertyChange("visibleRowCount", oldValue, visibleRowCount);
}
/** {@collect.stats}
* Returns the layout orientation property for the list: {@code VERTICAL}
* if the layout is a single column of cells, {@code VERTICAL_WRAP} if the
* layout is "newspaper style" with the content flowing vertically then
* horizontally, or {@code HORIZONTAL_WRAP} if the layout is "newspaper
* style" with the content flowing horizontally then vertically.
*
* @return the value of the {@code layoutOrientation} property
* @see #setLayoutOrientation
* @since 1.4
*/
public int getLayoutOrientation() {
return layoutOrientation;
}
/** {@collect.stats}
* Defines the way list cells are layed out. Consider a {@code JList}
* with five cells. Cells can be layed out in one of the following ways:
* <p>
* <pre>
* VERTICAL: 0
* 1
* 2
* 3
* 4
*
* HORIZONTAL_WRAP: 0 1 2
* 3 4
*
* VERTICAL_WRAP: 0 3
* 1 4
* 2
* </pre>
* <p>
* A description of these layouts follows:
*
* <table border="1"
* summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP">
* <tr><th><p align="left">Value</p></th><th><p align="left">Description</p></th></tr>
* <tr><td><code>VERTICAL</code>
* <td>Cells are layed out vertically in a single column.
* <tr><td><code>HORIZONTAL_WRAP</code>
* <td>Cells are layed out horizontally, wrapping to a new row as
* necessary. If the {@code visibleRowCount} property is less than
* or equal to zero, wrapping is determined by the width of the
* list; otherwise wrapping is done in such a way as to ensure
* {@code visibleRowCount} rows in the list.
* <tr><td><code>VERTICAL_WRAP</code>
* <td>Cells are layed out vertically, wrapping to a new column as
* necessary. If the {@code visibleRowCount} property is less than
* or equal to zero, wrapping is determined by the height of the
* list; otherwise wrapping is done at {@code visibleRowCount} rows.
* </table>
* <p>
* The default value of this property is <code>VERTICAL</code>.
*
* @param layoutOrientation the new layout orientation, one of:
* {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP}
* @see #getLayoutOrientation
* @see #setVisibleRowCount
* @see #getScrollableTracksViewportHeight
* @see #getScrollableTracksViewportWidth
* @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the
* allowable values
* @since 1.4
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines the way list cells are layed out.
* enum: VERTICAL JList.VERTICAL
* HORIZONTAL_WRAP JList.HORIZONTAL_WRAP
* VERTICAL_WRAP JList.VERTICAL_WRAP
*/
public void setLayoutOrientation(int layoutOrientation) {
int oldValue = this.layoutOrientation;
switch (layoutOrientation) {
case VERTICAL:
case VERTICAL_WRAP:
case HORIZONTAL_WRAP:
this.layoutOrientation = layoutOrientation;
firePropertyChange("layoutOrientation", oldValue, layoutOrientation);
break;
default:
throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP");
}
}
/** {@collect.stats}
* Returns the smallest list index that is currently visible.
* In a left-to-right {@code componentOrientation}, the first visible
* cell is found closest to the list's upper-left corner. In right-to-left
* orientation, it is found closest to the upper-right corner.
* If nothing is visible or the list is empty, {@code -1} is returned.
* Note that the returned cell may only be partially visible.
*
* @return the index of the first visible cell
* @see #getLastVisibleIndex
* @see JComponent#getVisibleRect
*/
public int getFirstVisibleIndex() {
Rectangle r = getVisibleRect();
int first;
if (this.getComponentOrientation().isLeftToRight()) {
first = locationToIndex(r.getLocation());
} else {
first = locationToIndex(new Point((r.x + r.width) - 1, r.y));
}
if (first != -1) {
Rectangle bounds = getCellBounds(first, first);
if (bounds != null) {
SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
if (bounds.width == 0 || bounds.height == 0) {
first = -1;
}
}
}
return first;
}
/** {@collect.stats}
* Returns the largest list index that is currently visible.
* If nothing is visible or the list is empty, {@code -1} is returned.
* Note that the returned cell may only be partially visible.
*
* @return the index of the last visible cell
* @see #getFirstVisibleIndex
* @see JComponent#getVisibleRect
*/
public int getLastVisibleIndex() {
boolean leftToRight = this.getComponentOrientation().isLeftToRight();
Rectangle r = getVisibleRect();
Point lastPoint;
if (leftToRight) {
lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1);
} else {
lastPoint = new Point(r.x, (r.y + r.height) - 1);
}
int location = locationToIndex(lastPoint);
if (location != -1) {
Rectangle bounds = getCellBounds(location, location);
if (bounds != null) {
SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
if (bounds.width == 0 || bounds.height == 0) {
// Try the top left(LTR) or top right(RTL) corner, and
// then go across checking each cell for HORIZONTAL_WRAP.
// Try the lower left corner, and then go across checking
// each cell for other list layout orientation.
boolean isHorizontalWrap =
(getLayoutOrientation() == HORIZONTAL_WRAP);
Point visibleLocation = isHorizontalWrap ?
new Point(lastPoint.x, r.y) :
new Point(r.x, lastPoint.y);
int last;
int visIndex = -1;
int lIndex = location;
location = -1;
do {
last = visIndex;
visIndex = locationToIndex(visibleLocation);
if (visIndex != -1) {
bounds = getCellBounds(visIndex, visIndex);
if (visIndex != lIndex && bounds != null &&
bounds.contains(visibleLocation)) {
location = visIndex;
if (isHorizontalWrap) {
visibleLocation.y = bounds.y + bounds.height;
if (visibleLocation.y >= lastPoint.y) {
// Past visible region, bail.
last = visIndex;
}
}
else {
visibleLocation.x = bounds.x + bounds.width;
if (visibleLocation.x >= lastPoint.x) {
// Past visible region, bail.
last = visIndex;
}
}
}
else {
last = visIndex;
}
}
} while (visIndex != -1 && last != visIndex);
}
}
}
return location;
}
/** {@collect.stats}
* Scrolls the list within an enclosing viewport to make the specified
* cell completely visible. This calls {@code scrollRectToVisible} with
* the bounds of the specified cell. For this method to work, the
* {@code JList} must be within a <code>JViewport</code>.
* <p>
* If the given index is outside the list's range of cells, this method
* results in nothing.
*
* @param index the index of the cell to make visible
* @see JComponent#scrollRectToVisible
* @see #getVisibleRect
*/
public void ensureIndexIsVisible(int index) {
Rectangle cellBounds = getCellBounds(index, index);
if (cellBounds != null) {
scrollRectToVisible(cellBounds);
}
}
/** {@collect.stats}
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* list's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the list's
* {@code ListUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* an item and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* list's {@code TransferHandler}.
*
* @param b whether or not to enable automatic drag handling
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/** {@collect.stats}
* Returns whether or not automatic drag handling is enabled.
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
/** {@collect.stats}
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of one of the other modes is recommended, however, for an
* improved user experience. <code>DropMode.ON</code>, for instance,
* offers similar behavior of showing items as selected, but does so without
* affecting the actual selection in the list.
* <p>
* <code>JList</code> supports the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.ON</code></li>
* <li><code>DropMode.INSERT</code></li>
* <li><code>DropMode.ON_OR_INSERT</code></li>
* </ul>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see TransferHandler
* @since 1.6
*/
public final void setDropMode(DropMode dropMode) {
if (dropMode != null) {
switch (dropMode) {
case USE_SELECTION:
case ON:
case INSERT:
case ON_OR_INSERT:
this.dropMode = dropMode;
return;
}
}
throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list");
}
/** {@collect.stats}
* Returns the drop mode for this component.
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
public final DropMode getDropMode() {
return dropMode;
}
/** {@collect.stats}
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
DropLocation dropLocationForPoint(Point p) {
DropLocation location = null;
Rectangle rect = null;
int index = locationToIndex(p);
if (index != -1) {
rect = getCellBounds(index, index);
}
switch(dropMode) {
case USE_SELECTION:
case ON:
location = new DropLocation(p,
(rect != null && rect.contains(p)) ? index : -1,
false);
break;
case INSERT:
if (index == -1) {
location = new DropLocation(p, getModel().getSize(), true);
break;
}
if (layoutOrientation == HORIZONTAL_WRAP) {
boolean ltr = getComponentOrientation().isLeftToRight();
if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
index++;
// special case for below all cells
} else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
index++;
}
} else {
if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
index++;
}
}
location = new DropLocation(p, index, true);
break;
case ON_OR_INSERT:
if (index == -1) {
location = new DropLocation(p, getModel().getSize(), true);
break;
}
boolean between = false;
if (layoutOrientation == HORIZONTAL_WRAP) {
boolean ltr = getComponentOrientation().isLeftToRight();
Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
if (section == TRAILING) {
index++;
between = true;
// special case for below all cells
} else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
index++;
between = true;
} else if (section == LEADING) {
between = true;
}
} else {
Section section = SwingUtilities2.liesInVertical(rect, p, true);
if (section == LEADING) {
between = true;
} else if (section == TRAILING) {
index++;
between = true;
}
}
location = new DropLocation(p, index, between);
break;
default:
assert false : "Unexpected drop mode";
}
return location;
}
/** {@collect.stats}
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
Object retVal = null;
DropLocation listLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (listLocation == null) {
if (!forDrop && state != null) {
setSelectedIndices(((int[][])state)[0]);
int anchor = ((int[][])state)[1][0];
int lead = ((int[][])state)[1][1];
SwingUtilities2.setLeadAnchorWithoutSelection(
getSelectionModel(), lead, anchor);
}
} else {
if (dropLocation == null) {
int[] inds = getSelectedIndices();
retVal = new int[][] {inds, {getAnchorSelectionIndex(),
getLeadSelectionIndex()}};
} else {
retVal = state;
}
int index = listLocation.getIndex();
if (index == -1) {
clearSelection();
getSelectionModel().setAnchorSelectionIndex(-1);
getSelectionModel().setLeadSelectionIndex(-1);
} else {
setSelectionInterval(index, index);
}
}
}
DropLocation old = dropLocation;
dropLocation = listLocation;
firePropertyChange("dropLocation", old, dropLocation);
return retVal;
}
/** {@collect.stats}
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
* <p>
* By default, responsibility for listening for changes to this property
* and indicating the drop location visually lies with the list's
* {@code ListUI}, which may paint it directly and/or install a cell
* renderer to do so. Developers wishing to implement custom drop location
* painting and/or replace the default cell renderer, may need to honor
* this property.
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public final DropLocation getDropLocation() {
return dropLocation;
}
/** {@collect.stats}
* Returns the next list element whose {@code toString} value
* starts with the given prefix.
*
* @param prefix the string to test for a match
* @param startIndex the index for starting the search
* @param bias the search direction, either
* Position.Bias.Forward or Position.Bias.Backward.
* @return the index of the next list element that
* starts with the prefix; otherwise {@code -1}
* @exception IllegalArgumentException if prefix is {@code null}
* or startIndex is out of bounds
* @since 1.4
*/
public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
ListModel model = getModel();
int max = model.getSize();
if (prefix == null) {
throw new IllegalArgumentException();
}
if (startIndex < 0 || startIndex >= max) {
throw new IllegalArgumentException();
}
prefix = prefix.toUpperCase();
// start search from the next element after the selected element
int increment = (bias == Position.Bias.Forward) ? 1 : -1;
int index = startIndex;
do {
Object o = model.getElementAt(index);
if (o != null) {
String string;
if (o instanceof String) {
string = ((String)o).toUpperCase();
}
else {
string = o.toString();
if (string != null) {
string = string.toUpperCase();
}
}
if (string != null && string.startsWith(prefix)) {
return index;
}
}
index = (index + increment + max) % max;
} while (index != startIndex);
return -1;
}
/** {@collect.stats}
* Returns the tooltip text to be used for the given event. This overrides
* {@code JComponent}'s {@code getToolTipText} to first check the cell
* renderer component for the cell over which the event occurred, returning
* its tooltip text, if any. This implementation allows you to specify
* tooltip text on the cell level, by using {@code setToolTipText} on your
* cell renderer component.
* <p>
* <bold>Note:</bold> For <code>JList</code> to properly display the
* tooltips of its renderers in this manner, <code>JList</code> must be a
* registered component with the <code>ToolTipManager</code>. This registration
* is done automatically in the constructor. However, if at a later point
* <code>JList</code> is unregistered, by way of a call to
* {@code setToolTipText(null)}, tips from the renderers will no longer display.
*
* @param event the {@code MouseEvent} to fetch the tooltip text for
* @see JComponent#setToolTipText
* @see JComponent#getToolTipText
*/
public String getToolTipText(MouseEvent event) {
if(event != null) {
Point p = event.getPoint();
int index = locationToIndex(p);
ListCellRenderer r = getCellRenderer();
Rectangle cellBounds;
if (index != -1 && r != null && (cellBounds =
getCellBounds(index, index)) != null &&
cellBounds.contains(p.x, p.y)) {
ListSelectionModel lsm = getSelectionModel();
Component rComponent = r.getListCellRendererComponent(
this, getModel().getElementAt(index), index,
lsm.isSelectedIndex(index),
(hasFocus() && (lsm.getLeadSelectionIndex() ==
index)));
if(rComponent instanceof JComponent) {
MouseEvent newEvent;
p.translate(-cellBounds.x, -cellBounds.y);
newEvent = new MouseEvent(rComponent, event.getID(),
event.getWhen(),
event.getModifiers(),
p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
String tip = ((JComponent)rComponent).getToolTipText(
newEvent);
if (tip != null) {
return tip;
}
}
}
}
return super.getToolTipText();
}
/** {@collect.stats}
* --- ListUI Delegations ---
*/
/** {@collect.stats}
* Returns the cell index closest to the given location in the list's
* coordinate system. To determine if the cell actually contains the
* specified location, compare the point against the cell's bounds,
* as provided by {@code getCellBounds}. This method returns {@code -1}
* if the model is empty
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code -1} if the list has
* no {@code ListUI}.
*
* @param location the coordinates of the point
* @return the cell index closest to the given location, or {@code -1}
*/
public int locationToIndex(Point location) {
ListUI ui = getUI();
return (ui != null) ? ui.locationToIndex(this, location) : -1;
}
/** {@collect.stats}
* Returns the origin of the specified item in the list's coordinate
* system. This method returns {@code null} if the index isn't valid.
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code null} if the list has
* no {@code ListUI}.
*
* @param index the cell index
* @return the origin of the cell, or {@code null}
*/
public Point indexToLocation(int index) {
ListUI ui = getUI();
return (ui != null) ? ui.indexToLocation(this, index) : null;
}
/** {@collect.stats}
* Returns the bounding rectangle, in the list's coordinate system,
* for the range of cells specified by the two indices.
* These indices can be supplied in any order.
* <p>
* If the smaller index is outside the list's range of cells, this method
* returns {@code null}. If the smaller index is valid, but the larger
* index is outside the list's range, the bounds of just the first index
* is returned. Otherwise, the bounds of the valid range is returned.
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code null} if the list has
* no {@code ListUI}.
*
* @param index0 the first index in the range
* @param index1 the second index in the range
* @return the bounding rectangle for the range of cells, or {@code null}
*/
public Rectangle getCellBounds(int index0, int index1) {
ListUI ui = getUI();
return (ui != null) ? ui.getCellBounds(this, index0, index1) : null;
}
/** {@collect.stats}
* --- ListModel Support ---
*/
/** {@collect.stats}
* Returns the data model that holds the list of items displayed
* by the <code>JList</code> component.
*
* @return the <code>ListModel</code> that provides the displayed
* list of items
* @see #setModel
*/
public ListModel getModel() {
return dataModel;
}
/** {@collect.stats}
* Sets the model that represents the contents or "value" of the
* list, notifies property change listeners, and then clears the
* list's selection.
* <p>
* This is a JavaBeans bound property.
*
* @param model the <code>ListModel</code> that provides the
* list of items for display
* @exception IllegalArgumentException if <code>model</code> is
* <code>null</code>
* @see #getModel
* @see #clearSelection
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The object that contains the data to be drawn by this JList.
*/
public void setModel(ListModel model) {
if (model == null) {
throw new IllegalArgumentException("model must be non null");
}
ListModel oldValue = dataModel;
dataModel = model;
firePropertyChange("model", oldValue, dataModel);
clearSelection();
}
/** {@collect.stats}
* Constructs a read-only <code>ListModel</code> from an array of objects,
* and calls {@code setModel} with this model.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given array directly. Attempts to modify the array
* after invoking this method results in undefined behavior.
*
* @param listData an array of {@code Objects} containing the items to
* display in the list
* @see #setModel
*/
public void setListData(final Object[] listData) {
setModel (
new AbstractListModel() {
public int getSize() { return listData.length; }
public Object getElementAt(int i) { return listData[i]; }
}
);
}
/** {@collect.stats}
* Constructs a read-only <code>ListModel</code> from a <code>Vector</code>
* and calls {@code setModel} with this model.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given {@code Vector} directly. Attempts to modify the
* {@code Vector} after invoking this method results in undefined behavior.
*
* @param listData a <code>Vector</code> containing the items to
* display in the list
* @see #setModel
*/
public void setListData(final Vector<?> listData) {
setModel (
new AbstractListModel() {
public int getSize() { return listData.size(); }
public Object getElementAt(int i) { return listData.elementAt(i); }
}
);
}
/** {@collect.stats}
* --- ListSelectionModel delegations and extensions ---
*/
/** {@collect.stats}
* Returns an instance of {@code DefaultListSelectionModel}; called
* during construction to initialize the list's selection model
* property.
*
* @return a {@code DefaultListSelecitonModel}, used to initialize
* the list's selection model property during construction
* @see #setSelectionModel
* @see DefaultListSelectionModel
*/
protected ListSelectionModel createSelectionModel() {
return new DefaultListSelectionModel();
}
/** {@collect.stats}
* Returns the current selection model. The selection model maintains the
* selection state of the list. See the class level documentation for more
* details.
*
* @return the <code>ListSelectionModel</code> that maintains the
* list's selections
*
* @see #setSelectionModel
* @see ListSelectionModel
*/
public ListSelectionModel getSelectionModel() {
return selectionModel;
}
/** {@collect.stats}
* Notifies {@code ListSelectionListener}s added directly to the list
* of selection changes made to the selection model. {@code JList}
* listens for changes made to the selection in the selection model,
* and forwards notification to listeners added to the list directly,
* by calling this method.
* <p>
* This method constructs a {@code ListSelectionEvent} with this list
* as the source, and the specified arguments, and sends it to the
* registered {@code ListSelectionListeners}.
*
* @param firstIndex the first index in the range, {@code <= lastIndex}
* @param lastIndex the last index in the range, {@code >= firstIndex}
* @param isAdjusting whether or not this is one in a series of
* multiple events, where changes are still being made
*
* @see #addListSelectionListener
* @see #removeListSelectionListener
* @see javax.swing.event.ListSelectionEvent
* @see EventListenerList
*/
protected void fireSelectionValueChanged(int firstIndex, int lastIndex,
boolean isAdjusting)
{
Object[] listeners = listenerList.getListenerList();
ListSelectionEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListSelectionListener.class) {
if (e == null) {
e = new ListSelectionEvent(this, firstIndex, lastIndex,
isAdjusting);
}
((ListSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
/* A ListSelectionListener that forwards ListSelectionEvents from
* the selectionModel to the JList ListSelectionListeners. The
* forwarded events only differ from the originals in that their
* source is the JList instead of the selectionModel itself.
*/
private class ListSelectionHandler implements ListSelectionListener, Serializable
{
public void valueChanged(ListSelectionEvent e) {
fireSelectionValueChanged(e.getFirstIndex(),
e.getLastIndex(),
e.getValueIsAdjusting());
}
}
/** {@collect.stats}
* Adds a listener to the list, to be notified each time a change to the
* selection occurs; the preferred way of listening for selection state
* changes. {@code JList} takes care of listening for selection state
* changes in the selection model, and notifies the given listener of
* each change. {@code ListSelectionEvent}s sent to the listener have a
* {@code source} property set to this list.
*
* @param listener the {@code ListSelectionListener} to add
* @see #getSelectionModel
* @see #getListSelectionListeners
*/
public void addListSelectionListener(ListSelectionListener listener)
{
if (selectionListener == null) {
selectionListener = new ListSelectionHandler();
getSelectionModel().addListSelectionListener(selectionListener);
}
listenerList.add(ListSelectionListener.class, listener);
}
/** {@collect.stats}
* Removes a selection listener from the list.
*
* @param listener the {@code ListSelectionListener} to remove
* @see #addListSelectionListener
* @see #getSelectionModel
*/
public void removeListSelectionListener(ListSelectionListener listener) {
listenerList.remove(ListSelectionListener.class, listener);
}
/** {@collect.stats}
* Returns an array of all the {@code ListSelectionListener}s added
* to this {@code JList} by way of {@code addListSelectionListener}.
*
* @return all of the {@code ListSelectionListener}s on this list, or
* an empty array if no listeners have been added
* @see #addListSelectionListener
* @since 1.4
*/
public ListSelectionListener[] getListSelectionListeners() {
return (ListSelectionListener[])listenerList.getListeners(
ListSelectionListener.class);
}
/** {@collect.stats}
* Sets the <code>selectionModel</code> for the list to a
* non-<code>null</code> <code>ListSelectionModel</code>
* implementation. The selection model handles the task of making single
* selections, selections of contiguous ranges, and non-contiguous
* selections.
* <p>
* This is a JavaBeans bound property.
*
* @param selectionModel the <code>ListSelectionModel</code> that
* implements the selections
* @exception IllegalArgumentException if <code>selectionModel</code>
* is <code>null</code>
* @see #getSelectionModel
* @beaninfo
* bound: true
* description: The selection model, recording which cells are selected.
*/
public void setSelectionModel(ListSelectionModel selectionModel) {
if (selectionModel == null) {
throw new IllegalArgumentException("selectionModel must be non null");
}
/* Remove the forwarding ListSelectionListener from the old
* selectionModel, and add it to the new one, if necessary.
*/
if (selectionListener != null) {
this.selectionModel.removeListSelectionListener(selectionListener);
selectionModel.addListSelectionListener(selectionListener);
}
ListSelectionModel oldValue = this.selectionModel;
this.selectionModel = selectionModel;
firePropertyChange("selectionModel", oldValue, selectionModel);
}
/** {@collect.stats}
* Sets the selection mode for the list. This is a cover method that sets
* the selection mode directly on the selection model.
* <p>
* The following list describes the accepted selection modes:
* <ul>
* <li>{@code ListSelectionModel.SINGLE_SELECTION} -
* Only one list index can be selected at a time. In this mode,
* {@code setSelectionInterval} and {@code addSelectionInterval} are
* equivalent, both replacing the current selection with the index
* represented by the second argument (the "lead").
* <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
* Only one contiguous interval can be selected at a time.
* In this mode, {@code addSelectionInterval} behaves like
* {@code setSelectionInterval} (replacing the current selection},
* unless the given interval is immediately adjacent to or overlaps
* the existing selection, and can be used to grow the selection.
* <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
* In this mode, there's no restriction on what can be selected.
* This mode is the default.
* </ul>
*
* @param selectionMode the selection mode
* @see #getSelectionMode
* @throws IllegalArgumentException if the selection mode isn't
* one of those allowed
* @beaninfo
* description: The selection mode.
* enum: SINGLE_SELECTION ListSelectionModel.SINGLE_SELECTION
* SINGLE_INTERVAL_SELECTION ListSelectionModel.SINGLE_INTERVAL_SELECTION
* MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
*/
public void setSelectionMode(int selectionMode) {
getSelectionModel().setSelectionMode(selectionMode);
}
/** {@collect.stats}
* Returns the current selection mode for the list. This is a cover
* method that delegates to the method of the same name on the
* list's selection model.
*
* @return the current selection mode
* @see #setSelectionMode
*/
public int getSelectionMode() {
return getSelectionModel().getSelectionMode();
}
/** {@collect.stats}
* Returns the anchor selection index. This is a cover method that
* delegates to the method of the same name on the list's selection model.
*
* @return the anchor selection index
* @see ListSelectionModel#getAnchorSelectionIndex
*/
public int getAnchorSelectionIndex() {
return getSelectionModel().getAnchorSelectionIndex();
}
/** {@collect.stats}
* Returns the lead selection index. This is a cover method that
* delegates to the method of the same name on the list's selection model.
*
* @return the lead selection index
* @see ListSelectionModel#getLeadSelectionIndex
* @beaninfo
* description: The lead selection index.
*/
public int getLeadSelectionIndex() {
return getSelectionModel().getLeadSelectionIndex();
}
/** {@collect.stats}
* Returns the smallest selected cell index, or {@code -1} if the selection
* is empty. This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* @return the smallest selected cell index, or {@code -1}
* @see ListSelectionModel#getMinSelectionIndex
*/
public int getMinSelectionIndex() {
return getSelectionModel().getMinSelectionIndex();
}
/** {@collect.stats}
* Returns the largest selected cell index, or {@code -1} if the selection
* is empty. This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* @return the largest selected cell index
* @see ListSelectionModel#getMaxSelectionIndex
*/
public int getMaxSelectionIndex() {
return getSelectionModel().getMaxSelectionIndex();
}
/** {@collect.stats}
* Returns {@code true} if the specified index is selected,
* else {@code false}. This is a cover method that delegates to the method
* of the same name on the list's selection model.
*
* @param index index to be queried for selection state
* @return {@code true} if the specified index is selected,
* else {@code false}
* @see ListSelectionModel#isSelectedIndex
* @see #setSelectedIndex
*/
public boolean isSelectedIndex(int index) {
return getSelectionModel().isSelectedIndex(index);
}
/** {@collect.stats}
* Returns {@code true} if nothing is selected, else {@code false}.
* This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* @return {@code true} if nothing is selected, else {@code false}
* @see ListSelectionModel#isSelectionEmpty
* @see #clearSelection
*/
public boolean isSelectionEmpty() {
return getSelectionModel().isSelectionEmpty();
}
/** {@collect.stats}
* Clears the selection; after calling this method, {@code isSelectionEmpty}
* will return {@code true}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
*
* @see ListSelectionModel#clearSelection
* @see #isSelectionEmpty
*/
public void clearSelection() {
getSelectionModel().clearSelection();
}
/** {@collect.stats}
* Selects the specified interval. Both {@code anchor} and {@code lead}
* indices are included. {@code anchor} doesn't have to be less than or
* equal to {@code lead}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* @param anchor the first index to select
* @param lead the last index to select
* @see ListSelectionModel#setSelectionInterval
* @see DefaultListSelectionModel#setSelectionInterval
* @see #createSelectionModel
* @see #addSelectionInterval
* @see #removeSelectionInterval
*/
public void setSelectionInterval(int anchor, int lead) {
getSelectionModel().setSelectionInterval(anchor, lead);
}
/** {@collect.stats}
* Sets the selection to be the union of the specified interval with current
* selection. Both the {@code anchor} and {@code lead} indices are
* included. {@code anchor} doesn't have to be less than or
* equal to {@code lead}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* @param anchor the first index to add to the selection
* @param lead the last index to add to the selection
* @see ListSelectionModel#addSelectionInterval
* @see DefaultListSelectionModel#addSelectionInterval
* @see #createSelectionModel
* @see #setSelectionInterval
* @see #removeSelectionInterval
*/
public void addSelectionInterval(int anchor, int lead) {
getSelectionModel().addSelectionInterval(anchor, lead);
}
/** {@collect.stats}
* Sets the selection to be the set difference of the specified interval
* and the current selection. Both the {@code index0} and {@code index1}
* indices are removed. {@code index0} doesn't have to be less than or
* equal to {@code index1}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* @param index0 the first index to remove from the selection
* @param index1 the last index to remove from the selection
* @see ListSelectionModel#removeSelectionInterval
* @see DefaultListSelectionModel#removeSelectionInterval
* @see #createSelectionModel
* @see #setSelectionInterval
* @see #addSelectionInterval
*/
public void removeSelectionInterval(int index0, int index1) {
getSelectionModel().removeSelectionInterval(index0, index1);
}
/** {@collect.stats}
* Sets the selection model's {@code valueIsAdjusting} property. When
* {@code true}, upcoming changes to selection should be considered part
* of a single change. This property is used internally and developers
* typically need not call this method. For example, when the model is being
* updated in response to a user drag, the value of the property is set
* to {@code true} when the drag is initiated and set to {@code false}
* when the drag is finished. This allows listeners to update only
* when a change has been finalized, rather than handling all of the
* intermediate values.
* <p>
* You may want to use this directly if making a series of changes
* that should be considered part of a single change.
* <p>
* This is a cover method that delegates to the method of the same name on
* the list's selection model. See the documentation for
* {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
* more details.
*
* @param b the new value for the property
* @see ListSelectionModel#setValueIsAdjusting
* @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
* @see #getValueIsAdjusting
*/
public void setValueIsAdjusting(boolean b) {
getSelectionModel().setValueIsAdjusting(b);
}
/** {@collect.stats}
* Returns the value of the selection model's {@code isAdjusting} property.
* <p>
* This is a cover method that delegates to the method of the same name on
* the list's selection model.
*
* @return the value of the selection model's {@code isAdjusting} property.
*
* @see #setValueIsAdjusting
* @see ListSelectionModel#getValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return getSelectionModel().getValueIsAdjusting();
}
/** {@collect.stats}
* Returns an array of all of the selected indices, in increasing
* order.
*
* @return all of the selected indices, in increasing order,
* or an empty array if nothing is selected
* @see #removeSelectionInterval
* @see #addListSelectionListener
*/
public int[] getSelectedIndices() {
ListSelectionModel sm = getSelectionModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return new int[0];
}
int[] rvTmp = new int[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
rvTmp[n++] = i;
}
}
int[] rv = new int[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
/** {@collect.stats}
* Selects a single cell. Does nothing if the given index is greater
* than or equal to the model size. This is a convenience method that uses
* {@code setSelectionInterval} on the selection model. Refer to the
* documentation for the selection model class being used for details on
* how values less than {@code 0} are handled.
*
* @param index the index of the cell to select
* @see ListSelectionModel#setSelectionInterval
* @see #isSelectedIndex
* @see #addListSelectionListener
* @beaninfo
* description: The index of the selected cell.
*/
public void setSelectedIndex(int index) {
if (index >= getModel().getSize()) {
return;
}
getSelectionModel().setSelectionInterval(index, index);
}
/** {@collect.stats}
* Changes the selection to be the set of indices specified by the given
* array. Indices greater than or equal to the model size are ignored.
* This is a convenience method that clears the selection and then uses
* {@code addSelectionInterval} on the selection model to add the indices.
* Refer to the documentation of the selection model class being used for
* details on how values less than {@code 0} are handled.
*
* @param indices an array of the indices of the cells to select,
* {@code non-null}
* @see ListSelectionModel#addSelectionInterval
* @see #isSelectedIndex
* @see #addListSelectionListener
* @throws NullPointerException if the given array is {@code null}
*/
public void setSelectedIndices(int[] indices) {
ListSelectionModel sm = getSelectionModel();
sm.clearSelection();
int size = getModel().getSize();
for(int i = 0; i < indices.length; i++) {
if (indices[i] < size) {
sm.addSelectionInterval(indices[i], indices[i]);
}
}
}
/** {@collect.stats}
* Returns an array of all the selected values, in increasing order based
* on their indices in the list.
*
* @return the selected values, or an empty array if nothing is selected
* @see #isSelectedIndex
* @see #getModel
* @see #addListSelectionListener
*/
public Object[] getSelectedValues() {
ListSelectionModel sm = getSelectionModel();
ListModel dm = getModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return new Object[0];
}
Object[] rvTmp = new Object[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
rvTmp[n++] = dm.getElementAt(i);
}
}
Object[] rv = new Object[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
/** {@collect.stats}
* Returns the smallest selected cell index; <i>the selection</i> when only
* a single item is selected in the list. When multiple items are selected,
* it is simply the smallest selected index. Returns {@code -1} if there is
* no selection.
* <p>
* This method is a cover that delegates to {@code getMinSelectionIndex}.
*
* @return the smallest selected cell index
* @see #getMinSelectionIndex
* @see #addListSelectionListener
*/
public int getSelectedIndex() {
return getMinSelectionIndex();
}
/** {@collect.stats}
* Returns the value for the smallest selected cell index;
* <i>the selected value</i> when only a single item is selected in the
* list. When multiple items are selected, it is simply the value for the
* smallest selected index. Returns {@code null} if there is no selection.
* <p>
* This is a convenience method that simply returns the model value for
* {@code getMinSelectionIndex}.
*
* @return the first selected value
* @see #getMinSelectionIndex
* @see #getModel
* @see #addListSelectionListener
*/
public Object getSelectedValue() {
int i = getMinSelectionIndex();
return (i == -1) ? null : getModel().getElementAt(i);
}
/** {@collect.stats}
* Selects the specified object from the list.
*
* @param anObject the object to select
* @param shouldScroll {@code true} if the list should scroll to display
* the selected object, if one exists; otherwise {@code false}
*/
public void setSelectedValue(Object anObject,boolean shouldScroll) {
if(anObject == null)
setSelectedIndex(-1);
else if(!anObject.equals(getSelectedValue())) {
int i,c;
ListModel dm = getModel();
for(i=0,c=dm.getSize();i<c;i++)
if(anObject.equals(dm.getElementAt(i))){
setSelectedIndex(i);
if(shouldScroll)
ensureIndexIsVisible(i);
repaint(); /** {@collect.stats} FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
return;
}
setSelectedIndex(-1);
}
repaint(); /** {@collect.stats} FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
}
/** {@collect.stats}
* --- The Scrollable Implementation ---
*/
private void checkScrollableParameters(Rectangle visibleRect, int orientation) {
if (visibleRect == null) {
throw new IllegalArgumentException("visibleRect must be non-null");
}
switch (orientation) {
case SwingConstants.VERTICAL:
case SwingConstants.HORIZONTAL:
break;
default:
throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
}
}
/** {@collect.stats}
* Computes the size of viewport needed to display {@code visibleRowCount}
* rows. The value returned by this method depends on the layout
* orientation:
* <p>
* <b>{@code VERTICAL}:</b>
* <br>
* This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight}
* have been set (either explicitly or by specifying a prototype cell value).
* The width is simply the {@code fixedCellWidth} plus the list's horizontal
* insets. The height is the {@code fixedCellHeight} multiplied by the
* {@code visibleRowCount}, plus the list's vertical insets.
* <p>
* If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been
* specified, heuristics are used. If the model is empty, the width is
* the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded
* value of {@code 256}. The height is the {@code fixedCellHeight} multiplied
* by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than
* {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by
* {@code visibleRowCount}.
* <p>
* If the model isn't empty, the width is the preferred size's width,
* typically the width of the widest list element. The height is the
* {@code fixedCellHeight} multiplied by the {@code visibleRowCount},
* plus the list's vertical insets.
* <p>
* <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b>
* <br>
* This method simply returns the value from {@code getPreferredSize}.
* The list's {@code ListUI} is expected to override {@code getPreferredSize}
* to return an appropriate value.
*
* @return a dimension containing the size of the viewport needed
* to display {@code visibleRowCount} rows
* @see #getPreferredScrollableViewportSize
* @see #setPrototypeCellValue
*/
public Dimension getPreferredScrollableViewportSize()
{
if (getLayoutOrientation() != VERTICAL) {
return getPreferredSize();
}
Insets insets = getInsets();
int dx = insets.left + insets.right;
int dy = insets.top + insets.bottom;
int visibleRowCount = getVisibleRowCount();
int fixedCellWidth = getFixedCellWidth();
int fixedCellHeight = getFixedCellHeight();
if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) {
int width = fixedCellWidth + dx;
int height = (visibleRowCount * fixedCellHeight) + dy;
return new Dimension(width, height);
}
else if (getModel().getSize() > 0) {
int width = getPreferredSize().width;
int height;
Rectangle r = getCellBounds(0, 0);
if (r != null) {
height = (visibleRowCount * r.height) + dy;
}
else {
// Will only happen if UI null, shouldn't matter what we return
height = 1;
}
return new Dimension(width, height);
}
else {
fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256;
fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16;
return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount);
}
}
/** {@collect.stats}
* Returns the distance to scroll to expose the next or previous
* row (for vertical scrolling) or column (for horizontal scrolling).
* <p>
* For horizontal scrolling, if the layout orientation is {@code VERTICAL},
* then the list's font size is returned (or {@code 1} if the font is
* {@code null}).
*
* @param visibleRect the view area visible within the viewport
* @param orientation {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstants.VERTICAL}
* @param direction less or equal to zero to scroll up/back,
* greater than zero for down/forward
* @return the "unit" increment for scrolling in the specified direction;
* always positive
* @see #getScrollableBlockIncrement
* @see Scrollable#getScrollableUnitIncrement
* @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
* {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}
*/
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
{
checkScrollableParameters(visibleRect, orientation);
if (orientation == SwingConstants.VERTICAL) {
int row = locationToIndex(visibleRect.getLocation());
if (row == -1) {
return 0;
}
else {
/* Scroll Down */
if (direction > 0) {
Rectangle r = getCellBounds(row, row);
return (r == null) ? 0 : r.height - (visibleRect.y - r.y);
}
/* Scroll Up */
else {
Rectangle r = getCellBounds(row, row);
/* The first row is completely visible and it's row 0.
* We're done.
*/
if ((r.y == visibleRect.y) && (row == 0)) {
return 0;
}
/* The first row is completely visible, return the
* height of the previous row or 0 if the first row
* is the top row of the list.
*/
else if (r.y == visibleRect.y) {
Point loc = r.getLocation();
loc.y--;
int prevIndex = locationToIndex(loc);
Rectangle prevR = getCellBounds(prevIndex, prevIndex);
if (prevR == null || prevR.y >= r.y) {
return 0;
}
return prevR.height;
}
/* The first row is partially visible, return the
* height of hidden part.
*/
else {
return visibleRect.y - r.y;
}
}
}
} else if (orientation == SwingConstants.HORIZONTAL &&
getLayoutOrientation() != JList.VERTICAL) {
boolean leftToRight = getComponentOrientation().isLeftToRight();
int index;
Point leadingPoint;
if (leftToRight) {
leadingPoint = visibleRect.getLocation();
}
else {
leadingPoint = new Point(visibleRect.x + visibleRect.width -1,
visibleRect.y);
}
index = locationToIndex(leadingPoint);
if (index != -1) {
Rectangle cellBounds = getCellBounds(index, index);
if (cellBounds != null && cellBounds.contains(leadingPoint)) {
int leadingVisibleEdge;
int leadingCellEdge;
if (leftToRight) {
leadingVisibleEdge = visibleRect.x;
leadingCellEdge = cellBounds.x;
}
else {
leadingVisibleEdge = visibleRect.x + visibleRect.width;
leadingCellEdge = cellBounds.x + cellBounds.width;
}
if (leadingCellEdge != leadingVisibleEdge) {
if (direction < 0) {
// Show remainder of leading cell
return Math.abs(leadingVisibleEdge - leadingCellEdge);
}
else if (leftToRight) {
// Hide rest of leading cell
return leadingCellEdge + cellBounds.width - leadingVisibleEdge;
}
else {
// Hide rest of leading cell
return leadingVisibleEdge - cellBounds.x;
}
}
// ASSUME: All cells are the same width
return cellBounds.width;
}
}
}
Font f = getFont();
return (f != null) ? f.getSize() : 1;
}
/** {@collect.stats}
* Returns the distance to scroll to expose the next or previous block.
* <p>
* For vertical scrolling, the following rules are used:
* <ul>
* <li>if scrolling down, returns the distance to scroll so that the last
* visible element becomes the first completely visible element
* <li>if scrolling up, returns the distance to scroll so that the first
* visible element becomes the last completely visible element
* <li>returns {@code visibleRect.height} if the list is empty
* </ul>
* <p>
* For horizontal scrolling, when the layout orientation is either
* {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:
* <ul>
* <li>if scrolling right, returns the distance to scroll so that the
* last visible element becomes
* the first completely visible element
* <li>if scrolling left, returns the distance to scroll so that the first
* visible element becomes the last completely visible element
* <li>returns {@code visibleRect.width} if the list is empty
* </ul>
* <p>
* For horizontal scrolling and {@code VERTICAL} orientation,
* returns {@code visibleRect.width}.
* <p>
* Note that the value of {@code visibleRect} must be the equal to
* {@code this.getVisibleRect()}.
*
* @param visibleRect the view area visible within the viewport
* @param orientation {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstants.VERTICAL}
* @param direction less or equal to zero to scroll up/back,
* greater than zero for down/forward
* @return the "block" increment for scrolling in the specified direction;
* always positive
* @see #getScrollableUnitIncrement
* @see Scrollable#getScrollableBlockIncrement
* @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
* {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}
*/
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
checkScrollableParameters(visibleRect, orientation);
if (orientation == SwingConstants.VERTICAL) {
int inc = visibleRect.height;
/* Scroll Down */
if (direction > 0) {
// last cell is the lowest left cell
int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1));
if (last != -1) {
Rectangle lastRect = getCellBounds(last,last);
if (lastRect != null) {
inc = lastRect.y - visibleRect.y;
if ( (inc == 0) && (last < getModel().getSize()-1) ) {
inc = lastRect.height;
}
}
}
}
/* Scroll Up */
else {
int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height));
int first = getFirstVisibleIndex();
if (newFirst != -1) {
if (first == -1) {
first = locationToIndex(visibleRect.getLocation());
}
Rectangle newFirstRect = getCellBounds(newFirst,newFirst);
Rectangle firstRect = getCellBounds(first,first);
if ((newFirstRect != null) && (firstRect!=null)) {
while ( (newFirstRect.y + visibleRect.height <
firstRect.y + firstRect.height) &&
(newFirstRect.y < firstRect.y) ) {
newFirst++;
newFirstRect = getCellBounds(newFirst,newFirst);
}
inc = visibleRect.y - newFirstRect.y;
if ( (inc <= 0) && (newFirstRect.y > 0)) {
newFirst--;
newFirstRect = getCellBounds(newFirst,newFirst);
if (newFirstRect != null) {
inc = visibleRect.y - newFirstRect.y;
}
}
}
}
}
return inc;
}
else if (orientation == SwingConstants.HORIZONTAL &&
getLayoutOrientation() != JList.VERTICAL) {
boolean leftToRight = getComponentOrientation().isLeftToRight();
int inc = visibleRect.width;
/* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */
if (direction > 0) {
// position is upper right if ltr, or upper left otherwise
int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0);
int last = locationToIndex(new Point(x, visibleRect.y));
if (last != -1) {
Rectangle lastRect = getCellBounds(last,last);
if (lastRect != null) {
if (leftToRight) {
inc = lastRect.x - visibleRect.x;
} else {
inc = visibleRect.x + visibleRect.width
- (lastRect.x + lastRect.width);
}
if (inc < 0) {
inc += lastRect.width;
} else if ( (inc == 0) && (last < getModel().getSize()-1) ) {
inc = lastRect.width;
}
}
}
}
/* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */
else {
// position is upper left corner of the visibleRect shifted
// left by the visibleRect.width if ltr, or upper right shifted
// right by the visibleRect.width otherwise
int x = visibleRect.x + (leftToRight
? -visibleRect.width
: visibleRect.width - 1 + visibleRect.width);
int first = locationToIndex(new Point(x, visibleRect.y));
if (first != -1) {
Rectangle firstRect = getCellBounds(first,first);
if (firstRect != null) {
// the right of the first cell
int firstRight = firstRect.x + firstRect.width;
if (leftToRight) {
if ((firstRect.x < visibleRect.x - visibleRect.width)
&& (firstRight < visibleRect.x)) {
inc = visibleRect.x - firstRight;
} else {
inc = visibleRect.x - firstRect.x;
}
} else {
int visibleRight = visibleRect.x + visibleRect.width;
if ((firstRight > visibleRight + visibleRect.width)
&& (firstRect.x > visibleRight)) {
inc = firstRect.x - visibleRight;
} else {
inc = firstRight - visibleRight;
}
}
}
}
}
return inc;
}
return visibleRect.width;
}
/** {@collect.stats}
* Returns {@code true} if this {@code JList} is displayed in a
* {@code JViewport} and the viewport is wider than the list's
* preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP}
* and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
* <p>
* If {@code false}, then don't track the viewport's width. This allows
* horizontal scrolling if the {@code JViewport} is itself embedded in a
* {@code JScrollPane}.
*
* @return whether or not an enclosing viewport should force the list's
* width to match its own
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
if (getLayoutOrientation() == HORIZONTAL_WRAP &&
getVisibleRowCount() <= 0) {
return true;
}
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
return false;
}
/** {@collect.stats}
* Returns {@code true} if this {@code JList} is displayed in a
* {@code JViewport} and the viewport is taller than the list's
* preferred height, or if the layout orientation is {@code VERTICAL_WRAP}
* and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
* <p>
* If {@code false}, then don't track the viewport's height. This allows
* vertical scrolling if the {@code JViewport} is itself embedded in a
* {@code JScrollPane}.
*
* @return whether or not an enclosing viewport should force the list's
* height to match its own
* @see Scrollable#getScrollableTracksViewportHeight
*/
public boolean getScrollableTracksViewportHeight() {
if (getLayoutOrientation() == VERTICAL_WRAP &&
getVisibleRowCount() <= 0) {
return true;
}
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
return false;
}
/*
* See {@code readObject} and {@code writeObject} in {@code JComponent}
* for more information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a {@code String} representation of this {@code JList}.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned {@code String} may vary
* between implementations. The returned {@code String} may be empty,
* but may not be {@code null}.
*
* @return a {@code String} representation of this {@code JList}.
*/
protected String paramString() {
String selectionForegroundString = (selectionForeground != null ?
selectionForeground.toString() :
"");
String selectionBackgroundString = (selectionBackground != null ?
selectionBackground.toString() :
"");
return super.paramString() +
",fixedCellHeight=" + fixedCellHeight +
",fixedCellWidth=" + fixedCellWidth +
",horizontalScrollIncrement=" + horizontalScrollIncrement +
",selectionBackground=" + selectionBackgroundString +
",selectionForeground=" + selectionForegroundString +
",visibleRowCount=" + visibleRowCount +
",layoutOrientation=" + layoutOrientation;
}
/** {@collect.stats}
* --- Accessibility Support ---
*/
/** {@collect.stats}
* Gets the {@code AccessibleContext} associated with this {@code JList}.
* For {@code JList}, the {@code AccessibleContext} takes the form of an
* {@code AccessibleJList}.
* <p>
* A new {@code AccessibleJList} instance is created if necessary.
*
* @return an {@code AccessibleJList} that serves as the
* {@code AccessibleContext} of this {@code JList}
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJList();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* {@code JList} class. It provides an implementation of the
* Java Accessibility API appropriate to list user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJList extends AccessibleJComponent
implements AccessibleSelection, PropertyChangeListener,
ListSelectionListener, ListDataListener {
int leadSelectionIndex;
public AccessibleJList() {
super();
JList.this.addPropertyChangeListener(this);
JList.this.getSelectionModel().addListSelectionListener(this);
JList.this.getModel().addListDataListener(this);
leadSelectionIndex = JList.this.getLeadSelectionIndex();
}
/** {@collect.stats}
* Property Change Listener change method. Used to track changes
* to the DataModel and ListSelectionModel, in order to re-set
* listeners to those for reporting changes there via the Accessibility
* PropertyChange mechanism.
*
* @param e PropertyChangeEvent
*/
public void propertyChange(PropertyChangeEvent e) {
String name = e.getPropertyName();
Object oldValue = e.getOldValue();
Object newValue = e.getNewValue();
// re-set listData listeners
if (name.compareTo("model") == 0) {
if (oldValue != null && oldValue instanceof ListModel) {
((ListModel) oldValue).removeListDataListener(this);
}
if (newValue != null && newValue instanceof ListModel) {
((ListModel) newValue).addListDataListener(this);
}
// re-set listSelectionModel listeners
} else if (name.compareTo("selectionModel") == 0) {
if (oldValue != null && oldValue instanceof ListSelectionModel) {
((ListSelectionModel) oldValue).removeListSelectionListener(this);
}
if (newValue != null && newValue instanceof ListSelectionModel) {
((ListSelectionModel) newValue).addListSelectionListener(this);
}
firePropertyChange(
AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
}
/** {@collect.stats}
* List Selection Listener value change method. Used to fire
* the property change
*
* @param e ListSelectionEvent
*
*/
public void valueChanged(ListSelectionEvent e) {
int oldLeadSelectionIndex = leadSelectionIndex;
leadSelectionIndex = JList.this.getLeadSelectionIndex();
if (oldLeadSelectionIndex != leadSelectionIndex) {
Accessible oldLS, newLS;
oldLS = (oldLeadSelectionIndex >= 0)
? getAccessibleChild(oldLeadSelectionIndex)
: null;
newLS = (leadSelectionIndex >= 0)
? getAccessibleChild(leadSelectionIndex)
: null;
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldLS, newLS);
}
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
// Process the State changes for Multiselectable
AccessibleStateSet s = getAccessibleStateSet();
ListSelectionModel lsm = JList.this.getSelectionModel();
if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) {
if (!s.contains(AccessibleState.MULTISELECTABLE)) {
s.add(AccessibleState.MULTISELECTABLE);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.MULTISELECTABLE);
}
} else {
if (s.contains(AccessibleState.MULTISELECTABLE)) {
s.remove(AccessibleState.MULTISELECTABLE);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.MULTISELECTABLE, null);
}
}
}
/** {@collect.stats}
* List Data Listener interval added method. Used to fire the visible data property change
*
* @param e ListDataEvent
*
*/
public void intervalAdded(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/** {@collect.stats}
* List Data Listener interval removed method. Used to fire the visible data property change
*
* @param e ListDataEvent
*
*/
public void intervalRemoved(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/** {@collect.stats}
* List Data Listener contents changed method. Used to fire the visible data property change
*
* @param e ListDataEvent
*
*/
public void contentsChanged(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
// AccessibleContext methods
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (selectionModel.getSelectionMode() !=
ListSelectionModel.SINGLE_SELECTION) {
states.add(AccessibleState.MULTISELECTABLE);
}
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.LIST;
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child contained at
* the local coordinate <code>Point</code>, if one exists.
* Otherwise returns <code>null</code>.
*
* @return the <code>Accessible</code> at the specified
* location, if it exists
*/
public Accessible getAccessibleAt(Point p) {
int i = locationToIndex(p);
if (i >= 0) {
return new AccessibleJListChild(JList.this, i);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return getModel().getSize();
}
/** {@collect.stats}
* Return the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
if (i >= getModel().getSize()) {
return null;
} else {
return new AccessibleJListChild(JList.this, i);
}
}
/** {@collect.stats}
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
// AccessibleSelection methods
/** {@collect.stats}
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
return JList.this.getSelectedIndices().length;
}
/** {@collect.stats}
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be <code>null</code>.
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
int len = getAccessibleSelectionCount();
if (i < 0 || i >= len) {
return null;
} else {
return getAccessibleChild(JList.this.getSelectedIndices()[i]);
}
}
/** {@collect.stats}
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
return isSelectedIndex(i);
}
/** {@collect.stats}
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
JList.this.addSelectionInterval(i, i);
}
/** {@collect.stats}
* Removes the specified selected item in the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
JList.this.removeSelectionInterval(i, i);
}
/** {@collect.stats}
* Clears the selection in the object, so that nothing in the
* object is selected.
*/
public void clearAccessibleSelection() {
JList.this.clearSelection();
}
/** {@collect.stats}
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
*/
public void selectAllAccessibleSelection() {
JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1);
}
/** {@collect.stats}
* This class implements accessibility support appropriate
* for list children.
*/
protected class AccessibleJListChild extends AccessibleContext
implements Accessible, AccessibleComponent {
private JList parent = null;
private int indexInParent;
private Component component = null;
private AccessibleContext accessibleContext = null;
private ListModel listModel;
private ListCellRenderer cellRenderer = null;
public AccessibleJListChild(JList parent, int indexInParent) {
this.parent = parent;
this.setAccessibleParent(parent);
this.indexInParent = indexInParent;
if (parent != null) {
listModel = parent.getModel();
cellRenderer = parent.getCellRenderer();
}
}
private Component getCurrentComponent() {
return getComponentAtIndex(indexInParent);
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getComponentAtIndex(indexInParent);
if (c instanceof Accessible) {
return ((Accessible) c).getAccessibleContext();
} else {
return null;
}
}
private Component getComponentAtIndex(int index) {
if (index < 0 || index >= listModel.getSize()) {
return null;
}
if ((parent != null)
&& (listModel != null)
&& cellRenderer != null) {
Object value = listModel.getElementAt(index);
boolean isSelected = parent.isSelectedIndex(index);
boolean isFocussed = parent.isFocusOwner()
&& (index == parent.getLeadSelectionIndex());
return cellRenderer.getListCellRendererComponent(
parent,
value,
index,
isSelected,
isFocussed);
} else {
return null;
}
}
// Accessible Methods
/** {@collect.stats}
* Get the AccessibleContext for this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is its own AccessibleContext.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
// AccessibleContext methods
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleName();
} else {
return null;
}
}
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
}
}
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return null;
}
}
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
}
}
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return null;
}
}
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet s;
if (ac != null) {
s = ac.getAccessibleStateSet();
} else {
s = new AccessibleStateSet();
}
s.add(AccessibleState.SELECTABLE);
if (parent.isFocusOwner()
&& (indexInParent == parent.getLeadSelectionIndex())) {
s.add(AccessibleState.ACTIVE);
}
if (parent.isSelectedIndex(indexInParent)) {
s.add(AccessibleState.SELECTED);
}
if (this.isShowing()) {
s.add(AccessibleState.SHOWING);
} else if (s.contains(AccessibleState.SHOWING)) {
s.remove(AccessibleState.SHOWING);
}
if (this.isVisible()) {
s.add(AccessibleState.VISIBLE);
} else if (s.contains(AccessibleState.VISIBLE)) {
s.remove(AccessibleState.VISIBLE);
}
s.add(AccessibleState.TRANSIENT); // cell-rendered
return s;
}
public int getAccessibleIndexInParent() {
return indexInParent;
}
public int getAccessibleChildrenCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
} else {
return 0;
}
}
public Accessible getAccessibleChild(int i) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
Accessible accessibleChild = ac.getAccessibleChild(i);
ac.setAccessibleParent(this);
return accessibleChild;
} else {
return null;
}
}
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return null;
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
}
}
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
}
}
public AccessibleAction getAccessibleAction() {
return getCurrentAccessibleContext().getAccessibleAction();
}
/** {@collect.stats}
* Get the AccessibleComponent associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleComponent interface on behalf of itself.
*
* @return this object
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
public AccessibleSelection getAccessibleSelection() {
return getCurrentAccessibleContext().getAccessibleSelection();
}
public AccessibleText getAccessibleText() {
return getCurrentAccessibleContext().getAccessibleText();
}
public AccessibleValue getAccessibleValue() {
return getCurrentAccessibleContext().getAccessibleValue();
}
// AccessibleComponent methods
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
public boolean isVisible() {
int fi = parent.getFirstVisibleIndex();
int li = parent.getLastVisibleIndex();
// The UI incorrectly returns a -1 for the last
// visible index if the list is smaller than the
// viewport size.
if (li == -1) {
li = parent.getModel().getSize() - 1;
}
return ((indexInParent >= fi)
&& (indexInParent <= li));
}
public void setVisible(boolean b) {
}
public boolean isShowing() {
return (parent.isShowing() && isVisible());
}
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
public Point getLocationOnScreen() {
if (parent != null) {
Point listLocation = parent.getLocationOnScreen();
Point componentLocation = parent.indexToLocation(indexInParent);
if (componentLocation != null) {
componentLocation.translate(listLocation.x, listLocation.y);
return componentLocation;
} else {
return null;
}
} else {
return null;
}
}
public Point getLocation() {
if (parent != null) {
return parent.indexToLocation(indexInParent);
} else {
return null;
}
}
public void setLocation(Point p) {
if ((parent != null) && (parent.contains(p))) {
ensureIndexIsVisible(indexInParent);
}
}
public Rectangle getBounds() {
if (parent != null) {
return parent.getCellBounds(indexInParent,indexInParent);
} else {
return null;
}
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
}
}
public Dimension getSize() {
Rectangle cellBounds = this.getBounds();
if (cellBounds != null) {
return cellBounds.getSize();
} else {
return null;
}
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
// TIGER - 4733624
/** {@collect.stats}
* Returns the icon for the element renderer, as the only item
* of an array of <code>AccessibleIcon</code>s or a <code>null</code> array
* if the renderer component contains no icons.
*
* @return an array containing the accessible icon
* or a <code>null</code> array if none
* @since 1.3
*/
public AccessibleIcon [] getAccessibleIcon() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleIcon();
} else {
return null;
}
}
} // inner class AccessibleJListChild
} // inner class AccessibleJList
}
|
Java
|
/*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.beans.PropertyVetoException;
import java.beans.PropertyChangeEvent;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.beans.PropertyChangeListener;
import sun.awt.AppContext;
import sun.swing.SwingUtilities2;
/** {@collect.stats}
* A lightweight object that provides many of the features of
* a native frame, including dragging, closing, becoming an icon,
* resizing, title display, and support for a menu bar.
* For task-oriented documentation and examples of using internal frames,
* see <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html" target="_top">How to Use Internal Frames</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
*
* Generally,
* you add <code>JInternalFrame</code>s to a <code>JDesktopPane</code>. The UI
* delegates the look-and-feel-specific actions to the
* <code>DesktopManager</code>
* object maintained by the <code>JDesktopPane</code>.
* <p>
* The <code>JInternalFrame</code> content pane
* is where you add child components.
* As a conveniance <code>add</code> and its variants, <code>remove</code> and
* <code>setLayout</code> have been overridden to forward to the
* <code>contentPane</code> as necessary. This means you can write:
* <pre>
* internalFrame.add(child);
* </pre>
* And the child will be added to the contentPane.
* The content pane is actually managed by an instance of
* <code>JRootPane</code>,
* which also manages a layout pane, glass pane, and
* optional menu bar for the internal frame. Please see the
* <code>JRootPane</code>
* documentation for a complete description of these components.
* Refer to {@link javax.swing.RootPaneContainer}
* for details on adding, removing and setting the <code>LayoutManager</code>
* of a <code>JInternalFrame</code>.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see InternalFrameEvent
* @see JDesktopPane
* @see DesktopManager
* @see JInternalFrame.JDesktopIcon
* @see JRootPane
* @see javax.swing.RootPaneContainer
*
* @author David Kloba
* @author Rich Schiavi
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getContentPane
* description: A frame container which is contained within
* another window.
*/
public class JInternalFrame extends JComponent implements
Accessible, WindowConstants,
RootPaneContainer
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "InternalFrameUI";
/** {@collect.stats}
* The <code>JRootPane</code> instance that manages the
* content pane
* and optional menu bar for this internal frame, as well as the
* glass pane.
*
* @see JRootPane
* @see RootPaneContainer
*/
protected JRootPane rootPane;
/** {@collect.stats}
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>JInternalFrame</code> is
* constructed.
*
* @see #isRootPaneCheckingEnabled
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean rootPaneCheckingEnabled = false;
/** {@collect.stats} The frame can be closed. */
protected boolean closable;
/** {@collect.stats} The frame has been closed. */
protected boolean isClosed;
/** {@collect.stats} The frame can be expanded to the size of the desktop pane. */
protected boolean maximizable;
/** {@collect.stats}
* The frame has been expanded to its maximum size.
* @see #maximizable
*/
protected boolean isMaximum;
/** {@collect.stats}
* The frame can "iconified" (shrunk down and displayed as
* an icon-image).
* @see JInternalFrame.JDesktopIcon
* @see #setIconifiable
*/
protected boolean iconable;
/** {@collect.stats}
* The frame has been iconified.
* @see #isIcon()
*/
protected boolean isIcon;
/** {@collect.stats} The frame's size can be changed. */
protected boolean resizable;
/** {@collect.stats} The frame is currently selected. */
protected boolean isSelected;
/** {@collect.stats} The icon shown in the top-left corner of this internal frame. */
protected Icon frameIcon;
/** {@collect.stats} The title displayed in this internal frame's title bar. */
protected String title;
/** {@collect.stats}
* The icon that is displayed when this internal frame is iconified.
* @see #iconable
*/
protected JDesktopIcon desktopIcon;
private Cursor lastCursor;
private boolean opened;
private Rectangle normalBounds = null;
private int defaultCloseOperation = DISPOSE_ON_CLOSE;
/** {@collect.stats}
* Contains the Component that focus is to go when
* <code>restoreSubcomponentFocus</code> is invoked, that is,
* <code>restoreSubcomponentFocus</code> sets this to the value returned
* from <code>getMostRecentFocusOwner</code>.
*/
private Component lastFocusOwner;
/** {@collect.stats} Bound property name. */
public final static String CONTENT_PANE_PROPERTY = "contentPane";
/** {@collect.stats} Bound property name. */
public final static String MENU_BAR_PROPERTY = "JMenuBar";
/** {@collect.stats} Bound property name. */
public final static String TITLE_PROPERTY = "title";
/** {@collect.stats} Bound property name. */
public final static String LAYERED_PANE_PROPERTY = "layeredPane";
/** {@collect.stats} Bound property name. */
public final static String ROOT_PANE_PROPERTY = "rootPane";
/** {@collect.stats} Bound property name. */
public final static String GLASS_PANE_PROPERTY = "glassPane";
/** {@collect.stats} Bound property name. */
public final static String FRAME_ICON_PROPERTY = "frameIcon";
/** {@collect.stats}
* Constrained property name indicated that this frame has
* selected status.
*/
public final static String IS_SELECTED_PROPERTY = "selected";
/** {@collect.stats} Constrained property name indicating that the internal frame is closed. */
public final static String IS_CLOSED_PROPERTY = "closed";
/** {@collect.stats} Constrained property name indicating that the internal frame is maximized. */
public final static String IS_MAXIMUM_PROPERTY = "maximum";
/** {@collect.stats} Constrained property name indicating that the internal frame is iconified. */
public final static String IS_ICON_PROPERTY = "icon";
private static final Object PROPERTY_CHANGE_LISTENER_KEY = new Object(); // InternalFramePropertyChangeListener
private static void addPropertyChangeListenerIfNecessary() {
if (AppContext.getAppContext().get(PROPERTY_CHANGE_LISTENER_KEY) ==
null) {
PropertyChangeListener focusListener =
new FocusPropertyChangeListener();
AppContext.getAppContext().put(PROPERTY_CHANGE_LISTENER_KEY,
focusListener);
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addPropertyChangeListener(focusListener);
}
}
private static class FocusPropertyChangeListener implements
PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName() == "permanentFocusOwner") {
updateLastFocusOwner((Component)e.getNewValue());
}
}
}
private static void updateLastFocusOwner(Component component) {
if (component != null) {
Component parent = component;
while (parent != null && !(parent instanceof Window)) {
if (parent instanceof JInternalFrame) {
// Update lastFocusOwner for parent.
((JInternalFrame)parent).setLastFocusOwner(component);
}
parent = parent.getParent();
}
}
}
/** {@collect.stats}
* Creates a non-resizable, non-closable, non-maximizable,
* non-iconifiable <code>JInternalFrame</code> with no title.
*/
public JInternalFrame() {
this("", false, false, false, false);
}
/** {@collect.stats}
* Creates a non-resizable, non-closable, non-maximizable,
* non-iconifiable <code>JInternalFrame</code> with the specified title.
* Note that passing in a <code>null</code> <code>title</code> results in
* unspecified behavior and possibly an exception.
*
* @param title the non-<code>null</code> <code>String</code>
* to display in the title bar
*/
public JInternalFrame(String title) {
this(title, false, false, false, false);
}
/** {@collect.stats}
* Creates a non-closable, non-maximizable, non-iconifiable
* <code>JInternalFrame</code> with the specified title
* and resizability.
*
* @param title the <code>String</code> to display in the title bar
* @param resizable if <code>true</code>, the internal frame can be resized
*/
public JInternalFrame(String title, boolean resizable) {
this(title, resizable, false, false, false);
}
/** {@collect.stats}
* Creates a non-maximizable, non-iconifiable <code>JInternalFrame</code>
* with the specified title, resizability, and
* closability.
*
* @param title the <code>String</code> to display in the title bar
* @param resizable if <code>true</code>, the internal frame can be resized
* @param closable if <code>true</code>, the internal frame can be closed
*/
public JInternalFrame(String title, boolean resizable, boolean closable) {
this(title, resizable, closable, false, false);
}
/** {@collect.stats}
* Creates a non-iconifiable <code>JInternalFrame</code>
* with the specified title,
* resizability, closability, and maximizability.
*
* @param title the <code>String</code> to display in the title bar
* @param resizable if <code>true</code>, the internal frame can be resized
* @param closable if <code>true</code>, the internal frame can be closed
* @param maximizable if <code>true</code>, the internal frame can be maximized
*/
public JInternalFrame(String title, boolean resizable, boolean closable,
boolean maximizable) {
this(title, resizable, closable, maximizable, false);
}
/** {@collect.stats}
* Creates a <code>JInternalFrame</code> with the specified title,
* resizability, closability, maximizability, and iconifiability.
* All <code>JInternalFrame</code> constructors use this one.
*
* @param title the <code>String</code> to display in the title bar
* @param resizable if <code>true</code>, the internal frame can be resized
* @param closable if <code>true</code>, the internal frame can be closed
* @param maximizable if <code>true</code>, the internal frame can be maximized
* @param iconifiable if <code>true</code>, the internal frame can be iconified
*/
public JInternalFrame(String title, boolean resizable, boolean closable,
boolean maximizable, boolean iconifiable) {
setRootPane(createRootPane());
setLayout(new BorderLayout());
this.title = title;
this.resizable = resizable;
this.closable = closable;
this.maximizable = maximizable;
isMaximum = false;
this.iconable = iconifiable;
isIcon = false;
setVisible(false);
setRootPaneCheckingEnabled(true);
desktopIcon = new JDesktopIcon(this);
updateUI();
sun.awt.SunToolkit.checkAndSetPolicy(this, true);
addPropertyChangeListenerIfNecessary();
}
/** {@collect.stats}
* Called by the constructor to set up the <code>JRootPane</code>.
* @return a new <code>JRootPane</code>
* @see JRootPane
*/
protected JRootPane createRootPane() {
return new JRootPane();
}
/** {@collect.stats}
* Returns the look-and-feel object that renders this component.
*
* @return the <code>InternalFrameUI</code> object that renders
* this component
*/
public InternalFrameUI getUI() {
return (InternalFrameUI)ui;
}
/** {@collect.stats}
* Sets the UI delegate for this <code>JInternalFrame</code>.
* @param ui the UI delegate
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(InternalFrameUI ui) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
super.setUI(ui);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the look and feel
* has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((InternalFrameUI)UIManager.getUI(this));
invalidate();
if (desktopIcon != null) {
desktopIcon.updateUIWhenHidden();
}
}
/* This method is called if <code>updateUI</code> was called
* on the associated
* JDesktopIcon. It's necessary to avoid infinite recursion.
*/
void updateUIWhenHidden() {
setUI((InternalFrameUI)UIManager.getUI(this));
invalidate();
Component[] children = getComponents();
if (children != null) {
for(int i = 0; i < children.length; i++) {
SwingUtilities.updateComponentTreeUI(children[i]);
}
}
}
/** {@collect.stats}
* Returns the name of the look-and-feel
* class that renders this component.
*
* @return the string "InternalFrameUI"
*
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*
* @beaninfo
* description: UIClassID
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @return true if <code>add</code> and <code>setLayout</code>
* are fowarded; false otherwise
*
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/** {@collect.stats}
* Sets whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @param enabled true if <code>add</code> and <code>setLayout</code>
* are forwarded, false if they should operate directly on the
* <code>JInternalFrame</code>.
*
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
* @beaninfo
* hidden: true
* description: Whether the add and setLayout methods are forwarded
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/** {@collect.stats}
* Adds the specified child <code>Component</code>.
* This method is overridden to conditionally forward calls to the
* <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for
* details.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
*
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected void addImpl(Component comp, Object constraints, int index) {
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/** {@collect.stats}
* Removes the specified component from the container. If
* <code>comp</code> is not a child of the <code>JInternalFrame</code>
* this will forward the call to the <code>contentPane</code>.
*
* @param comp the component to be removed
* @throws NullPointerException if <code>comp</code> is null
* @see #add
* @see javax.swing.RootPaneContainer
*/
public void remove(Component comp) {
int oldCount = getComponentCount();
super.remove(comp);
if (oldCount == getComponentCount()) {
getContentPane().remove(comp);
}
}
/** {@collect.stats}
* Ensures that, by default, the layout of this component cannot be set.
* Overridden to conditionally forward the call to the
* <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for
* more information.
*
* @param manager the <code>LayoutManager</code>
* @see #setRootPaneCheckingEnabled
*/
public void setLayout(LayoutManager manager) {
if(isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
//////////////////////////////////////////////////////////////////////////
/// Property Methods
//////////////////////////////////////////////////////////////////////////
/** {@collect.stats}
* Returns the current <code>JMenuBar</code> for this
* <code>JInternalFrame</code>, or <code>null</code>
* if no menu bar has been set.
* @return the current menu bar, or <code>null</code> if none has been set
*
* @deprecated As of Swing version 1.0.3,
* replaced by <code>getJMenuBar()</code>.
*/
@Deprecated
public JMenuBar getMenuBar() {
return getRootPane().getMenuBar();
}
/** {@collect.stats}
* Returns the current <code>JMenuBar</code> for this
* <code>JInternalFrame</code>, or <code>null</code>
* if no menu bar has been set.
*
* @return the <code>JMenuBar</code> used by this internal frame
* @see #setJMenuBar
*/
public JMenuBar getJMenuBar() {
return getRootPane().getJMenuBar();
}
/** {@collect.stats}
* Sets the <code>menuBar</code> property for this <code>JInternalFrame</code>.
*
* @param m the <code>JMenuBar</code> to use in this internal frame
* @see #getJMenuBar
* @deprecated As of Swing version 1.0.3
* replaced by <code>setJMenuBar(JMenuBar m)</code>.
*/
@Deprecated
public void setMenuBar(JMenuBar m) {
JMenuBar oldValue = getMenuBar();
getRootPane().setJMenuBar(m);
firePropertyChange(MENU_BAR_PROPERTY, oldValue, m);
}
/** {@collect.stats}
* Sets the <code>menuBar</code> property for this <code>JInternalFrame</code>.
*
* @param m the <code>JMenuBar</code> to use in this internal frame
* @see #getJMenuBar
* @beaninfo
* bound: true
* preferred: true
* description: The menu bar for accessing pulldown menus
* from this internal frame.
*/
public void setJMenuBar(JMenuBar m){
JMenuBar oldValue = getMenuBar();
getRootPane().setJMenuBar(m);
firePropertyChange(MENU_BAR_PROPERTY, oldValue, m);
}
// implements javax.swing.RootPaneContainer
/** {@collect.stats}
* Returns the content pane for this internal frame.
* @return the content pane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/** {@collect.stats}
* Sets this <code>JInternalFrame</code>'s <code>contentPane</code>
* property.
*
* @param c the content pane for this internal frame
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see RootPaneContainer#getContentPane
* @beaninfo
* bound: true
* hidden: true
* description: The client area of the internal frame where child
* components are normally inserted.
*/
public void setContentPane(Container c) {
Container oldValue = getContentPane();
getRootPane().setContentPane(c);
firePropertyChange(CONTENT_PANE_PROPERTY, oldValue, c);
}
/** {@collect.stats}
* Returns the layered pane for this internal frame.
*
* @return a <code>JLayeredPane</code> object
* @see RootPaneContainer#setLayeredPane
* @see RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/** {@collect.stats}
* Sets this <code>JInternalFrame</code>'s
* <code>layeredPane</code> property.
*
* @param layered the <code>JLayeredPane</code> for this internal frame
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is <code>null</code>
* @see RootPaneContainer#setLayeredPane
* @beaninfo
* hidden: true
* bound: true
* description: The pane which holds the various desktop layers.
*/
public void setLayeredPane(JLayeredPane layered) {
JLayeredPane oldValue = getLayeredPane();
getRootPane().setLayeredPane(layered);
firePropertyChange(LAYERED_PANE_PROPERTY, oldValue, layered);
}
/** {@collect.stats}
* Returns the glass pane for this internal frame.
*
* @return the glass pane
* @see RootPaneContainer#setGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/** {@collect.stats}
* Sets this <code>JInternalFrame</code>'s
* <code>glassPane</code> property.
*
* @param glass the glass pane for this internal frame
* @see RootPaneContainer#getGlassPane
* @beaninfo
* bound: true
* hidden: true
* description: A transparent pane used for menu rendering.
*/
public void setGlassPane(Component glass) {
Component oldValue = getGlassPane();
getRootPane().setGlassPane(glass);
firePropertyChange(GLASS_PANE_PROPERTY, oldValue, glass);
}
/** {@collect.stats}
* Returns the <code>rootPane</code> object for this internal frame.
*
* @return the <code>rootPane</code> property
* @see RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/** {@collect.stats}
* Sets the <code>rootPane</code> property
* for this <code>JInternalFrame</code>.
* This method is called by the constructor.
*
* @param root the new <code>JRootPane</code> object
* @beaninfo
* bound: true
* hidden: true
* description: The root pane used by this internal frame.
*/
protected void setRootPane(JRootPane root) {
if(rootPane != null) {
remove(rootPane);
}
JRootPane oldValue = getRootPane();
rootPane = root;
if(rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
firePropertyChange(ROOT_PANE_PROPERTY, oldValue, root);
}
/** {@collect.stats}
* Sets whether this <code>JInternalFrame</code> can be closed by
* some user action.
* @param b a boolean value, where <code>true</code> means this internal frame can be closed
* @beaninfo
* preferred: true
* bound: true
* description: Indicates whether this internal frame can be closed.
*/
public void setClosable(boolean b) {
Boolean oldValue = closable ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
closable = b;
firePropertyChange("closable", oldValue, newValue);
}
/** {@collect.stats}
* Returns whether this <code>JInternalFrame</code> can be closed by
* some user action.
* @return <code>true</code> if this internal frame can be closed
*/
public boolean isClosable() {
return closable;
}
/** {@collect.stats}
* Returns whether this <code>JInternalFrame</code> is currently closed.
* @return <code>true</code> if this internal frame is closed, <code>false</code> otherwise
*/
public boolean isClosed() {
return isClosed;
}
/** {@collect.stats}
* Closes this internal frame if the argument is <code>true</code>.
* Do not invoke this method with a <code>false</code> argument;
* the result of invoking <code>setClosed(false)</code>
* is unspecified.
*
* <p>
*
* If the internal frame is already closed,
* this method does nothing and returns immediately.
* Otherwise,
* this method begins by firing
* an <code>INTERNAL_FRAME_CLOSING</code> event.
* Then this method sets the <code>closed</code> property to <code>true</code>
* unless a listener vetoes the property change.
* This method finishes by making the internal frame
* invisible and unselected,
* and then firing an <code>INTERNAL_FRAME_CLOSED</code> event.
*
* <p>
*
* <b>Note:</b>
* To reuse an internal frame that has been closed,
* you must add it to a container
* (even if you never removed it from its previous container).
* Typically, this container will be the <code>JDesktopPane</code>
* that previously contained the internal frame.
*
* @param b must be <code>true</code>
*
* @exception PropertyVetoException when the attempt to set the
* property is vetoed by the <code>JInternalFrame</code>
*
* @see #isClosed()
* @see #setDefaultCloseOperation
* @see #dispose
* @see javax.swing.event.InternalFrameEvent#INTERNAL_FRAME_CLOSING
*
* @beaninfo
* bound: true
* constrained: true
* description: Indicates whether this internal frame has been closed.
*/
public void setClosed(boolean b) throws PropertyVetoException {
if (isClosed == b) {
return;
}
Boolean oldValue = isClosed ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
if (b) {
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_CLOSING);
}
fireVetoableChange(IS_CLOSED_PROPERTY, oldValue, newValue);
isClosed = b;
if (isClosed) {
setVisible(false);
}
firePropertyChange(IS_CLOSED_PROPERTY, oldValue, newValue);
if (isClosed) {
dispose();
} else if (!opened) {
/* this bogus -- we haven't defined what
setClosed(false) means. */
// fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_OPENED);
// opened = true;
}
}
/** {@collect.stats}
* Sets whether the <code>JInternalFrame</code> can be resized by some
* user action.
*
* @param b a boolean, where <code>true</code> means this internal frame can be resized
* @beaninfo
* preferred: true
* bound: true
* description: Determines whether this internal frame can be resized
* by the user.
*/
public void setResizable(boolean b) {
Boolean oldValue = resizable ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
resizable = b;
firePropertyChange("resizable", oldValue, newValue);
}
/** {@collect.stats}
* Returns whether the <code>JInternalFrame</code> can be resized
* by some user action.
*
* @return <code>true</code> if this internal frame can be resized, <code>false</code> otherwise
*/
public boolean isResizable() {
// don't allow resizing when maximized.
return isMaximum ? false : resizable;
}
/** {@collect.stats}
* Sets the <code>iconable</code> property,
* which must be <code>true</code>
* for the user to be able to
* make the <code>JInternalFrame</code> an icon.
* Some look and feels might not implement iconification;
* they will ignore this property.
*
* @param b a boolean, where <code>true</code> means this internal frame can be iconified
* @beaninfo
* preferred: true
bound: true
* description: Determines whether this internal frame can be iconified.
*/
public void setIconifiable(boolean b) {
Boolean oldValue = iconable ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
iconable = b;
firePropertyChange("iconable", oldValue, newValue);
}
/** {@collect.stats}
* Gets the <code>iconable</code> property,
* which by default is <code>false</code>.
*
* @return the value of the <code>iconable</code> property.
*
* @see #setIconifiable
*/
public boolean isIconifiable() {
return iconable;
}
/** {@collect.stats}
* Returns whether the <code>JInternalFrame</code> is currently iconified.
*
* @return <code>true</code> if this internal frame is iconified
*/
public boolean isIcon() {
return isIcon;
}
/** {@collect.stats}
* Iconifies or de-iconifies this internal frame,
* if the look and feel supports iconification.
* If the internal frame's state changes to iconified,
* this method fires an <code>INTERNAL_FRAME_ICONIFIED</code> event.
* If the state changes to de-iconified,
* an <code>INTERNAL_FRAME_DEICONIFIED</code> event is fired.
*
* @param b a boolean, where <code>true</code> means to iconify this internal frame and
* <code>false</code> means to de-iconify it
* @exception PropertyVetoException when the attempt to set the
* property is vetoed by the <code>JInternalFrame</code>
*
* @see InternalFrameEvent#INTERNAL_FRAME_ICONIFIED
* @see InternalFrameEvent#INTERNAL_FRAME_DEICONIFIED
*
* @beaninfo
* bound: true
* constrained: true
* description: The image displayed when this internal frame is minimized.
*/
public void setIcon(boolean b) throws PropertyVetoException {
if (isIcon == b) {
return;
}
/* If an internal frame is being iconified before it has a
parent, (e.g., client wants it to start iconic), create the
parent if possible so that we can place the icon in its
proper place on the desktop. I am not sure the call to
validate() is necessary, since we are not going to display
this frame yet */
firePropertyChange("ancestor", null, getParent());
Boolean oldValue = isIcon ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
fireVetoableChange(IS_ICON_PROPERTY, oldValue, newValue);
isIcon = b;
firePropertyChange(IS_ICON_PROPERTY, oldValue, newValue);
if (b)
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_ICONIFIED);
else
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_DEICONIFIED);
}
/** {@collect.stats}
* Sets the <code>maximizable</code> property,
* which determines whether the <code>JInternalFrame</code>
* can be maximized by
* some user action.
* Some look and feels might not support maximizing internal frames;
* they will ignore this property.
*
* @param b <code>true</code> to specify that this internal frame should be maximizable; <code>false</code> to specify that it should not be
* @beaninfo
* bound: true
* preferred: true
* description: Determines whether this internal frame can be maximized.
*/
public void setMaximizable(boolean b) {
Boolean oldValue = maximizable ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
maximizable = b;
firePropertyChange("maximizable", oldValue, newValue);
}
/** {@collect.stats}
* Gets the value of the <code>maximizable</code> property.
*
* @return the value of the <code>maximizable</code> property
* @see #setMaximizable
*/
public boolean isMaximizable() {
return maximizable;
}
/** {@collect.stats}
* Returns whether the <code>JInternalFrame</code> is currently maximized.
*
* @return <code>true</code> if this internal frame is maximized, <code>false</code> otherwise
*/
public boolean isMaximum() {
return isMaximum;
}
/** {@collect.stats}
* Maximizes and restores this internal frame. A maximized frame is resized to
* fully fit the <code>JDesktopPane</code> area associated with the
* <code>JInternalFrame</code>.
* A restored frame's size is set to the <code>JInternalFrame</code>'s
* actual size.
*
* @param b a boolean, where <code>true</code> maximizes this internal frame and <code>false</code>
* restores it
* @exception PropertyVetoException when the attempt to set the
* property is vetoed by the <code>JInternalFrame</code>
* @beaninfo
* bound: true
* constrained: true
* description: Indicates whether this internal frame is maximized.
*/
public void setMaximum(boolean b) throws PropertyVetoException {
if (isMaximum == b) {
return;
}
Boolean oldValue = isMaximum ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = b ? Boolean.TRUE : Boolean.FALSE;
fireVetoableChange(IS_MAXIMUM_PROPERTY, oldValue, newValue);
/* setting isMaximum above the event firing means that
property listeners that, for some reason, test it will
get it wrong... See, for example, getNormalBounds() */
isMaximum = b;
firePropertyChange(IS_MAXIMUM_PROPERTY, oldValue, newValue);
}
/** {@collect.stats}
* Returns the title of the <code>JInternalFrame</code>.
*
* @return a <code>String</code> containing this internal frame's title
* @see #setTitle
*/
public String getTitle() {
return title;
}
/** {@collect.stats}
* Sets the <code>JInternalFrame</code> title. <code>title</code>
* may have a <code>null</code> value.
* @see #getTitle
*
* @param title the <code>String</code> to display in the title bar
* @beaninfo
* preferred: true
* bound: true
* description: The text displayed in the title bar.
*/
public void setTitle(String title) {
String oldValue = this.title;
this.title = title;
firePropertyChange(TITLE_PROPERTY, oldValue, title);
}
/** {@collect.stats}
* Selects or deselects the internal frame
* if it's showing.
* A <code>JInternalFrame</code> normally draws its title bar
* differently if it is
* the selected frame, which indicates to the user that this
* internal frame has the focus.
* When this method changes the state of the internal frame
* from deselected to selected, it fires an
* <code>InternalFrameEvent.INTERNAL_FRAME_ACTIVATED</code> event.
* If the change is from selected to deselected,
* an <code>InternalFrameEvent.INTERNAL_FRAME_DEACTIVATED</code> event
* is fired.
*
* @param selected a boolean, where <code>true</code> means this internal frame
* should become selected (currently active)
* and <code>false</code> means it should become deselected
* @exception PropertyVetoException when the attempt to set the
* property is vetoed by the <code>JInternalFrame</code>
*
* @see #isShowing
* @see InternalFrameEvent#INTERNAL_FRAME_ACTIVATED
* @see InternalFrameEvent#INTERNAL_FRAME_DEACTIVATED
*
* @beaninfo
* constrained: true
* bound: true
* description: Indicates whether this internal frame is currently
* the active frame.
*/
public void setSelected(boolean selected) throws PropertyVetoException {
// The InternalFrame may already be selected, but the focus
// may be outside it, so restore the focus to the subcomponent
// which previously had it. See Bug 4302764.
if (selected && isSelected) {
restoreSubcomponentFocus();
return;
}
// The internal frame or the desktop icon must be showing to allow
// selection. We may deselect even if neither is showing.
if ((isSelected == selected) || (selected &&
(isIcon ? !desktopIcon.isShowing() : !isShowing()))) {
return;
}
Boolean oldValue = isSelected ? Boolean.TRUE : Boolean.FALSE;
Boolean newValue = selected ? Boolean.TRUE : Boolean.FALSE;
fireVetoableChange(IS_SELECTED_PROPERTY, oldValue, newValue);
/* We don't want to leave focus in the previously selected
frame, so we have to set it to *something* in case it
doesn't get set in some other way (as if a user clicked on
a component that doesn't request focus). If this call is
happening because the user clicked on a component that will
want focus, then it will get transfered there later.
We test for parent.isShowing() above, because AWT throws a
NPE if you try to request focus on a lightweight before its
parent has been made visible */
if (selected) {
restoreSubcomponentFocus();
}
isSelected = selected;
firePropertyChange(IS_SELECTED_PROPERTY, oldValue, newValue);
if (isSelected)
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_ACTIVATED);
else
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_DEACTIVATED);
repaint();
}
/** {@collect.stats}
* Returns whether the <code>JInternalFrame</code> is the
* currently "selected" or active frame.
*
* @return <code>true</code> if this internal frame is currently selected (active)
* @see #setSelected
*/
public boolean isSelected() {
return isSelected;
}
/** {@collect.stats}
* Sets an image to be displayed in the titlebar of this internal frame (usually
* in the top-left corner).
* This image is not the <code>desktopIcon</code> object, which
* is the image displayed in the <code>JDesktop</code> when
* this internal frame is iconified.
*
* Passing <code>null</code> to this function is valid,
* but the look and feel
* can choose the
* appropriate behavior for that situation, such as displaying no icon
* or a default icon for the look and feel.
*
* @param icon the <code>Icon</code> to display in the title bar
* @see #getFrameIcon
* @beaninfo
* bound: true
* description: The icon shown in the top-left corner of this internal frame.
*/
public void setFrameIcon(Icon icon) {
Icon oldIcon = frameIcon;
frameIcon = icon;
firePropertyChange(FRAME_ICON_PROPERTY, oldIcon, icon);
}
/** {@collect.stats}
* Returns the image displayed in the title bar of this internal frame (usually
* in the top-left corner).
*
* @return the <code>Icon</code> displayed in the title bar
* @see #setFrameIcon
*/
public Icon getFrameIcon() {
return frameIcon;
}
/** {@collect.stats}
* Convenience method that moves this component to position 0 if its
* parent is a <code>JLayeredPane</code>.
*/
public void moveToFront() {
if (isIcon()) {
if (getDesktopIcon().getParent() instanceof JLayeredPane) {
((JLayeredPane)getDesktopIcon().getParent()).
moveToFront(getDesktopIcon());
}
}
else if (getParent() instanceof JLayeredPane) {
((JLayeredPane)getParent()).moveToFront(this);
}
}
/** {@collect.stats}
* Convenience method that moves this component to position -1 if its
* parent is a <code>JLayeredPane</code>.
*/
public void moveToBack() {
if (isIcon()) {
if (getDesktopIcon().getParent() instanceof JLayeredPane) {
((JLayeredPane)getDesktopIcon().getParent()).
moveToBack(getDesktopIcon());
}
}
else if (getParent() instanceof JLayeredPane) {
((JLayeredPane)getParent()).moveToBack(this);
}
}
/** {@collect.stats}
* Returns the last <code>Cursor</code> that was set by the
* <code>setCursor</code> method that is not a resizable
* <code>Cursor</code>.
*
* @return the last non-resizable <code>Cursor</code>
* @since 1.6
*/
public Cursor getLastCursor() {
return lastCursor;
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void setCursor(Cursor cursor) {
if (cursor == null) {
lastCursor = null;
super.setCursor(cursor);
return;
}
int type = cursor.getType();
if (!(type == Cursor.SW_RESIZE_CURSOR ||
type == Cursor.SE_RESIZE_CURSOR ||
type == Cursor.NW_RESIZE_CURSOR ||
type == Cursor.NE_RESIZE_CURSOR ||
type == Cursor.N_RESIZE_CURSOR ||
type == Cursor.S_RESIZE_CURSOR ||
type == Cursor.W_RESIZE_CURSOR ||
type == Cursor.E_RESIZE_CURSOR)) {
lastCursor = cursor;
}
super.setCursor(cursor);
}
/** {@collect.stats}
* Convenience method for setting the layer attribute of this component.
*
* @param layer an <code>Integer</code> object specifying this
* frame's desktop layer
* @see JLayeredPane
* @beaninfo
* expert: true
* description: Specifies what desktop layer is used.
*/
public void setLayer(Integer layer) {
if(getParent() != null && getParent() instanceof JLayeredPane) {
// Normally we want to do this, as it causes the LayeredPane
// to draw properly.
JLayeredPane p = (JLayeredPane)getParent();
p.setLayer(this, layer.intValue(), p.getPosition(this));
} else {
// Try to do the right thing
JLayeredPane.putLayer(this, layer.intValue());
if(getParent() != null)
getParent().repaint(getX(), getY(), getWidth(), getHeight());
}
}
/** {@collect.stats}
* Convenience method for setting the layer attribute of this component.
* The method <code>setLayer(Integer)</code> should be used for
* layer values predefined in <code>JLayeredPane</code>.
* When using <code>setLayer(int)</code>, care must be taken not to
* accidentally clash with those values.
*
* @param layer an integer specifying this internal frame's desktop layer
*
* @since 1.3
*
* @see #setLayer(Integer)
* @see JLayeredPane
* @beaninfo
* expert: true
* description: Specifies what desktop layer is used.
*/
public void setLayer(int layer) {
this.setLayer(new Integer(layer));
}
/** {@collect.stats}
* Convenience method for getting the layer attribute of this component.
*
* @return an <code>Integer</code> object specifying this
* frame's desktop layer
* @see JLayeredPane
*/
public int getLayer() {
return JLayeredPane.getLayer(this);
}
/** {@collect.stats}
* Convenience method that searches the ancestor hierarchy for a
* <code>JDesktop</code> instance. If <code>JInternalFrame</code>
* finds none, the <code>desktopIcon</code> tree is searched.
*
* @return the <code>JDesktopPane</code> this internal frame belongs to,
* or <code>null</code> if none is found
*/
public JDesktopPane getDesktopPane() {
Container p;
// Search upward for desktop
p = getParent();
while(p != null && !(p instanceof JDesktopPane))
p = p.getParent();
if(p == null) {
// search its icon parent for desktop
p = getDesktopIcon().getParent();
while(p != null && !(p instanceof JDesktopPane))
p = p.getParent();
}
return (JDesktopPane)p;
}
/** {@collect.stats}
* Sets the <code>JDesktopIcon</code> associated with this
* <code>JInternalFrame</code>.
*
* @param d the <code>JDesktopIcon</code> to display on the desktop
* @see #getDesktopIcon
* @beaninfo
* bound: true
* description: The icon shown when this internal frame is minimized.
*/
public void setDesktopIcon(JDesktopIcon d) {
JDesktopIcon oldValue = getDesktopIcon();
desktopIcon = d;
firePropertyChange("desktopIcon", oldValue, d);
}
/** {@collect.stats}
* Returns the <code>JDesktopIcon</code> used when this
* <code>JInternalFrame</code> is iconified.
*
* @return the <code>JDesktopIcon</code> displayed on the desktop
* @see #setDesktopIcon
*/
public JDesktopIcon getDesktopIcon() {
return desktopIcon;
}
/** {@collect.stats}
* If the <code>JInternalFrame</code> is not in maximized state, returns
* <code>getBounds()</code>; otherwise, returns the bounds that the
* <code>JInternalFrame</code> would be restored to.
*
* @return a <code>Rectangle</code> containing the bounds of this
* frame when in the normal state
* @since 1.3
*/
public Rectangle getNormalBounds() {
/* we used to test (!isMaximum) here, but since this
method is used by the property listener for the
IS_MAXIMUM_PROPERTY, it ended up getting the wrong
answer... Since normalBounds get set to null when the
frame is restored, this should work better */
if (normalBounds != null) {
return normalBounds;
} else {
return getBounds();
}
}
/** {@collect.stats}
* Sets the normal bounds for this internal frame, the bounds that
* this internal frame would be restored to from its maximized state.
* This method is intended for use only by desktop managers.
*
* @param r the bounds that this internal frame should be restored to
* @since 1.3
*/
public void setNormalBounds(Rectangle r) {
normalBounds = r;
}
/** {@collect.stats}
* If this <code>JInternalFrame</code> is active,
* returns the child that has focus.
* Otherwise, returns <code>null</code>.
*
* @return the component with focus, or <code>null</code> if no children have focus
* @since 1.3
*/
public Component getFocusOwner() {
if (isSelected()) {
return lastFocusOwner;
}
return null;
}
/** {@collect.stats}
* Returns the child component of this <code>JInternalFrame</code>
* that will receive the
* focus when this <code>JInternalFrame</code> is selected.
* If this <code>JInternalFrame</code> is
* currently selected, this method returns the same component as
* the <code>getFocusOwner</code> method.
* If this <code>JInternalFrame</code> is not selected,
* then the child component that most recently requested focus will be
* returned. If no child component has ever requested focus, then this
* <code>JInternalFrame</code>'s initial focusable component is returned.
* If no such
* child exists, then this <code>JInternalFrame</code>'s default component
* to focus is returned.
*
* @return the child component that will receive focus when this
* <code>JInternalFrame</code> is selected
* @see #getFocusOwner
* @see #isSelected
* @since 1.4
*/
public Component getMostRecentFocusOwner() {
if (isSelected()) {
return getFocusOwner();
}
if (lastFocusOwner != null) {
return lastFocusOwner;
}
FocusTraversalPolicy policy = getFocusTraversalPolicy();
if (policy instanceof InternalFrameFocusTraversalPolicy) {
return ((InternalFrameFocusTraversalPolicy)policy).
getInitialComponent(this);
}
Component toFocus = policy.getDefaultComponent(this);
if (toFocus != null) {
return toFocus;
}
return getContentPane();
}
/** {@collect.stats}
* Requests the internal frame to restore focus to the
* last subcomponent that had focus. This is used by the UI when
* the user selected this internal frame --
* for example, by clicking on the title bar.
*
* @since 1.3
*/
public void restoreSubcomponentFocus() {
if (isIcon()) {
SwingUtilities2.compositeRequestFocus(getDesktopIcon());
}
else {
// FocusPropertyChangeListener will eventually update
// lastFocusOwner. As focus requests are asynchronous
// lastFocusOwner may be accessed before it has been correctly
// updated. To avoid any problems, lastFocusOwner is immediately
// set, assuming the request will succeed.
lastFocusOwner = getMostRecentFocusOwner();
if (lastFocusOwner == null) {
// Make sure focus is restored somewhere, so that
// we don't leave a focused component in another frame while
// this frame is selected.
lastFocusOwner = getContentPane();
}
lastFocusOwner.requestFocus();
}
}
private void setLastFocusOwner(Component component) {
lastFocusOwner = component;
}
/** {@collect.stats}
* Moves and resizes this component. Unlike other components,
* this implementation also forces re-layout, so that frame
* decorations such as the title bar are always redisplayed.
*
* @param x an integer giving the component's new horizontal position
* measured in pixels from the left of its container
* @param y an integer giving the component's new vertical position,
* measured in pixels from the bottom of its container
* @param width an integer giving the component's new width in pixels
* @param height an integer giving the component's new height in pixels
*/
public void reshape(int x, int y, int width, int height) {
super.reshape(x, y, width, height);
validate();
repaint();
}
///////////////////////////
// Frame/Window equivalents
///////////////////////////
/** {@collect.stats}
* Adds the specified listener to receive internal
* frame events from this internal frame.
*
* @param l the internal frame listener
*/
public void addInternalFrameListener(InternalFrameListener l) { // remind: sync ??
listenerList.add(InternalFrameListener.class, l);
// remind: needed?
enableEvents(0); // turn on the newEventsOnly flag in Component.
}
/** {@collect.stats}
* Removes the specified internal frame listener so that it no longer
* receives internal frame events from this internal frame.
*
* @param l the internal frame listener
*/
public void removeInternalFrameListener(InternalFrameListener l) { // remind: sync??
listenerList.remove(InternalFrameListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>InternalFrameListener</code>s added
* to this <code>JInternalFrame</code> with
* <code>addInternalFrameListener</code>.
*
* @return all of the <code>InternalFrameListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*
* @see #addInternalFrameListener
*/
public InternalFrameListener[] getInternalFrameListeners() {
return (InternalFrameListener[])listenerList.getListeners(
InternalFrameListener.class);
}
// remind: name ok? all one method ok? need to be synchronized?
/** {@collect.stats}
* Fires an internal frame event.
*
* @param id the type of the event being fired; one of the following:
* <ul>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_OPENED</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_CLOSING</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_CLOSED</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_ICONIFIED</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_DEICONIFIED</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_ACTIVATED</code>
* <li><code>InternalFrameEvent.INTERNAL_FRAME_DEACTIVATED</code>
* </ul>
* If the event type is not one of the above, nothing happens.
*/
protected void fireInternalFrameEvent(int id){
Object[] listeners = listenerList.getListenerList();
InternalFrameEvent e = null;
for (int i = listeners.length -2; i >=0; i -= 2){
if (listeners[i] == InternalFrameListener.class){
if (e == null){
e = new InternalFrameEvent(this, id);
// System.out.println("InternalFrameEvent: " + e.paramString());
}
switch(e.getID()) {
case InternalFrameEvent.INTERNAL_FRAME_OPENED:
((InternalFrameListener)listeners[i+1]).internalFrameOpened(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_CLOSING:
((InternalFrameListener)listeners[i+1]).internalFrameClosing(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_CLOSED:
((InternalFrameListener)listeners[i+1]).internalFrameClosed(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_ICONIFIED:
((InternalFrameListener)listeners[i+1]).internalFrameIconified(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_DEICONIFIED:
((InternalFrameListener)listeners[i+1]).internalFrameDeiconified(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_ACTIVATED:
((InternalFrameListener)listeners[i+1]).internalFrameActivated(e);
break;
case InternalFrameEvent.INTERNAL_FRAME_DEACTIVATED:
((InternalFrameListener)listeners[i+1]).internalFrameDeactivated(e);
break;
default:
break;
}
}
}
/* we could do it off the event, but at the moment, that's not how
I'm implementing it */
// if (id == InternalFrameEvent.INTERNAL_FRAME_CLOSING) {
// doDefaultCloseAction();
// }
}
/** {@collect.stats}
* Fires an
* <code>INTERNAL_FRAME_CLOSING</code> event
* and then performs the action specified by
* the internal frame's default close operation.
* This method is typically invoked by the
* look-and-feel-implemented action handler
* for the internal frame's close button.
*
* @since 1.3
* @see #setDefaultCloseOperation
* @see javax.swing.event.InternalFrameEvent#INTERNAL_FRAME_CLOSING
*/
public void doDefaultCloseAction() {
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_CLOSING);
switch(defaultCloseOperation) {
case DO_NOTHING_ON_CLOSE:
break;
case HIDE_ON_CLOSE:
setVisible(false);
if (isSelected())
try {
setSelected(false);
} catch (PropertyVetoException pve) {}
/* should this activate the next frame? that's really
desktopmanager's policy... */
break;
case DISPOSE_ON_CLOSE:
try {
fireVetoableChange(IS_CLOSED_PROPERTY, Boolean.FALSE,
Boolean.TRUE);
isClosed = true;
setVisible(false);
firePropertyChange(IS_CLOSED_PROPERTY, Boolean.FALSE,
Boolean.TRUE);
dispose();
} catch (PropertyVetoException pve) {}
break;
default:
break;
}
}
/** {@collect.stats}
* Sets the operation that will happen by default when
* the user initiates a "close" on this internal frame.
* The possible choices are:
* <p>
* <dl>
* <dt><code>DO_NOTHING_ON_CLOSE</code>
* <dd> Do nothing.
* This requires the program to handle the operation
* in the <code>windowClosing</code> method
* of a registered <code>InternalFrameListener</code> object.
* <dt><code>HIDE_ON_CLOSE</code>
* <dd> Automatically make the internal frame invisible.
* <dt><code>DISPOSE_ON_CLOSE</code>
* <dd> Automatically dispose of the internal frame.
* </dl>
* <p>
* The default value is <code>DISPOSE_ON_CLOSE</code>.
* Before performing the specified close operation,
* the internal frame fires
* an <code>INTERNAL_FRAME_CLOSING</code> event.
*
* @param operation one of the following constants defined in
* <code>javax.swing.WindowConstants</code>
* (an interface implemented by
* <code>JInternalFrame</code>):
* <code>DO_NOTHING_ON_CLOSE</code>,
* <code>HIDE_ON_CLOSE</code>, or
* <code>DISPOSE_ON_CLOSE</code>
*
* @see #addInternalFrameListener
* @see #getDefaultCloseOperation
* @see #setVisible
* @see #dispose
* @see InternalFrameEvent#INTERNAL_FRAME_CLOSING
*/
public void setDefaultCloseOperation(int operation) {
this.defaultCloseOperation = operation;
}
/** {@collect.stats}
* Returns the default operation that occurs when the user
* initiates a "close" on this internal frame.
* @return the operation that will occur when the user closes the internal
* frame
* @see #setDefaultCloseOperation
*/
public int getDefaultCloseOperation() {
return defaultCloseOperation;
}
/** {@collect.stats}
* Causes subcomponents of this <code>JInternalFrame</code>
* to be laid out at their preferred size. Internal frames that are
* iconized or maximized are first restored and then packed. If the
* internal frame is unable to be restored its state is not changed
* and will not be packed.
*
* @see java.awt.Window#pack
*/
public void pack() {
try {
if (isIcon()) {
setIcon(false);
} else if (isMaximum()) {
setMaximum(false);
}
} catch(PropertyVetoException e) {
return;
}
setSize(getPreferredSize());
validate();
}
/** {@collect.stats}
* If the internal frame is not visible,
* brings the internal frame to the front,
* makes it visible,
* and attempts to select it.
* The first time the internal frame is made visible,
* this method also fires an <code>INTERNAL_FRAME_OPENED</code> event.
* This method does nothing if the internal frame is already visible.
* Invoking this method
* has the same result as invoking
* <code>setVisible(true)</code>.
*
* @see #moveToFront
* @see #setSelected
* @see InternalFrameEvent#INTERNAL_FRAME_OPENED
* @see #setVisible
*/
public void show() {
// bug 4312922
if (isVisible()) {
//match the behavior of setVisible(true): do nothing
return;
}
// bug 4149505
if (!opened) {
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_OPENED);
opened = true;
}
/* icon default visibility is false; set it to true so that it shows
up when user iconifies frame */
getDesktopIcon().setVisible(true);
toFront();
super.show();
if (isIcon) {
return;
}
if (!isSelected()) {
try {
setSelected(true);
} catch (PropertyVetoException pve) {}
}
}
public void hide() {
if (isIcon()) {
getDesktopIcon().setVisible(false);
}
super.hide();
}
/** {@collect.stats}
* Makes this internal frame
* invisible, unselected, and closed.
* If the frame is not already closed,
* this method fires an
* <code>INTERNAL_FRAME_CLOSED</code> event.
* The results of invoking this method are similar to
* <code>setClosed(true)</code>,
* but <code>dispose</code> always succeeds in closing
* the internal frame and does not fire
* an <code>INTERNAL_FRAME_CLOSING</code> event.
*
* @see javax.swing.event.InternalFrameEvent#INTERNAL_FRAME_CLOSED
* @see #setVisible
* @see #setSelected
* @see #setClosed
*/
public void dispose() {
if (isVisible()) {
setVisible(false);
}
if (isSelected()) {
try {
setSelected(false);
} catch (PropertyVetoException pve) {}
}
if (!isClosed) {
firePropertyChange(IS_CLOSED_PROPERTY, Boolean.FALSE, Boolean.TRUE);
isClosed = true;
}
fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_CLOSED);
}
/** {@collect.stats}
* Brings this internal frame to the front.
* Places this internal frame at the top of the stacking order
* and makes the corresponding adjustment to other visible internal
* frames.
*
* @see java.awt.Window#toFront
* @see #moveToFront
*/
public void toFront() {
moveToFront();
}
/** {@collect.stats}
* Sends this internal frame to the back.
* Places this internal frame at the bottom of the stacking order
* and makes the corresponding adjustment to other visible
* internal frames.
*
* @see java.awt.Window#toBack
* @see #moveToBack
*/
public void toBack() {
moveToBack();
}
/** {@collect.stats}
* Does nothing because <code>JInternalFrame</code>s must always be roots of a focus
* traversal cycle.
*
* @param focusCycleRoot this value is ignored
* @see #isFocusCycleRoot
* @see java.awt.Container#setFocusTraversalPolicy
* @see java.awt.Container#getFocusTraversalPolicy
* @since 1.4
*/
public final void setFocusCycleRoot(boolean focusCycleRoot) {
}
/** {@collect.stats}
* Always returns <code>true</code> because all <code>JInternalFrame</code>s must be
* roots of a focus traversal cycle.
*
* @return <code>true</code>
* @see #setFocusCycleRoot
* @see java.awt.Container#setFocusTraversalPolicy
* @see java.awt.Container#getFocusTraversalPolicy
* @since 1.4
*/
public final boolean isFocusCycleRoot() {
return true;
}
/** {@collect.stats}
* Always returns <code>null</code> because <code>JInternalFrame</code>s
* must always be roots of a focus
* traversal cycle.
*
* @return <code>null</code>
* @see java.awt.Container#isFocusCycleRoot()
* @since 1.4
*/
public final Container getFocusCycleRootAncestor() {
return null;
}
/** {@collect.stats}
* Gets the warning string that is displayed with this internal frame.
* Since an internal frame is always secure (since it's fully
* contained within a window that might need a warning string)
* this method always returns <code>null</code>.
* @return <code>null</code>
* @see java.awt.Window#getWarningString
*/
public final String getWarningString() {
return null;
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code>
* in <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
boolean old = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
ui.installUI(this);
} finally {
setRootPaneCheckingEnabled(old);
}
}
}
}
/* Called from the JComponent's EnableSerializationFocusListener to
* do any Swing-specific pre-serialization configuration.
*/
void compWriteObjectNotify() {
// need to disable rootpane checking for InternalFrame: 4172083
boolean old = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
super.compWriteObjectNotify();
}
finally {
setRootPaneCheckingEnabled(old);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JInternalFrame</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JInternalFrame</code>
*/
protected String paramString() {
String rootPaneString = (rootPane != null ?
rootPane.toString() : "");
String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
"true" : "false");
String closableString = (closable ? "true" : "false");
String isClosedString = (isClosed ? "true" : "false");
String maximizableString = (maximizable ? "true" : "false");
String isMaximumString = (isMaximum ? "true" : "false");
String iconableString = (iconable ? "true" : "false");
String isIconString = (isIcon ? "true" : "false");
String resizableString = (resizable ? "true" : "false");
String isSelectedString = (isSelected ? "true" : "false");
String frameIconString = (frameIcon != null ?
frameIcon.toString() : "");
String titleString = (title != null ?
title : "");
String desktopIconString = (desktopIcon != null ?
desktopIcon.toString() : "");
String openedString = (opened ? "true" : "false");
String defaultCloseOperationString;
if (defaultCloseOperation == HIDE_ON_CLOSE) {
defaultCloseOperationString = "HIDE_ON_CLOSE";
} else if (defaultCloseOperation == DISPOSE_ON_CLOSE) {
defaultCloseOperationString = "DISPOSE_ON_CLOSE";
} else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) {
defaultCloseOperationString = "DO_NOTHING_ON_CLOSE";
} else defaultCloseOperationString = "";
return super.paramString() +
",closable=" + closableString +
",defaultCloseOperation=" + defaultCloseOperationString +
",desktopIcon=" + desktopIconString +
",frameIcon=" + frameIconString +
",iconable=" + iconableString +
",isClosed=" + isClosedString +
",isIcon=" + isIconString +
",isMaximum=" + isMaximumString +
",isSelected=" + isSelectedString +
",maximizable=" + maximizableString +
",opened=" + openedString +
",resizable=" + resizableString +
",rootPane=" + rootPaneString +
",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString +
",title=" + titleString;
}
// ======= begin optimized frame dragging defence code ==============
boolean isDragging = false;
boolean danger = false;
/** {@collect.stats}
* Overridden to allow optimized painting when the
* internal frame is being dragged.
*/
protected void paintComponent(Graphics g) {
if (isDragging) {
// System.out.println("ouch");
danger = true;
}
super.paintComponent(g);
}
// ======= end optimized frame dragging defence code ==============
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>JInternalFrame</code>.
* For internal frames, the <code>AccessibleContext</code>
* takes the form of an
* <code>AccessibleJInternalFrame</code> object.
* A new <code>AccessibleJInternalFrame</code> instance is created if necessary.
*
* @return an <code>AccessibleJInternalFrame</code> that serves as the
* <code>AccessibleContext</code> of this
* <code>JInternalFrame</code>
* @see AccessibleJInternalFrame
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJInternalFrame();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JInternalFrame</code> class. It provides an implementation of the
* Java Accessibility API appropriate to internal frame user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJInternalFrame extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be <code>null</code> if this
* object does not have a name
* @see #setAccessibleName
*/
public String getAccessibleName() {
String name = accessibleName;
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
if (name == null) {
name = getTitle();
}
return name;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.INTERNAL_FRAME;
}
/** {@collect.stats}
* Gets the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is responsible for implementing the
* <code>AccessibleValue</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
//
// AccessibleValue methods
//
/** {@collect.stats}
* Get the value of this object as a Number.
*
* @return value of the object -- can be <code>null</code> if this object does not
* have a value
*/
public Number getCurrentAccessibleValue() {
return new Integer(getLayer());
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return <code>true</code> if the value was set
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
setLayer(new Integer(n.intValue()));
return true;
}
/** {@collect.stats}
* Get the minimum value of this object as a Number.
*
* @return Minimum value of the object; <code>null</code> if this object does not
* have a minimum value
*/
public Number getMinimumAccessibleValue() {
return new Integer(Integer.MIN_VALUE);
}
/** {@collect.stats}
* Get the maximum value of this object as a Number.
*
* @return Maximum value of the object; <code>null</code> if this object does not
* have a maximum value
*/
public Number getMaximumAccessibleValue() {
return new Integer(Integer.MAX_VALUE);
}
} // AccessibleJInternalFrame
/** {@collect.stats}
* This component represents an iconified version of a
* <code>JInternalFrame</code>.
* This API should NOT BE USED by Swing applications, as it will go
* away in future versions of Swing as its functionality is moved into
* <code>JInternalFrame</code>. This class is public only so that
* UI objects can display a desktop icon. If an application
* wants to display a desktop icon, it should create a
* <code>JInternalFrame</code> instance and iconify it.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author David Kloba
*/
static public class JDesktopIcon extends JComponent implements Accessible
{
JInternalFrame internalFrame;
/** {@collect.stats}
* Creates an icon for an internal frame.
*
* @param f the <code>JInternalFrame</code>
* for which the icon is created
*/
public JDesktopIcon(JInternalFrame f) {
setVisible(false);
setInternalFrame(f);
updateUI();
}
/** {@collect.stats}
* Returns the look-and-feel object that renders this component.
*
* @return the <code>DesktopIconUI</code> object that renders
* this component
*/
public DesktopIconUI getUI() {
return (DesktopIconUI)ui;
}
/** {@collect.stats}
* Sets the look-and-feel object that renders this component.
*
* @param ui the <code>DesktopIconUI</code> look-and-feel object
* @see UIDefaults#getUI
*/
public void setUI(DesktopIconUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Returns the <code>JInternalFrame</code> that this
* <code>DesktopIcon</code> is associated with.
*
* @return the <code>JInternalFrame</code> with which this icon
* is associated
*/
public JInternalFrame getInternalFrame() {
return internalFrame;
}
/** {@collect.stats}
* Sets the <code>JInternalFrame</code> with which this
* <code>DesktopIcon</code> is associated.
*
* @param f the <code>JInternalFrame</code> with which this icon
* is associated
*/
public void setInternalFrame(JInternalFrame f) {
internalFrame = f;
}
/** {@collect.stats}
* Convenience method to ask the icon for the <code>Desktop</code>
* object it belongs to.
*
* @return the <code>JDesktopPane</code> that contains this
* icon's internal frame, or <code>null</code> if none found
*/
public JDesktopPane getDesktopPane() {
if(getInternalFrame() != null)
return getInternalFrame().getDesktopPane();
return null;
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the look and feel
* has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
boolean hadUI = (ui != null);
setUI((DesktopIconUI)UIManager.getUI(this));
invalidate();
Dimension r = getPreferredSize();
setSize(r.width, r.height);
if (internalFrame != null && internalFrame.getUI() != null) { // don't do this if UI not created yet
SwingUtilities.updateComponentTreeUI(internalFrame);
}
}
/* This method is called if updateUI was called on the associated
* JInternalFrame. It's necessary to avoid infinite recursion.
*/
void updateUIWhenHidden() {
/* Update this UI and any associated internal frame */
setUI((DesktopIconUI)UIManager.getUI(this));
Dimension r = getPreferredSize();
setSize(r.width, r.height);
invalidate();
Component[] children = getComponents();
if (children != null) {
for(int i = 0; i < children.length; i++) {
SwingUtilities.updateComponentTreeUI(children[i]);
}
}
}
/** {@collect.stats}
* Returns the name of the look-and-feel
* class that renders this component.
*
* @return the string "DesktopIconUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return "DesktopIconUI";
}
////////////////
// Serialization support
////////////////
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals("DesktopIconUI")) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JDesktopIcon.
* For desktop icons, the AccessibleContext takes the form of an
* AccessibleJDesktopIcon.
* A new AccessibleJDesktopIcon instance is created if necessary.
*
* @return an AccessibleJDesktopIcon that serves as the
* AccessibleContext of this JDesktopIcon
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJDesktopIcon();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JInternalFrame.JDesktopIcon</code> class. It provides an
* implementation of the Java Accessibility API appropriate to
* desktop icon user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJDesktopIcon extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.DESKTOP_ICON;
}
/** {@collect.stats}
* Gets the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is responsible for implementing the
* <code>AccessibleValue</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
//
// AccessibleValue methods
//
/** {@collect.stats}
* Gets the value of this object as a <code>Number</code>.
*
* @return value of the object -- can be <code>null</code> if this object does not
* have a value
*/
public Number getCurrentAccessibleValue() {
AccessibleContext a = JDesktopIcon.this.getInternalFrame().getAccessibleContext();
AccessibleValue v = a.getAccessibleValue();
if (v != null) {
return v.getCurrentAccessibleValue();
} else {
return null;
}
}
/** {@collect.stats}
* Sets the value of this object as a <code>Number</code>.
*
* @return <code>true</code> if the value was set
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
AccessibleContext a = JDesktopIcon.this.getInternalFrame().getAccessibleContext();
AccessibleValue v = a.getAccessibleValue();
if (v != null) {
return v.setCurrentAccessibleValue(n);
} else {
return false;
}
}
/** {@collect.stats}
* Gets the minimum value of this object as a <code>Number</code>.
*
* @return minimum value of the object; <code>null</code> if this object does not
* have a minimum value
*/
public Number getMinimumAccessibleValue() {
AccessibleContext a = JDesktopIcon.this.getInternalFrame().getAccessibleContext();
if (a instanceof AccessibleValue) {
return ((AccessibleValue)a).getMinimumAccessibleValue();
} else {
return null;
}
}
/** {@collect.stats}
* Gets the maximum value of this object as a <code>Number</code>.
*
* @return maximum value of the object; <code>null</code> if this object does not
* have a maximum value
*/
public Number getMaximumAccessibleValue() {
AccessibleContext a = JDesktopIcon.this.getInternalFrame().getAccessibleContext();
if (a instanceof AccessibleValue) {
return ((AccessibleValue)a).getMaximumAccessibleValue();
} else {
return null;
}
}
} // AccessibleJDesktopIcon
}
}
|
Java
|
/*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.awt.event.*;
import sun.awt.AppContext;
import sun.swing.AccumulativeRunnable;
/** {@collect.stats}
* An abstract class to perform lengthy GUI-interacting tasks in a
* dedicated thread.
*
* <p>
* When writing a multi-threaded application using Swing, there are
* two constraints to keep in mind:
* (refer to
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
* How to Use Threads
* </a> for more details):
* <ul>
* <li> Time-consuming tasks should not be run on the <i>Event
* Dispatch Thread</i>. Otherwise the application becomes unresponsive.
* </li>
* <li> Swing components should be accessed on the <i>Event
* Dispatch Thread</i> only.
* </li>
* </ul>
*
* <p>
*
* <p>
* These constraints mean that a GUI application with time intensive
* computing needs at least two threads: 1) a thread to perform the lengthy
* task and 2) the <i>Event Dispatch Thread</i> (EDT) for all GUI-related
* activities. This involves inter-thread communication which can be
* tricky to implement.
*
* <p>
* {@code SwingWorker} is designed for situations where you need to have a long
* running task run in a background thread and provide updates to the UI
* either when done, or while processing.
* Subclasses of {@code SwingWorker} must implement
* the {@link #doInBackground} method to perform the background computation.
*
*
* <p>
* <b>Workflow</b>
* <p>
* There are three threads involved in the life cycle of a
* {@code SwingWorker} :
* <ul>
* <li>
* <p>
* <i>Current</i> thread: The {@link #execute} method is
* called on this thread. It schedules {@code SwingWorker} for the execution on a
* <i>worker</i>
* thread and returns immediately. One can wait for the {@code SwingWorker} to
* complete using the {@link #get get} methods.
* <li>
* <p>
* <i>Worker</i> thread: The {@link #doInBackground}
* method is called on this thread.
* This is where all background activities should happen. To notify
* {@code PropertyChangeListeners} about bound properties changes use the
* {@link #firePropertyChange firePropertyChange} and
* {@link #getPropertyChangeSupport} methods. By default there are two bound
* properties available: {@code state} and {@code progress}.
* <li>
* <p>
* <i>Event Dispatch Thread</i>: All Swing related activities occur
* on this thread. {@code SwingWorker} invokes the
* {@link #process process} and {@link #done} methods and notifies
* any {@code PropertyChangeListeners} on this thread.
* </ul>
*
* <p>
* Often, the <i>Current</i> thread is the <i>Event Dispatch
* Thread</i>.
*
*
* <p>
* Before the {@code doInBackground} method is invoked on a <i>worker</i> thread,
* {@code SwingWorker} notifies any {@code PropertyChangeListeners} about the
* {@code state} property change to {@code StateValue.STARTED}. After the
* {@code doInBackground} method is finished the {@code done} method is
* executed. Then {@code SwingWorker} notifies any {@code PropertyChangeListeners}
* about the {@code state} property change to {@code StateValue.DONE}.
*
* <p>
* {@code SwingWorker} is only designed to be executed once. Executing a
* {@code SwingWorker} more than once will not result in invoking the
* {@code doInBackground} method twice.
*
* <p>
* <b>Sample Usage</b>
* <p>
* The following example illustrates the simplest use case. Some
* processing is done in the background and when done you update a Swing
* component.
*
* <p>
* Say we want to find the "Meaning of Life" and display the result in
* a {@code JLabel}.
*
* <pre>
* final JLabel label;
* class MeaningOfLifeFinder extends SwingWorker<String, Object> {
* {@code @Override}
* public String doInBackground() {
* return findTheMeaningOfLife();
* }
*
* {@code @Override}
* protected void done() {
* try {
* label.setText(get());
* } catch (Exception ignore) {
* }
* }
* }
*
* (new MeaningOfLifeFinder()).execute();
* </pre>
*
* <p>
* The next example is useful in situations where you wish to process data
* as it is ready on the <i>Event Dispatch Thread</i>.
*
* <p>
* Now we want to find the first N prime numbers and display the results in a
* {@code JTextArea}. While this is computing, we want to update our
* progress in a {@code JProgressBar}. Finally, we also want to print
* the prime numbers to {@code System.out}.
* <pre>
* class PrimeNumbersTask extends
* SwingWorker<List<Integer>, Integer> {
* PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
* //initialize
* }
*
* {@code @Override}
* public List<Integer> doInBackground() {
* while (! enough && ! isCancelled()) {
* number = nextPrimeNumber();
* publish(number);
* setProgress(100 * numbers.size() / numbersToFind);
* }
* }
* return numbers;
* }
*
* {@code @Override}
* protected void process(List<Integer> chunks) {
* for (int number : chunks) {
* textArea.append(number + "\n");
* }
* }
* }
*
* JTextArea textArea = new JTextArea();
* final JProgressBar progressBar = new JProgressBar(0, 100);
* PrimeNumbersTask task = new PrimeNumbersTask(textArea, N);
* task.addPropertyChangeListener(
* new PropertyChangeListener() {
* public void propertyChange(PropertyChangeEvent evt) {
* if ("progress".equals(evt.getPropertyName())) {
* progressBar.setValue((Integer)evt.getNewValue());
* }
* }
* });
*
* task.execute();
* System.out.println(task.get()); //prints all prime numbers we have got
* </pre>
*
* <p>
* Because {@code SwingWorker} implements {@code Runnable}, a
* {@code SwingWorker} can be submitted to an
* {@link java.util.concurrent.Executor} for execution.
*
* @author Igor Kushnirskiy
*
* @param <T> the result type returned by this {@code SwingWorker's}
* {@code doInBackground} and {@code get} methods
* @param <V> the type used for carrying out intermediate results by this
* {@code SwingWorker's} {@code publish} and {@code process} methods
*
* @since 1.6
*/
public abstract class SwingWorker<T, V> implements RunnableFuture<T> {
/** {@collect.stats}
* number of worker threads.
*/
private static final int MAX_WORKER_THREADS = 10;
/** {@collect.stats}
* current progress.
*/
private volatile int progress;
/** {@collect.stats}
* current state.
*/
private volatile StateValue state;
/** {@collect.stats}
* everything is run inside this FutureTask. Also it is used as
* a delegatee for the Future API.
*/
private final FutureTask<T> future;
/** {@collect.stats}
* all propertyChangeSupport goes through this.
*/
private final PropertyChangeSupport propertyChangeSupport;
/** {@collect.stats}
* handler for {@code process} mehtod.
*/
private AccumulativeRunnable<V> doProcess;
/** {@collect.stats}
* handler for progress property change notifications.
*/
private AccumulativeRunnable<Integer> doNotifyProgressChange;
private final AccumulativeRunnable<Runnable> doSubmit = getDoSubmit();
/** {@collect.stats}
* Values for the {@code state} bound property.
* @since 1.6
*/
public enum StateValue {
/** {@collect.stats}
* Initial {@code SwingWorker} state.
*/
PENDING,
/** {@collect.stats}
* {@code SwingWorker} is {@code STARTED}
* before invoking {@code doInBackground}.
*/
STARTED,
/** {@collect.stats}
* {@code SwingWorker} is {@code DONE}
* after {@code doInBackground} method
* is finished.
*/
DONE
};
/** {@collect.stats}
* Constructs this {@code SwingWorker}.
*/
public SwingWorker() {
Callable<T> callable =
new Callable<T>() {
public T call() throws Exception {
setState(StateValue.STARTED);
return doInBackground();
}
};
future = new FutureTask<T>(callable) {
@Override
protected void done() {
doneEDT();
setState(StateValue.DONE);
}
};
state = StateValue.PENDING;
propertyChangeSupport = new SwingWorkerPropertyChangeSupport(this);
doProcess = null;
doNotifyProgressChange = null;
}
/** {@collect.stats}
* Computes a result, or throws an exception if unable to do so.
*
* <p>
* Note that this method is executed only once.
*
* <p>
* Note: this method is executed in a background thread.
*
*
* @return the computed result
* @throws Exception if unable to compute a result
*
*/
protected abstract T doInBackground() throws Exception ;
/** {@collect.stats}
* Sets this {@code Future} to the result of computation unless
* it has been cancelled.
*/
public final void run() {
future.run();
}
/** {@collect.stats}
* Sends data chunks to the {@link #process} method. This method is to be
* used from inside the {@code doInBackground} method to deliver
* intermediate results
* for processing on the <i>Event Dispatch Thread</i> inside the
* {@code process} method.
*
* <p>
* Because the {@code process} method is invoked asynchronously on
* the <i>Event Dispatch Thread</i>
* multiple invocations to the {@code publish} method
* might occur before the {@code process} method is executed. For
* performance purposes all these invocations are coalesced into one
* invocation with concatenated arguments.
*
* <p>
* For example:
*
* <pre>
* publish("1");
* publish("2", "3");
* publish("4", "5", "6");
* </pre>
*
* might result in:
*
* <pre>
* process("1", "2", "3", "4", "5", "6")
* </pre>
*
* <p>
* <b>Sample Usage</b>. This code snippet loads some tabular data and
* updates {@code DefaultTableModel} with it. Note that it safe to mutate
* the tableModel from inside the {@code process} method because it is
* invoked on the <i>Event Dispatch Thread</i>.
*
* <pre>
* class TableSwingWorker extends
* SwingWorker<DefaultTableModel, Object[]> {
* private final DefaultTableModel tableModel;
*
* public TableSwingWorker(DefaultTableModel tableModel) {
* this.tableModel = tableModel;
* }
*
* {@code @Override}
* protected DefaultTableModel doInBackground() throws Exception {
* for (Object[] row = loadData();
* ! isCancelled() && row != null;
* row = loadData()) {
* publish((Object[]) row);
* }
* return tableModel;
* }
*
* {@code @Override}
* protected void process(List<Object[]> chunks) {
* for (Object[] row : chunks) {
* tableModel.addRow(row);
* }
* }
* }
* </pre>
*
* @param chunks intermediate results to process
*
* @see #process
*
*/
protected final void publish(V... chunks) {
synchronized (this) {
if (doProcess == null) {
doProcess = new AccumulativeRunnable<V>() {
@Override
public void run(List<V> args) {
process(args);
}
@Override
protected void submit() {
doSubmit.add(this);
}
};
}
}
doProcess.add(chunks);
}
/** {@collect.stats}
* Receives data chunks from the {@code publish} method asynchronously on the
* <i>Event Dispatch Thread</i>.
*
* <p>
* Please refer to the {@link #publish} method for more details.
*
* @param chunks intermediate results to process
*
* @see #publish
*
*/
protected void process(List<V> chunks) {
}
/** {@collect.stats}
* Executed on the <i>Event Dispatch Thread</i> after the {@code doInBackground}
* method is finished. The default
* implementation does nothing. Subclasses may override this method to
* perform completion actions on the <i>Event Dispatch Thread</i>. Note
* that you can query status inside the implementation of this method to
* determine the result of this task or whether this task has been cancelled.
*
* @see #doInBackground
* @see #isCancelled()
* @see #get
*/
protected void done() {
}
/** {@collect.stats}
* Sets the {@code progress} bound property.
* The value should be from 0 to 100.
*
* <p>
* Because {@code PropertyChangeListener}s are notified asynchronously on
* the <i>Event Dispatch Thread</i> multiple invocations to the
* {@code setProgress} method might occur before any
* {@code PropertyChangeListeners} are invoked. For performance purposes
* all these invocations are coalesced into one invocation with the last
* invocation argument only.
*
* <p>
* For example, the following invokations:
*
* <pre>
* setProgress(1);
* setProgress(2);
* setProgress(3);
* </pre>
*
* might result in a single {@code PropertyChangeListener} notification with
* the value {@code 3}.
*
* @param progress the progress value to set
* @throws IllegalArgumentException is value not from 0 to 100
*/
protected final void setProgress(int progress) {
if (progress < 0 || progress > 100) {
throw new IllegalArgumentException("the value should be from 0 to 100");
}
if (this.progress == progress) {
return;
}
int oldProgress = this.progress;
this.progress = progress;
if (! getPropertyChangeSupport().hasListeners("progress")) {
return;
}
synchronized (this) {
if (doNotifyProgressChange == null) {
doNotifyProgressChange =
new AccumulativeRunnable<Integer>() {
@Override
public void run(List<Integer> args) {
firePropertyChange("progress",
args.get(0),
args.get(args.size() - 1));
}
@Override
protected void submit() {
doSubmit.add(this);
}
};
}
}
doNotifyProgressChange.add(oldProgress, progress);
}
/** {@collect.stats}
* Returns the {@code progress} bound property.
*
* @return the progress bound property.
*/
public final int getProgress() {
return progress;
}
/** {@collect.stats}
* Schedules this {@code SwingWorker} for execution on a <i>worker</i>
* thread. There are a number of <i>worker</i> threads available. In the
* event all <i>worker</i> threads are busy handling other
* {@code SwingWorkers} this {@code SwingWorker} is placed in a waiting
* queue.
*
* <p>
* Note:
* {@code SwingWorker} is only designed to be executed once. Executing a
* {@code SwingWorker} more than once will not result in invoking the
* {@code doInBackground} method twice.
*/
public final void execute() {
getWorkersExecutorService().execute(this);
}
// Future methods START
/** {@collect.stats}
* {@inheritDoc}
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public final boolean isCancelled() {
return future.isCancelled();
}
/** {@collect.stats}
* {@inheritDoc}
*/
public final boolean isDone() {
return future.isDone();
}
/** {@collect.stats}
* {@inheritDoc}
* <p>
* Note: calling {@code get} on the <i>Event Dispatch Thread</i> blocks
* <i>all</i> events, including repaints, from being processed until this
* {@code SwingWorker} is complete.
*
* <p>
* When you want the {@code SwingWorker} to block on the <i>Event
* Dispatch Thread</i> we recommend that you use a <i>modal dialog</i>.
*
* <p>
* For example:
*
* <pre>
* class SwingWorkerCompletionWaiter extends PropertyChangeListener {
* private JDialog dialog;
*
* public SwingWorkerCompletionWaiter(JDialog dialog) {
* this.dialog = dialog;
* }
*
* public void propertyChange(PropertyChangeEvent event) {
* if ("state".equals(event.getPropertyName())
* && SwingWorker.StateValue.DONE == event.getNewValue()) {
* dialog.setVisible(false);
* dialog.dispose();
* }
* }
* }
* JDialog dialog = new JDialog(owner, true);
* swingWorker.addPropertyChangeListener(
* new SwingWorkerCompletionWaiter(dialog));
* swingWorker.execute();
* //the dialog will be visible until the SwingWorker is done
* dialog.setVisible(true);
* </pre>
*/
public final T get() throws InterruptedException, ExecutionException {
return future.get();
}
/** {@collect.stats}
* {@inheritDoc}
* <p>
* Please refer to {@link #get} for more details.
*/
public final T get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
// Future methods END
// PropertyChangeSupports methods START
/** {@collect.stats}
* Adds a {@code PropertyChangeListener} to the listener list. The listener
* is registered for all properties. The same listener object may be added
* more than once, and will be called as many times as it is added. If
* {@code listener} is {@code null}, no exception is thrown and no action is taken.
*
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
* @param listener the {@code PropertyChangeListener} to be added
*/
public final void addPropertyChangeListener(PropertyChangeListener listener) {
getPropertyChangeSupport().addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a {@code PropertyChangeListener} from the listener list. This
* removes a {@code PropertyChangeListener} that was registered for all
* properties. If {@code listener} was added more than once to the same
* event source, it will be notified one less time after being removed. If
* {@code listener} is {@code null}, or was never added, no exception is
* thrown and no action is taken.
*
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
* @param listener the {@code PropertyChangeListener} to be removed
*/
public final void removePropertyChangeListener(PropertyChangeListener listener) {
getPropertyChangeSupport().removePropertyChangeListener(listener);
}
/** {@collect.stats}
* Reports a bound property update to any registered listeners. No event is
* fired if {@code old} and {@code new} are equal and non-null.
*
* <p>
* This {@code SwingWorker} will be the source for
* any generated events.
*
* <p>
* When called off the <i>Event Dispatch Thread</i>
* {@code PropertyChangeListeners} are notified asynchronously on
* the <i>Event Dispatch Thread</i>.
* <p>
* Note: This is merely a convenience wrapper. All work is delegated to
* {@code PropertyChangeSupport} from {@link #getPropertyChangeSupport}.
*
*
* @param propertyName the programmatic name of the property that was
* changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public final void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
getPropertyChangeSupport().firePropertyChange(propertyName,
oldValue, newValue);
}
/** {@collect.stats}
* Returns the {@code PropertyChangeSupport} for this {@code SwingWorker}.
* This method is used when flexible access to bound properties support is
* needed.
* <p>
* This {@code SwingWorker} will be the source for
* any generated events.
*
* <p>
* Note: The returned {@code PropertyChangeSupport} notifies any
* {@code PropertyChangeListener}s asynchronously on the <i>Event Dispatch
* Thread</i> in the event that {@code firePropertyChange} or
* {@code fireIndexedPropertyChange} are called off the <i>Event Dispatch
* Thread</i>.
*
* @return {@code PropertyChangeSupport} for this {@code SwingWorker}
*/
public final PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
// PropertyChangeSupports methods END
/** {@collect.stats}
* Returns the {@code SwingWorker} state bound property.
*
* @return the current state
*/
public final StateValue getState() {
/*
* DONE is a speacial case
* to keep getState and isDone is sync
*/
if (isDone()) {
return StateValue.DONE;
} else {
return state;
}
}
/** {@collect.stats}
* Sets this {@code SwingWorker} state bound property.
* @param the state state to set
*/
private void setState(StateValue state) {
StateValue old = this.state;
this.state = state;
firePropertyChange("state", old, state);
}
/** {@collect.stats}
* Invokes {@code done} on the EDT.
*/
private void doneEDT() {
Runnable doDone =
new Runnable() {
public void run() {
done();
}
};
if (SwingUtilities.isEventDispatchThread()) {
doDone.run();
} else {
doSubmit.add(doDone);
}
}
/** {@collect.stats}
* returns workersExecutorService.
*
* returns the service stored in the appContext or creates it if
* necessary. If the last one it triggers autoShutdown thread to
* get started.
*
* @return ExecutorService for the {@code SwingWorkers}
* @see #startAutoShutdownThread
*/
private static synchronized ExecutorService getWorkersExecutorService() {
final AppContext appContext = AppContext.getAppContext();
Object obj = appContext.get(SwingWorker.class);
if (obj == null) {
//this creates non-daemon threads.
ThreadFactory threadFactory =
new ThreadFactory() {
final ThreadFactory defaultFactory =
Executors.defaultThreadFactory();
public Thread newThread(final Runnable r) {
Thread thread =
defaultFactory.newThread(r);
thread.setName("SwingWorker-"
+ thread.getName());
return thread;
}
};
/*
* We want a to have no more than MAX_WORKER_THREADS
* running threads.
*
* We want a worker thread to wait no longer than 1 second
* for new tasks before terminating.
*/
obj = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
1L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory) {
private final ReentrantLock pauseLock = new ReentrantLock();
private final Condition unpaused = pauseLock.newCondition();
private boolean isPaused = false;
private final ReentrantLock executeLock = new ReentrantLock();
@Override
public void execute(Runnable command) {
/*
* ThreadPoolExecutor first tries to run task
* in a corePool. If all threads are busy it
* tries to add task to the waiting queue. If it
* fails it run task in maximumPool.
*
* We want corePool to be 0 and
* maximumPool to be MAX_WORKER_THREADS
* We need to change the order of the execution.
* First try corePool then try maximumPool
* pool and only then store to the waiting
* queue. We can not do that because we would
* need access to the private methods.
*
* Instead we enlarge corePool to
* MAX_WORKER_THREADS before the execution and
* shrink it back to 0 after.
* It does pretty much what we need.
*
* While we changing the corePoolSize we need
* to stop running worker threads from accepting new
* tasks.
*/
//we need atomicity for the execute method.
executeLock.lock();
try {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
setCorePoolSize(MAX_WORKER_THREADS);
super.execute(command);
setCorePoolSize(0);
pauseLock.lock();
try {
isPaused = false;
unpaused.signalAll();
} finally {
pauseLock.unlock();
}
} finally {
executeLock.unlock();
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
pauseLock.lock();
try {
while(isPaused) {
unpaused.await();
}
} catch(InterruptedException ignore) {
} finally {
pauseLock.unlock();
}
}
};
appContext.put(SwingWorker.class, obj);
}
return (ExecutorService)obj;
}
private static final Object DO_SUBMIT_KEY = new Object(); // doSubmit
private static AccumulativeRunnable<Runnable> getDoSubmit() {
synchronized (DO_SUBMIT_KEY) {
final AppContext appContext = AppContext.getAppContext();
Object doSubmit = appContext.get(DO_SUBMIT_KEY);
if (doSubmit == null) {
doSubmit = new DoSubmitAccumulativeRunnable();
appContext.put(DO_SUBMIT_KEY, doSubmit);
}
return (AccumulativeRunnable<Runnable>) doSubmit;
}
}
private static class DoSubmitAccumulativeRunnable
extends AccumulativeRunnable<Runnable> implements ActionListener {
private final static int DELAY = (int) (1000 / 30);
@Override
protected void run(List<Runnable> args) {
for (Runnable runnable : args) {
runnable.run();
}
}
@Override
protected void submit() {
Timer timer = new Timer(DELAY, this);
timer.setRepeats(false);
timer.start();
}
public void actionPerformed(ActionEvent event) {
run();
}
}
private class SwingWorkerPropertyChangeSupport
extends PropertyChangeSupport {
SwingWorkerPropertyChangeSupport(Object source) {
super(source);
}
@Override
public void firePropertyChange(final PropertyChangeEvent evt) {
if (SwingUtilities.isEventDispatchThread()) {
super.firePropertyChange(evt);
} else {
doSubmit.add(
new Runnable() {
public void run() {
SwingWorkerPropertyChangeSupport.this
.firePropertyChange(evt);
}
});
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.awt.peer.ComponentPeer;
import java.awt.peer.ContainerPeer;
import java.awt.image.VolatileImage;
import java.security.AccessController;
import java.util.*;
import java.applet.*;
import sun.awt.AppContext;
import sun.awt.DisplayChangedListener;
import sun.awt.SunToolkit;
import sun.java2d.SunGraphicsEnvironment;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* This class manages repaint requests, allowing the number
* of repaints to be minimized, for example by collapsing multiple
* requests into a single repaint for members of a component tree.
* <p>
* As of 1.6 <code>RepaintManager</code> handles repaint requests
* for Swing's top level components (<code>JApplet</code>,
* <code>JWindow</code>, <code>JFrame</code> and <code>JDialog</code>).
* Any calls to <code>repaint</code> on one of these will call into the
* appropriate <code>addDirtyRegion</code> method.
*
* @author Arnaud Weber
*/
public class RepaintManager
{
/** {@collect.stats}
* Whether or not the RepaintManager should handle paint requests
* for top levels.
*/
static final boolean HANDLE_TOP_LEVEL_PAINT;
private static final short BUFFER_STRATEGY_NOT_SPECIFIED = 0;
private static final short BUFFER_STRATEGY_SPECIFIED_ON = 1;
private static final short BUFFER_STRATEGY_SPECIFIED_OFF = 2;
private static final short BUFFER_STRATEGY_TYPE;
/** {@collect.stats}
* Maps from GraphicsConfiguration to VolatileImage.
*/
private Map<GraphicsConfiguration,VolatileImage> volatileMap = new
HashMap<GraphicsConfiguration,VolatileImage>(1);
//
// As of 1.6 Swing handles scheduling of paint events from native code.
// That is, SwingPaintEventDispatcher is invoked on the toolkit thread,
// which in turn invokes nativeAddDirtyRegion. Because this is invoked
// from the native thread we can not invoke any public methods and so
// we introduce these added maps. So, any time nativeAddDirtyRegion is
// invoked the region is added to hwDirtyComponents and a work request
// is scheduled. When the work request is processed all entries in
// this map are pushed to the real map (dirtyComponents) and then
// painted with the rest of the components.
//
private Map<Container,Rectangle> hwDirtyComponents;
private Map<Component,Rectangle> dirtyComponents;
private Map<Component,Rectangle> tmpDirtyComponents;
private java.util.List<Component> invalidComponents;
// List of Runnables that need to be processed before painting from AWT.
private java.util.List<Runnable> runnableList;
boolean doubleBufferingEnabled = true;
private Dimension doubleBufferMaxSize;
// Support for both the standard and volatile offscreen buffers exists to
// provide backwards compatibility for the [rare] programs which may be
// calling getOffScreenBuffer() and not expecting to get a VolatileImage.
// Swing internally is migrating to use *only* the volatile image buffer.
// Support for standard offscreen buffer
//
DoubleBufferInfo standardDoubleBuffer;
/** {@collect.stats}
* Object responsible for hanlding core paint functionality.
*/
private PaintManager paintManager;
private static final Object repaintManagerKey = RepaintManager.class;
// Whether or not a VolatileImage should be used for double-buffered painting
static boolean volatileImageBufferEnabled = true;
/** {@collect.stats}
* Value of the system property awt.nativeDoubleBuffering.
*/
private static boolean nativeDoubleBuffering;
// The maximum number of times Swing will attempt to use the VolatileImage
// buffer during a paint operation.
private static final int VOLATILE_LOOP_MAX = 2;
/** {@collect.stats}
* Number of <code>beginPaint</code> that have been invoked.
*/
private int paintDepth = 0;
/** {@collect.stats}
* Type of buffer strategy to use. Will be one of the BUFFER_STRATEGY_
* constants.
*/
private short bufferStrategyType;
//
// BufferStrategyPaintManager has the unique characteristic that it
// must deal with the buffer being lost while painting to it. For
// example, if we paint a component and show it and the buffer has
// become lost we must repaint the whole window. To deal with that
// the PaintManager calls into repaintRoot, and if we're still in
// the process of painting the repaintRoot field is set to the JRootPane
// and after the current JComponent.paintImmediately call finishes
// paintImmediately will be invoked on the repaintRoot. In this
// way we don't try to show garbage to the screen.
//
/** {@collect.stats}
* True if we're in the process of painting the dirty regions. This is
* set to true in <code>paintDirtyRegions</code>.
*/
private boolean painting;
/** {@collect.stats}
* If the PaintManager calls into repaintRoot during painting this field
* will be set to the root.
*/
private JComponent repaintRoot;
/** {@collect.stats}
* The Thread that has initiated painting. If null it
* indicates painting is not currently in progress.
*/
private Thread paintThread;
/** {@collect.stats}
* Runnable used to process all repaint/revalidate requests.
*/
private final ProcessingRunnable processingRunnable;
static {
volatileImageBufferEnabled = "true".equals(AccessController.
doPrivileged(new GetPropertyAction(
"swing.volatileImageBufferEnabled", "true")));
boolean headless = GraphicsEnvironment.isHeadless();
if (volatileImageBufferEnabled && headless) {
volatileImageBufferEnabled = false;
}
nativeDoubleBuffering = "true".equals(AccessController.doPrivileged(
new GetPropertyAction("awt.nativeDoubleBuffering")));
String bs = AccessController.doPrivileged(
new GetPropertyAction("swing.bufferPerWindow"));
if (headless) {
BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_OFF;
}
else if (bs == null) {
BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_NOT_SPECIFIED;
}
else if ("true".equals(bs)) {
BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_ON;
}
else {
BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_OFF;
}
HANDLE_TOP_LEVEL_PAINT = "true".equals(AccessController.doPrivileged(
new GetPropertyAction("swing.handleTopLevelPaint", "true")));
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
if (ge instanceof SunGraphicsEnvironment) {
((SunGraphicsEnvironment)ge).addDisplayChangedListener(
new DisplayChangedHandler());
}
}
/** {@collect.stats}
* Return the RepaintManager for the calling thread given a Component.
*
* @param c a Component -- unused in the default implementation, but could
* be used by an overridden version to return a different RepaintManager
* depending on the Component
* @return the RepaintManager object
*/
public static RepaintManager currentManager(Component c) {
// Note: DisplayChangedRunnable passes in null as the component, so if
// component is ever used to determine the current
// RepaintManager, DisplayChangedRunnable will need to be modified
// accordingly.
return currentManager(AppContext.getAppContext());
}
/** {@collect.stats}
* Returns the RepaintManager for the specified AppContext. If
* a RepaintManager has not been created for the specified
* AppContext this will return null.
*/
static RepaintManager currentManager(AppContext appContext) {
RepaintManager rm = (RepaintManager)appContext.get(repaintManagerKey);
if (rm == null) {
rm = new RepaintManager(BUFFER_STRATEGY_TYPE);
appContext.put(repaintManagerKey, rm);
}
return rm;
}
/** {@collect.stats}
* Return the RepaintManager for the calling thread given a JComponent.
* <p>
* Note: This method exists for backward binary compatibility with earlier
* versions of the Swing library. It simply returns the result returned by
* {@link #currentManager(Component)}.
*
* @param c a JComponent -- unused
* @return the RepaintManager object
*/
public static RepaintManager currentManager(JComponent c) {
return currentManager((Component)c);
}
/** {@collect.stats}
* Set the RepaintManager that should be used for the calling
* thread. <b>aRepaintManager</b> will become the current RepaintManager
* for the calling thread's thread group.
* @param aRepaintManager the RepaintManager object to use
*/
public static void setCurrentManager(RepaintManager aRepaintManager) {
if (aRepaintManager != null) {
SwingUtilities.appContextPut(repaintManagerKey, aRepaintManager);
} else {
SwingUtilities.appContextRemove(repaintManagerKey);
}
}
/** {@collect.stats}
* Create a new RepaintManager instance. You rarely call this constructor.
* directly. To get the default RepaintManager, use
* RepaintManager.currentManager(JComponent) (normally "this").
*/
public RepaintManager() {
// Because we can't know what a subclass is doing with the
// volatile image we immediately punt in subclasses. If this
// poses a problem we'll need a more sophisticated detection algorithm,
// or API.
this(BUFFER_STRATEGY_SPECIFIED_OFF);
}
private RepaintManager(short bufferStrategyType) {
// If native doublebuffering is being used, do NOT use
// Swing doublebuffering.
doubleBufferingEnabled = !nativeDoubleBuffering;
synchronized(this) {
dirtyComponents = new IdentityHashMap<Component,Rectangle>();
tmpDirtyComponents = new IdentityHashMap<Component,Rectangle>();
this.bufferStrategyType = bufferStrategyType;
hwDirtyComponents = new IdentityHashMap<Container,Rectangle>();
}
processingRunnable = new ProcessingRunnable();
}
private void displayChanged() {
clearImages();
}
/** {@collect.stats}
* Mark the component as in need of layout and queue a runnable
* for the event dispatching thread that will validate the components
* first isValidateRoot() ancestor.
*
* @see JComponent#isValidateRoot
* @see #removeInvalidComponent
*/
public synchronized void addInvalidComponent(JComponent invalidComponent)
{
Component validateRoot = null;
/* Find the first JComponent ancestor of this component whose
* isValidateRoot() method returns true.
*/
for(Component c = invalidComponent; c != null; c = c.getParent()) {
if ((c instanceof CellRendererPane) || (c.getPeer() == null)) {
return;
}
if ((c instanceof JComponent) && (((JComponent)c).isValidateRoot())) {
validateRoot = c;
break;
}
}
/* There's no validateRoot to apply validate to, so we're done.
*/
if (validateRoot == null) {
return;
}
/* If the validateRoot and all of its ancestors aren't visible
* then we don't do anything. While we're walking up the tree
* we find the root Window or Applet.
*/
Component root = null;
for(Component c = validateRoot; c != null; c = c.getParent()) {
if (!c.isVisible() || (c.getPeer() == null)) {
return;
}
if ((c instanceof Window) || (c instanceof Applet)) {
root = c;
break;
}
}
if (root == null) {
return;
}
/* Lazily create the invalidateComponents vector and add the
* validateRoot if it's not there already. If this validateRoot
* is already in the vector, we're done.
*/
if (invalidComponents == null) {
invalidComponents = new ArrayList<Component>();
}
else {
int n = invalidComponents.size();
for(int i = 0; i < n; i++) {
if(validateRoot == invalidComponents.get(i)) {
return;
}
}
}
invalidComponents.add(validateRoot);
// Queue a Runnable to invoke paintDirtyRegions and
// validateInvalidComponents.
scheduleProcessingRunnable();
}
/** {@collect.stats}
* Remove a component from the list of invalid components.
*
* @see #addInvalidComponent
*/
public synchronized void removeInvalidComponent(JComponent component) {
if(invalidComponents != null) {
int index = invalidComponents.indexOf(component);
if(index != -1) {
invalidComponents.remove(index);
}
}
}
/** {@collect.stats}
* Add a component in the list of components that should be refreshed.
* If <i>c</i> already has a dirty region, the rectangle <i>(x,y,w,h)</i>
* will be unioned with the region that should be redrawn.
*
* @see JComponent#repaint
*/
private void addDirtyRegion0(Container c, int x, int y, int w, int h) {
/* Special cases we don't have to bother with.
*/
if ((w <= 0) || (h <= 0) || (c == null)) {
return;
}
if ((c.getWidth() <= 0) || (c.getHeight() <= 0)) {
return;
}
if (extendDirtyRegion(c, x, y, w, h)) {
// Component was already marked as dirty, region has been
// extended, no need to continue.
return;
}
/* Make sure that c and all it ancestors (up to an Applet or
* Window) are visible. This loop has the same effect as
* checking c.isShowing() (and note that it's still possible
* that c is completely obscured by an opaque ancestor in
* the specified rectangle).
*/
Component root = null;
// Note: We can't synchronize around this, Frame.getExtendedState
// is synchronized so that if we were to synchronize around this
// it could lead to the possibility of getting locks out
// of order and deadlocking.
for (Container p = c; p != null; p = p.getParent()) {
if (!p.isVisible() || (p.getPeer() == null)) {
return;
}
if ((p instanceof Window) || (p instanceof Applet)) {
// Iconified frames are still visible!
if (p instanceof Frame &&
(((Frame)p).getExtendedState() & Frame.ICONIFIED) ==
Frame.ICONIFIED) {
return;
}
root = p;
break;
}
}
if (root == null) return;
synchronized(this) {
if (extendDirtyRegion(c, x, y, w, h)) {
// In between last check and this check another thread
// queued up runnable, can bail here.
return;
}
dirtyComponents.put(c, new Rectangle(x, y, w, h));
}
// Queue a Runnable to invoke paintDirtyRegions and
// validateInvalidComponents.
scheduleProcessingRunnable();
}
/** {@collect.stats}
* Add a component in the list of components that should be refreshed.
* If <i>c</i> already has a dirty region, the rectangle <i>(x,y,w,h)</i>
* will be unioned with the region that should be redrawn.
*
* @param c Component to repaint, null results in nothing happening.
* @param x X coordinate of the region to repaint
* @param y Y coordinate of the region to repaint
* @param w Width of the region to repaint
* @param h Height of the region to repaint
* @see JComponent#repaint
*/
public void addDirtyRegion(JComponent c, int x, int y, int w, int h)
{
addDirtyRegion0(c, x, y, w, h);
}
/** {@collect.stats}
* Adds <code>window</code> to the list of <code>Component</code>s that
* need to be repainted.
*
* @param window Window to repaint, null results in nothing happening.
* @param x X coordinate of the region to repaint
* @param y Y coordinate of the region to repaint
* @param w Width of the region to repaint
* @param h Height of the region to repaint
* @see JFrame#repaint
* @see JWindow#repaint
* @see JDialog#repaint
* @since 1.6
*/
public void addDirtyRegion(Window window, int x, int y, int w, int h) {
addDirtyRegion0(window, x, y, w, h);
}
/** {@collect.stats}
* Adds <code>applet</code> to the list of <code>Component</code>s that
* need to be repainted.
*
* @param applet Applet to repaint, null results in nothing happening.
* @param x X coordinate of the region to repaint
* @param y Y coordinate of the region to repaint
* @param w Width of the region to repaint
* @param h Height of the region to repaint
* @see JApplet#repaint
* @since 1.6
*/
public void addDirtyRegion(Applet applet, int x, int y, int w, int h) {
addDirtyRegion0(applet, x, y, w, h);
}
void scheduleHeavyWeightPaints() {
Map<Container,Rectangle> hws;
synchronized(this) {
if (hwDirtyComponents.size() == 0) {
return;
}
hws = hwDirtyComponents;
hwDirtyComponents = new IdentityHashMap<Container,Rectangle>();
}
for (Container hw : hws.keySet()) {
Rectangle dirty = hws.get(hw);
if (hw instanceof Window) {
addDirtyRegion((Window)hw, dirty.x, dirty.y,
dirty.width, dirty.height);
}
else if (hw instanceof Applet) {
addDirtyRegion((Applet)hw, dirty.x, dirty.y,
dirty.width, dirty.height);
}
else { // SwingHeavyWeight
addDirtyRegion0(hw, dirty.x, dirty.y,
dirty.width, dirty.height);
}
}
}
//
// This is called from the toolkit thread when a native expose is
// received.
//
void nativeAddDirtyRegion(AppContext appContext, Container c,
int x, int y, int w, int h) {
if (w > 0 && h > 0) {
synchronized(this) {
Rectangle dirty = hwDirtyComponents.get(c);
if (dirty == null) {
hwDirtyComponents.put(c, new Rectangle(x, y, w, h));
}
else {
hwDirtyComponents.put(c, SwingUtilities.computeUnion(
x, y, w, h, dirty));
}
}
scheduleProcessingRunnable(appContext);
}
}
//
// This is called from the toolkit thread when awt needs to run a
// Runnable before we paint.
//
void nativeQueueSurfaceDataRunnable(AppContext appContext, Component c,
Runnable r) {
synchronized(this) {
if (runnableList == null) {
runnableList = new LinkedList<Runnable>();
}
runnableList.add(r);
}
scheduleProcessingRunnable(appContext);
}
/** {@collect.stats}
* Extends the dirty region for the specified component to include
* the new region.
*
* @return false if <code>c</code> is not yet marked dirty.
*/
private synchronized boolean extendDirtyRegion(
Component c, int x, int y, int w, int h) {
Rectangle r = (Rectangle)dirtyComponents.get(c);
if (r != null) {
// A non-null r implies c is already marked as dirty,
// and that the parent is valid. Therefore we can
// just union the rect and bail.
SwingUtilities.computeUnion(x, y, w, h, r);
return true;
}
return false;
}
/** {@collect.stats} Return the current dirty region for a component.
* Return an empty rectangle if the component is not
* dirty.
*/
public Rectangle getDirtyRegion(JComponent aComponent) {
Rectangle r = null;
synchronized(this) {
r = (Rectangle)dirtyComponents.get(aComponent);
}
if(r == null)
return new Rectangle(0,0,0,0);
else
return new Rectangle(r);
}
/** {@collect.stats}
* Mark a component completely dirty. <b>aComponent</b> will be
* completely painted during the next paintDirtyRegions() call.
*/
public void markCompletelyDirty(JComponent aComponent) {
addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE);
}
/** {@collect.stats}
* Mark a component completely clean. <b>aComponent</b> will not
* get painted during the next paintDirtyRegions() call.
*/
public void markCompletelyClean(JComponent aComponent) {
synchronized(this) {
dirtyComponents.remove(aComponent);
}
}
/** {@collect.stats}
* Convenience method that returns true if <b>aComponent</b> will be completely
* painted during the next paintDirtyRegions(). If computing dirty regions is
* expensive for your component, use this method and avoid computing dirty region
* if it return true.
*/
public boolean isCompletelyDirty(JComponent aComponent) {
Rectangle r;
r = getDirtyRegion(aComponent);
if(r.width == Integer.MAX_VALUE &&
r.height == Integer.MAX_VALUE)
return true;
else
return false;
}
/** {@collect.stats}
* Validate all of the components that have been marked invalid.
* @see #addInvalidComponent
*/
public void validateInvalidComponents() {
java.util.List<Component> ic;
synchronized(this) {
if(invalidComponents == null) {
return;
}
ic = invalidComponents;
invalidComponents = null;
}
int n = ic.size();
for(int i = 0; i < n; i++) {
ic.get(i).validate();
}
}
/** {@collect.stats}
* This is invoked to process paint requests. It's needed
* for backward compatability in so far as RepaintManager would previously
* not see paint requests for top levels, so, we have to make sure
* a subclass correctly paints any dirty top levels.
*/
private void prePaintDirtyRegions() {
Map<Component,Rectangle> dirtyComponents;
java.util.List<Runnable> runnableList;
synchronized(this) {
dirtyComponents = this.dirtyComponents;
runnableList = this.runnableList;
this.runnableList = null;
}
if (runnableList != null) {
for (Runnable runnable : runnableList) {
runnable.run();
}
}
paintDirtyRegions();
if (dirtyComponents.size() > 0) {
// This'll only happen if a subclass isn't correctly dealing
// with toplevels.
paintDirtyRegions(dirtyComponents);
}
}
/** {@collect.stats}
* Paint all of the components that have been marked dirty.
*
* @see #addDirtyRegion
*/
public void paintDirtyRegions() {
synchronized(this) { // swap for thread safety
Map<Component,Rectangle> tmp = tmpDirtyComponents;
tmpDirtyComponents = dirtyComponents;
dirtyComponents = tmp;
dirtyComponents.clear();
}
paintDirtyRegions(tmpDirtyComponents);
}
private void paintDirtyRegions(Map<Component,Rectangle>
tmpDirtyComponents){
int i, count;
java.util.List<Component> roots;
Component dirtyComponent;
count = tmpDirtyComponents.size();
if (count == 0) {
return;
}
Rectangle rect;
int localBoundsX = 0;
int localBoundsY = 0;
int localBoundsH = 0;
int localBoundsW = 0;
Enumeration keys;
roots = new ArrayList<Component>(count);
for (Component dirty : tmpDirtyComponents.keySet()) {
collectDirtyComponents(tmpDirtyComponents, dirty, roots);
}
count = roots.size();
// System.out.println("roots size is " + count);
painting = true;
try {
for(i=0 ; i < count ; i++) {
dirtyComponent = roots.get(i);
rect = tmpDirtyComponents.get(dirtyComponent);
// System.out.println("Should refresh :" + rect);
localBoundsH = dirtyComponent.getHeight();
localBoundsW = dirtyComponent.getWidth();
SwingUtilities.computeIntersection(localBoundsX,
localBoundsY,
localBoundsW,
localBoundsH,
rect);
if (dirtyComponent instanceof JComponent) {
((JComponent)dirtyComponent).paintImmediately(
rect.x,rect.y,rect.width, rect.height);
}
else if (dirtyComponent.isShowing()) {
Graphics g = JComponent.safelyGetGraphics(
dirtyComponent, dirtyComponent);
// If the Graphics goes away, it means someone disposed of
// the window, don't do anything.
if (g != null) {
g.setClip(rect.x, rect.y, rect.width, rect.height);
try {
dirtyComponent.paint(g);
} finally {
g.dispose();
}
}
}
// If the repaintRoot has been set, service it now and
// remove any components that are children of repaintRoot.
if (repaintRoot != null) {
adjustRoots(repaintRoot, roots, i + 1);
count = roots.size();
paintManager.isRepaintingRoot = true;
repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(),
repaintRoot.getHeight());
paintManager.isRepaintingRoot = false;
// Only service repaintRoot once.
repaintRoot = null;
}
}
} finally {
painting = false;
}
tmpDirtyComponents.clear();
}
/** {@collect.stats}
* Removes any components from roots that are children of
* root.
*/
private void adjustRoots(JComponent root,
java.util.List<Component> roots, int index) {
for (int i = roots.size() - 1; i >= index; i--) {
Component c = roots.get(i);
for(;;) {
if (c == root || c == null || !(c instanceof JComponent)) {
break;
}
c = c.getParent();
}
if (c == root) {
roots.remove(i);
}
}
}
Rectangle tmp = new Rectangle();
void collectDirtyComponents(Map<Component,Rectangle> dirtyComponents,
Component dirtyComponent,
java.util.List<Component> roots) {
int dx, dy, rootDx, rootDy;
Component component, rootDirtyComponent,parent;
Rectangle cBounds;
// Find the highest parent which is dirty. When we get out of this
// rootDx and rootDy will contain the translation from the
// rootDirtyComponent's coordinate system to the coordinates of the
// original dirty component. The tmp Rect is also used to compute the
// visible portion of the dirtyRect.
component = rootDirtyComponent = dirtyComponent;
int x = dirtyComponent.getX();
int y = dirtyComponent.getY();
int w = dirtyComponent.getWidth();
int h = dirtyComponent.getHeight();
dx = rootDx = 0;
dy = rootDy = 0;
tmp.setBounds((Rectangle) dirtyComponents.get(dirtyComponent));
// System.out.println("Collect dirty component for bound " + tmp +
// "component bounds is " + cBounds);;
SwingUtilities.computeIntersection(0,0,w,h,tmp);
if (tmp.isEmpty()) {
// System.out.println("Empty 1");
return;
}
for(;;) {
if(!(component instanceof JComponent))
break;
parent = component.getParent();
if(parent == null)
break;
component = parent;
dx += x;
dy += y;
tmp.setLocation(tmp.x + x, tmp.y + y);
x = component.getX();
y = component.getY();
w = component.getWidth();
h = component.getHeight();
tmp = SwingUtilities.computeIntersection(0,0,w,h,tmp);
if (tmp.isEmpty()) {
// System.out.println("Empty 2");
return;
}
if (dirtyComponents.get(component) != null) {
rootDirtyComponent = component;
rootDx = dx;
rootDy = dy;
}
}
if (dirtyComponent != rootDirtyComponent) {
Rectangle r;
tmp.setLocation(tmp.x + rootDx - dx,
tmp.y + rootDy - dy);
r = (Rectangle)dirtyComponents.get(rootDirtyComponent);
SwingUtilities.computeUnion(tmp.x,tmp.y,tmp.width,tmp.height,r);
}
// If we haven't seen this root before, then we need to add it to the
// list of root dirty Views.
if (!roots.contains(rootDirtyComponent))
roots.add(rootDirtyComponent);
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public synchronized String toString() {
StringBuffer sb = new StringBuffer();
if(dirtyComponents != null)
sb.append("" + dirtyComponents);
return sb.toString();
}
/** {@collect.stats}
* Return the offscreen buffer that should be used as a double buffer with
* the component <code>c</code>.
* By default there is a double buffer per RepaintManager.
* The buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>
* This happens when the maximum double buffer size as been set for the receiving
* repaint manager.
*/
public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) {
return _getOffscreenBuffer(c, proposedWidth, proposedHeight);
}
/** {@collect.stats}
* Return a volatile offscreen buffer that should be used as a
* double buffer with the specified component <code>c</code>.
* The image returned will be an instance of VolatileImage, or null
* if a VolatileImage object could not be instantiated.
* This buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>.
* This happens when the maximum double buffer size has been set for this
* repaint manager.
*
* @see java.awt.image.VolatileImage
* @since 1.4
*/
public Image getVolatileOffscreenBuffer(Component c,
int proposedWidth,int proposedHeight) {
GraphicsConfiguration config = c.getGraphicsConfiguration();
if (config == null) {
config = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
}
Dimension maxSize = getDoubleBufferMaximumSize();
int width = proposedWidth < 1 ? 1 :
(proposedWidth > maxSize.width? maxSize.width : proposedWidth);
int height = proposedHeight < 1 ? 1 :
(proposedHeight > maxSize.height? maxSize.height : proposedHeight);
VolatileImage image = volatileMap.get(config);
if (image == null || image.getWidth() < width ||
image.getHeight() < height) {
if (image != null) {
image.flush();
}
image = config.createCompatibleVolatileImage(width, height);
volatileMap.put(config, image);
}
return image;
}
private Image _getOffscreenBuffer(Component c, int proposedWidth, int proposedHeight) {
Dimension maxSize = getDoubleBufferMaximumSize();
DoubleBufferInfo doubleBuffer = null;
int width, height;
if (standardDoubleBuffer == null) {
standardDoubleBuffer = new DoubleBufferInfo();
}
doubleBuffer = standardDoubleBuffer;
width = proposedWidth < 1? 1 :
(proposedWidth > maxSize.width? maxSize.width : proposedWidth);
height = proposedHeight < 1? 1 :
(proposedHeight > maxSize.height? maxSize.height : proposedHeight);
if (doubleBuffer.needsReset || (doubleBuffer.image != null &&
(doubleBuffer.size.width < width ||
doubleBuffer.size.height < height))) {
doubleBuffer.needsReset = false;
if (doubleBuffer.image != null) {
doubleBuffer.image.flush();
doubleBuffer.image = null;
}
width = Math.max(doubleBuffer.size.width, width);
height = Math.max(doubleBuffer.size.height, height);
}
Image result = doubleBuffer.image;
if (doubleBuffer.image == null) {
result = c.createImage(width , height);
doubleBuffer.size = new Dimension(width, height);
if (c instanceof JComponent) {
((JComponent)c).setCreatedDoubleBuffer(true);
doubleBuffer.image = result;
}
// JComponent will inform us when it is no longer valid
// (via removeNotify) we have no such hook to other components,
// therefore we don't keep a ref to the Component
// (indirectly through the Image) by stashing the image.
}
return result;
}
/** {@collect.stats} Set the maximum double buffer size. **/
public void setDoubleBufferMaximumSize(Dimension d) {
doubleBufferMaxSize = d;
if (doubleBufferMaxSize == null) {
clearImages();
} else {
clearImages(d.width, d.height);
}
}
private void clearImages() {
clearImages(0, 0);
}
private void clearImages(int width, int height) {
if (standardDoubleBuffer != null && standardDoubleBuffer.image != null) {
if (standardDoubleBuffer.image.getWidth(null) > width ||
standardDoubleBuffer.image.getHeight(null) > height) {
standardDoubleBuffer.image.flush();
standardDoubleBuffer.image = null;
}
}
// Clear out the VolatileImages
Iterator gcs = volatileMap.keySet().iterator();
while (gcs.hasNext()) {
GraphicsConfiguration gc = (GraphicsConfiguration)gcs.next();
VolatileImage image = (VolatileImage)volatileMap.get(gc);
if (image.getWidth() > width || image.getHeight() > height) {
image.flush();
gcs.remove();
}
}
}
/** {@collect.stats}
* Returns the maximum double buffer size.
*
* @return a Dimension object representing the maximum size
*/
public Dimension getDoubleBufferMaximumSize() {
if (doubleBufferMaxSize == null) {
try {
Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
for (GraphicsDevice gd : ge.getScreenDevices()) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
virtualBounds = virtualBounds.union(gc.getBounds());
}
doubleBufferMaxSize = new Dimension(virtualBounds.width,
virtualBounds.height);
} catch (HeadlessException e) {
doubleBufferMaxSize = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
}
return doubleBufferMaxSize;
}
/** {@collect.stats}
* Enables or disables double buffering in this RepaintManager.
* CAUTION: The default value for this property is set for optimal
* paint performance on the given platform and it is not recommended
* that programs modify this property directly.
*
* @param aFlag true to activate double buffering
* @see #isDoubleBufferingEnabled
*/
public void setDoubleBufferingEnabled(boolean aFlag) {
doubleBufferingEnabled = aFlag;
PaintManager paintManager = getPaintManager();
if (!aFlag && paintManager.getClass() != PaintManager.class) {
setPaintManager(new PaintManager());
}
}
/** {@collect.stats}
* Returns true if this RepaintManager is double buffered.
* The default value for this property may vary from platform
* to platform. On platforms where native double buffering
* is supported in the AWT, the default value will be <code>false</code>
* to avoid unnecessary buffering in Swing.
* On platforms where native double buffering is not supported,
* the default value will be <code>true</code>.
*
* @return true if this object is double buffered
*/
public boolean isDoubleBufferingEnabled() {
return doubleBufferingEnabled;
}
/** {@collect.stats}
* This resets the double buffer. Actually, it marks the double buffer
* as invalid, the double buffer will then be recreated on the next
* invocation of getOffscreenBuffer.
*/
void resetDoubleBuffer() {
if (standardDoubleBuffer != null) {
standardDoubleBuffer.needsReset = true;
}
}
/** {@collect.stats}
* This resets the volatile double buffer.
*/
void resetVolatileDoubleBuffer(GraphicsConfiguration gc) {
Image image = volatileMap.remove(gc);
if (image != null) {
image.flush();
}
}
/** {@collect.stats}
* Returns true if we should use the <code>Image</code> returned
* from <code>getVolatileOffscreenBuffer</code> to do double buffering.
*/
boolean useVolatileDoubleBuffer() {
return volatileImageBufferEnabled;
}
/** {@collect.stats}
* Returns true if the current thread is the thread painting. This
* will return false if no threads are painting.
*/
private synchronized boolean isPaintingThread() {
return (Thread.currentThread() == paintThread);
}
//
// Paint methods. You very, VERY rarely need to invoke these.
// They are invoked directly from JComponent's painting code and
// when painting happens outside the normal flow: DefaultDesktopManager
// and JViewport. If you end up needing these methods in other places be
// careful that you don't get stuck in a paint loop.
//
/** {@collect.stats}
* Paints a region of a component
*
* @param paintingComponent Component to paint
* @param bufferComponent Component to obtain buffer for
* @param g Graphics to paint to
* @param x X-coordinate
* @param y Y-coordinate
* @param w Width
* @param h Height
*/
void paint(JComponent paintingComponent,
JComponent bufferComponent, Graphics g,
int x, int y, int w, int h) {
PaintManager paintManager = getPaintManager();
if (!isPaintingThread()) {
// We're painting to two threads at once. PaintManager deals
// with this a bit better than BufferStrategyPaintManager, use
// it to avoid possible exceptions/corruption.
if (paintManager.getClass() != PaintManager.class) {
paintManager = new PaintManager();
paintManager.repaintManager = this;
}
}
if (!paintManager.paint(paintingComponent, bufferComponent, g,
x, y, w, h)) {
g.setClip(x, y, w, h);
paintingComponent.paintToOffscreen(g, x, y, w, h, x + w, y + h);
}
}
/** {@collect.stats}
* Does a copy area on the specified region.
*
* @param clip Whether or not the copyArea needs to be clipped to the
* Component's bounds.
*/
void copyArea(JComponent c, Graphics g, int x, int y, int w, int h,
int deltaX, int deltaY, boolean clip) {
getPaintManager().copyArea(c, g, x, y, w, h, deltaX, deltaY, clip);
}
/** {@collect.stats}
* Invoked prior to any paint/copyArea method calls. This will
* be followed by an invocation of <code>endPaint</code>.
* <b>WARNING</b>: Callers of this method need to wrap the call
* in a <code>try/finally</code>, otherwise if an exception is thrown
* during the course of painting the RepaintManager may
* be left in a state in which the screen is not updated, eg:
* <pre>
* repaintManager.beginPaint();
* try {
* repaintManager.paint(...);
* } finally {
* repaintManager.endPaint();
* }
* </pre>
*/
void beginPaint() {
boolean multiThreadedPaint = false;
int paintDepth = 0;
Thread currentThread = Thread.currentThread();
synchronized(this) {
paintDepth = this.paintDepth;
if (paintThread == null || currentThread == paintThread) {
paintThread = currentThread;
this.paintDepth++;
} else {
multiThreadedPaint = true;
}
}
if (!multiThreadedPaint && paintDepth == 0) {
getPaintManager().beginPaint();
}
}
/** {@collect.stats}
* Invoked after <code>beginPaint</code> has been invoked.
*/
void endPaint() {
if (isPaintingThread()) {
PaintManager paintManager = null;
synchronized(this) {
if (--paintDepth == 0) {
paintManager = getPaintManager();
}
}
if (paintManager != null) {
paintManager.endPaint();
synchronized(this) {
paintThread = null;
}
}
}
}
/** {@collect.stats}
* If possible this will show a previously rendered portion of
* a Component. If successful, this will return true, otherwise false.
* <p>
* WARNING: This method is invoked from the native toolkit thread, be
* very careful as to what methods this invokes!
*/
boolean show(Container c, int x, int y, int w, int h) {
return getPaintManager().show(c, x, y, w, h);
}
/** {@collect.stats}
* Invoked when the doubleBuffered or useTrueDoubleBuffering
* properties of a JRootPane change. This may come in on any thread.
*/
void doubleBufferingChanged(JRootPane rootPane) {
getPaintManager().doubleBufferingChanged(rootPane);
}
/** {@collect.stats}
* Sets the <code>PaintManager</code> that is used to handle all
* double buffered painting.
*
* @param paintManager The PaintManager to use. Passing in null indicates
* the fallback PaintManager should be used.
*/
void setPaintManager(PaintManager paintManager) {
if (paintManager == null) {
paintManager = new PaintManager();
}
PaintManager oldPaintManager;
synchronized(this) {
oldPaintManager = this.paintManager;
this.paintManager = paintManager;
paintManager.repaintManager = this;
}
if (oldPaintManager != null) {
oldPaintManager.dispose();
}
}
private synchronized PaintManager getPaintManager() {
if (paintManager == null) {
PaintManager paintManager = null;
if (doubleBufferingEnabled && !nativeDoubleBuffering) {
switch (bufferStrategyType) {
case BUFFER_STRATEGY_NOT_SPECIFIED:
if (((SunToolkit)Toolkit.getDefaultToolkit()).
useBufferPerWindow()) {
paintManager = new BufferStrategyPaintManager();
}
break;
case BUFFER_STRATEGY_SPECIFIED_ON:
paintManager = new BufferStrategyPaintManager();
break;
default:
break;
}
}
// null case handled in setPaintManager
setPaintManager(paintManager);
}
return paintManager;
}
private void scheduleProcessingRunnable() {
scheduleProcessingRunnable(AppContext.getAppContext());
}
private void scheduleProcessingRunnable(AppContext context) {
if (processingRunnable.markPending()) {
SunToolkit.getSystemEventQueueImplPP(context).
postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(),
processingRunnable));
}
}
/** {@collect.stats}
* PaintManager is used to handle all double buffered painting for
* Swing. Subclasses should call back into the JComponent method
* <code>paintToOffscreen</code> to handle the actual painting.
*/
static class PaintManager {
/** {@collect.stats}
* RepaintManager the PaintManager has been installed on.
*/
protected RepaintManager repaintManager;
boolean isRepaintingRoot;
/** {@collect.stats}
* Paints a region of a component
*
* @param paintingComponent Component to paint
* @param bufferComponent Component to obtain buffer for
* @param g Graphics to paint to
* @param x X-coordinate
* @param y Y-coordinate
* @param w Width
* @param h Height
* @return true if painting was successful.
*/
public boolean paint(JComponent paintingComponent,
JComponent bufferComponent, Graphics g,
int x, int y, int w, int h) {
// First attempt to use VolatileImage buffer for performance.
// If this fails (which should rarely occur), fallback to a
// standard Image buffer.
boolean paintCompleted = false;
Image offscreen;
if (repaintManager.useVolatileDoubleBuffer() &&
(offscreen = getValidImage(repaintManager.
getVolatileOffscreenBuffer(bufferComponent, w, h))) != null) {
VolatileImage vImage = (java.awt.image.VolatileImage)offscreen;
GraphicsConfiguration gc = bufferComponent.
getGraphicsConfiguration();
for (int i = 0; !paintCompleted &&
i < RepaintManager.VOLATILE_LOOP_MAX; i++) {
if (vImage.validate(gc) ==
VolatileImage.IMAGE_INCOMPATIBLE) {
repaintManager.resetVolatileDoubleBuffer(gc);
offscreen = repaintManager.getVolatileOffscreenBuffer(
bufferComponent,w, h);
vImage = (java.awt.image.VolatileImage)offscreen;
}
paintDoubleBuffered(paintingComponent, vImage, g, x, y,
w, h);
paintCompleted = !vImage.contentsLost();
}
}
// VolatileImage painting loop failed, fallback to regular
// offscreen buffer
if (!paintCompleted && (offscreen = getValidImage(
repaintManager.getOffscreenBuffer(
bufferComponent, w, h))) != null) {
paintDoubleBuffered(paintingComponent, offscreen, g, x, y, w,
h);
paintCompleted = true;
}
return paintCompleted;
}
/** {@collect.stats}
* Does a copy area on the specified region.
*/
public void copyArea(JComponent c, Graphics g, int x, int y, int w,
int h, int deltaX, int deltaY, boolean clip) {
g.copyArea(x, y, w, h, deltaX, deltaY);
}
/** {@collect.stats}
* Invoked prior to any calls to paint or copyArea.
*/
public void beginPaint() {
}
/** {@collect.stats}
* Invoked to indicate painting has been completed.
*/
public void endPaint() {
}
/** {@collect.stats}
* Shows a region of a previously rendered component. This
* will return true if successful, false otherwise. The default
* implementation returns false.
*/
public boolean show(Container c, int x, int y, int w, int h) {
return false;
}
/** {@collect.stats}
* Invoked when the doubleBuffered or useTrueDoubleBuffering
* properties of a JRootPane change. This may come in on any thread.
*/
public void doubleBufferingChanged(JRootPane rootPane) {
}
/** {@collect.stats}
* Paints a portion of a component to an offscreen buffer.
*/
protected void paintDoubleBuffered(JComponent c, Image image,
Graphics g, int clipX, int clipY,
int clipW, int clipH) {
Graphics osg = image.getGraphics();
int bw = Math.min(clipW, image.getWidth(null));
int bh = Math.min(clipH, image.getHeight(null));
int x,y,maxx,maxy;
try {
for(x = clipX, maxx = clipX+clipW; x < maxx ; x += bw ) {
for(y=clipY, maxy = clipY + clipH; y < maxy ; y += bh) {
osg.translate(-x, -y);
osg.setClip(x,y,bw,bh);
c.paintToOffscreen(osg, x, y, bw, bh, maxx, maxy);
g.setClip(x, y, bw, bh);
g.drawImage(image, x, y, c);
osg.translate(x, y);
}
}
} finally {
osg.dispose();
}
}
/** {@collect.stats}
* If <code>image</code> is non-null with a positive size it
* is returned, otherwise null is returned.
*/
private Image getValidImage(Image image) {
if (image != null && image.getWidth(null) > 0 &&
image.getHeight(null) > 0) {
return image;
}
return null;
}
/** {@collect.stats}
* Schedules a repaint for the specified component. This differs
* from <code>root.repaint</code> in that if the RepaintManager is
* currently processing paint requests it'll process this request
* with the current set of requests.
*/
protected void repaintRoot(JComponent root) {
assert (repaintManager.repaintRoot == null);
if (repaintManager.painting) {
repaintManager.repaintRoot = root;
}
else {
root.repaint();
}
}
/** {@collect.stats}
* Returns true if the component being painted is the root component
* that was previously passed to <code>repaintRoot</code>.
*/
protected boolean isRepaintingRoot() {
return isRepaintingRoot;
}
/** {@collect.stats}
* Cleans up any state. After invoked the PaintManager will no
* longer be used anymore.
*/
protected void dispose() {
}
}
private class DoubleBufferInfo {
public Image image;
public Dimension size;
public boolean needsReset = false;
}
/** {@collect.stats}
* Listener installed to detect display changes. When display changes,
* schedules a callback to notify all RepaintManagers of the display
* changes. Only one DisplayChangedHandler is ever installed. The
* singleton instance will schedule notification for all AppContexts.
*/
private static final class DisplayChangedHandler implements
DisplayChangedListener {
public void displayChanged() {
scheduleDisplayChanges();
}
public void paletteChanged() {
}
private void scheduleDisplayChanges() {
// To avoid threading problems, we notify each RepaintManager
// on the thread it was created on.
for (Object c : AppContext.getAppContexts()) {
AppContext context = (AppContext) c;
synchronized(context) {
if (!context.isDisposed()) {
EventQueue eventQueue = (EventQueue)context.get(
AppContext.EVENT_QUEUE_KEY);
if (eventQueue != null) {
eventQueue.postEvent(new InvocationEvent(
Toolkit.getDefaultToolkit(),
new DisplayChangedRunnable()));
}
}
}
}
}
}
private static final class DisplayChangedRunnable implements Runnable {
public void run() {
RepaintManager.currentManager((JComponent)null).displayChanged();
}
}
/** {@collect.stats}
* Runnable used to process all repaint/revalidate requests.
*/
private final class ProcessingRunnable implements Runnable {
// If true, we're wainting on the EventQueue.
private boolean pending;
/** {@collect.stats}
* Marks this processing runnable as pending. If this was not
* already marked as pending, true is returned.
*/
public synchronized boolean markPending() {
if (!pending) {
pending = true;
return true;
}
return false;
}
public void run() {
synchronized (this) {
pending = false;
}
// First pass, flush any heavy paint events into real paint
// events. If there are pending heavy weight requests this will
// result in q'ing this request up one more time. As
// long as no other requests come in between now and the time
// the second one is processed nothing will happen. This is not
// ideal, but the logic needed to suppress the second request is
// more headache than it's worth.
scheduleHeavyWeightPaints();
// Do the actual validation and painting.
validateInvalidComponents();
prePaintDirtyRegions();
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Window;
/** {@collect.stats}
* Comparator which attempts to sort Components based on their size and
* position. Code adapted from original javax.swing.DefaultFocusManager
* implementation.
*
* @author David Mendenhall
*/
final class LayoutComparator implements Comparator, java.io.Serializable {
private static final int ROW_TOLERANCE = 10;
private boolean horizontal = true;
private boolean leftToRight = true;
void setComponentOrientation(ComponentOrientation orientation) {
horizontal = orientation.isHorizontal();
leftToRight = orientation.isLeftToRight();
}
public int compare(Object o1, Object o2) {
Component a = (Component)o1;
Component b = (Component)o2;
if (a == b) {
return 0;
}
// Row/Column algorithm only applies to siblings. If 'a' and 'b'
// aren't siblings, then we need to find their most inferior
// ancestors which share a parent. Compute the ancestory lists for
// each Component and then search from the Window down until the
// hierarchy branches.
if (a.getParent() != b.getParent()) {
LinkedList aAncestory, bAncestory;
for(aAncestory = new LinkedList(); a != null; a = a.getParent()) {
aAncestory.add(a);
if (a instanceof Window) {
break;
}
}
if (a == null) {
// 'a' is not part of a Window hierarchy. Can't cope.
throw new ClassCastException();
}
for(bAncestory = new LinkedList(); b != null; b = b.getParent()) {
bAncestory.add(b);
if (b instanceof Window) {
break;
}
}
if (b == null) {
// 'b' is not part of a Window hierarchy. Can't cope.
throw new ClassCastException();
}
for (ListIterator
aIter = aAncestory.listIterator(aAncestory.size()),
bIter = bAncestory.listIterator(bAncestory.size()); ;) {
if (aIter.hasPrevious()) {
a = (Component)aIter.previous();
} else {
// a is an ancestor of b
return -1;
}
if (bIter.hasPrevious()) {
b = (Component)bIter.previous();
} else {
// b is an ancestor of a
return 1;
}
if (a != b) {
break;
}
}
}
int ax = a.getX(), ay = a.getY(), bx = b.getX(), by = b.getY();
int zOrder = a.getParent().getComponentZOrder(a) - b.getParent().getComponentZOrder(b);
if (horizontal) {
if (leftToRight) {
// LT - Western Europe (optional for Japanese, Chinese, Korean)
if (Math.abs(ay - by) < ROW_TOLERANCE) {
return (ax < bx) ? -1 : ((ax > bx) ? 1 : zOrder);
} else {
return (ay < by) ? -1 : 1;
}
} else { // !leftToRight
// RT - Middle East (Arabic, Hebrew)
if (Math.abs(ay - by) < ROW_TOLERANCE) {
return (ax > bx) ? -1 : ((ax < bx) ? 1 : zOrder);
} else {
return (ay < by) ? -1 : 1;
}
}
} else { // !horizontal
if (leftToRight) {
// TL - Mongolian
if (Math.abs(ax - bx) < ROW_TOLERANCE) {
return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder);
} else {
return (ax < bx) ? -1 : 1;
}
} else { // !leftToRight
// TR - Japanese, Chinese, Korean
if (Math.abs(ax - bx) < ROW_TOLERANCE) {
return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder);
} else {
return (ax > bx) ? -1 : 1;
}
}
}
}
}
|
Java
|
/*
* Copyright (c) 2001, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.Set;
/** {@collect.stats}
* Provides a javax.swing.DefaultFocusManager view onto an arbitrary
* java.awt.KeyboardFocusManager. We subclass DefaultFocusManager instead of
* FocusManager because it seems more backward-compatible. It is likely that
* some pre-1.4 code assumes that the object returned by
* FocusManager.getCurrentManager is an instance of DefaultFocusManager unless
* set explicitly.
*/
final class DelegatingDefaultFocusManager extends DefaultFocusManager {
private final KeyboardFocusManager delegate;
DelegatingDefaultFocusManager(KeyboardFocusManager delegate) {
this.delegate = delegate;
setDefaultFocusTraversalPolicy(gluePolicy);
}
KeyboardFocusManager getDelegate() {
return delegate;
}
// Legacy methods which first appeared in javax.swing.FocusManager.
// Client code is most likely to invoke these methods.
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
delegate.processKeyEvent(focusedComponent, e);
}
public void focusNextComponent(Component aComponent) {
delegate.focusNextComponent(aComponent);
}
public void focusPreviousComponent(Component aComponent) {
delegate.focusPreviousComponent(aComponent);
}
// Make sure that we delegate all new methods in KeyboardFocusManager
// as well as the legacy methods from Swing. It is theoretically possible,
// although unlikely, that a client app will treat this instance as a
// new-style KeyboardFocusManager. We might as well be safe.
//
// The JLS won't let us override the protected methods in
// KeyboardFocusManager such that they invoke the corresponding methods on
// the delegate. However, since client code would never be able to call
// those methods anyways, we don't have to worry about that problem.
public Component getFocusOwner() {
return delegate.getFocusOwner();
}
public void clearGlobalFocusOwner() {
delegate.clearGlobalFocusOwner();
}
public Component getPermanentFocusOwner() {
return delegate.getPermanentFocusOwner();
}
public Window getFocusedWindow() {
return delegate.getFocusedWindow();
}
public Window getActiveWindow() {
return delegate.getActiveWindow();
}
public FocusTraversalPolicy getDefaultFocusTraversalPolicy() {
return delegate.getDefaultFocusTraversalPolicy();
}
public void setDefaultFocusTraversalPolicy(FocusTraversalPolicy
defaultPolicy) {
if (delegate != null) {
// Will be null when invoked from supers constructor.
delegate.setDefaultFocusTraversalPolicy(defaultPolicy);
}
}
public void
setDefaultFocusTraversalKeys(int id,
Set<? extends AWTKeyStroke> keystrokes)
{
delegate.setDefaultFocusTraversalKeys(id, keystrokes);
}
public Set<AWTKeyStroke> getDefaultFocusTraversalKeys(int id) {
return delegate.getDefaultFocusTraversalKeys(id);
}
public Container getCurrentFocusCycleRoot() {
return delegate.getCurrentFocusCycleRoot();
}
public void setGlobalCurrentFocusCycleRoot(Container newFocusCycleRoot) {
delegate.setGlobalCurrentFocusCycleRoot(newFocusCycleRoot);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
delegate.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
delegate.removePropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
delegate.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
delegate.removePropertyChangeListener(propertyName, listener);
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
delegate.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener listener) {
delegate.removeVetoableChangeListener(listener);
}
public void addVetoableChangeListener(String propertyName,
VetoableChangeListener listener) {
delegate.addVetoableChangeListener(propertyName, listener);
}
public void removeVetoableChangeListener(String propertyName,
VetoableChangeListener listener) {
delegate.removeVetoableChangeListener(propertyName, listener);
}
public void addKeyEventDispatcher(KeyEventDispatcher dispatcher) {
delegate.addKeyEventDispatcher(dispatcher);
}
public void removeKeyEventDispatcher(KeyEventDispatcher dispatcher) {
delegate.removeKeyEventDispatcher(dispatcher);
}
public boolean dispatchEvent(AWTEvent e) {
return delegate.dispatchEvent(e);
}
public boolean dispatchKeyEvent(KeyEvent e) {
return delegate.dispatchKeyEvent(e);
}
public void upFocusCycle(Component aComponent) {
delegate.upFocusCycle(aComponent);
}
public void downFocusCycle(Container aContainer) {
delegate.downFocusCycle(aContainer);
}
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.io.*;
import java.awt.Component;
/** {@collect.stats}
* Monitors the progress of reading from some InputStream. This ProgressMonitor
* is normally invoked in roughly this form:
* <pre>
* InputStream in = new BufferedInputStream(
* new ProgressMonitorInputStream(
* parentComponent,
* "Reading " + fileName,
* new FileInputStream(fileName)));
* </pre><p>
* This creates a progress monitor to monitor the progress of reading
* the input stream. If it's taking a while, a ProgressDialog will
* be popped up to inform the user. If the user hits the Cancel button
* an InterruptedIOException will be thrown on the next read.
* All the right cleanup is done when the stream is closed.
*
*
* <p>
*
* For further documentation and examples see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html">How to Monitor Progress</a>,
* a section in <em>The Java Tutorial.</em>
*
* @see ProgressMonitor
* @see JOptionPane
* @author James Gosling
*/
public class ProgressMonitorInputStream extends FilterInputStream
{
private ProgressMonitor monitor;
private int nread = 0;
private int size = 0;
/** {@collect.stats}
* Constructs an object to monitor the progress of an input stream.
*
* @param message Descriptive text to be placed in the dialog box
* if one is popped up.
* @param parentComponent The component triggering the operation
* being monitored.
* @param in The input stream to be monitored.
*/
public ProgressMonitorInputStream(Component parentComponent,
Object message,
InputStream in) {
super(in);
try {
size = in.available();
}
catch(IOException ioe) {
size = 0;
}
monitor = new ProgressMonitor(parentComponent, message, null, 0, size);
}
/** {@collect.stats}
* Get the ProgressMonitor object being used by this stream. Normally
* this isn't needed unless you want to do something like change the
* descriptive text partway through reading the file.
* @return the ProgressMonitor object used by this object
*/
public ProgressMonitor getProgressMonitor() {
return monitor;
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.read</code>
* to update the progress monitor after the read.
*/
public int read() throws IOException {
int c = in.read();
if (c >= 0) monitor.setProgress(++nread);
if (monitor.isCanceled()) {
InterruptedIOException exc =
new InterruptedIOException("progress");
exc.bytesTransferred = nread;
throw exc;
}
return c;
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.read</code>
* to update the progress monitor after the read.
*/
public int read(byte b[]) throws IOException {
int nr = in.read(b);
if (nr > 0) monitor.setProgress(nread += nr);
if (monitor.isCanceled()) {
InterruptedIOException exc =
new InterruptedIOException("progress");
exc.bytesTransferred = nread;
throw exc;
}
return nr;
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.read</code>
* to update the progress monitor after the read.
*/
public int read(byte b[],
int off,
int len) throws IOException {
int nr = in.read(b, off, len);
if (nr > 0) monitor.setProgress(nread += nr);
if (monitor.isCanceled()) {
InterruptedIOException exc =
new InterruptedIOException("progress");
exc.bytesTransferred = nread;
throw exc;
}
return nr;
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.skip</code>
* to update the progress monitor after the skip.
*/
public long skip(long n) throws IOException {
long nr = in.skip(n);
if (nr > 0) monitor.setProgress(nread += nr);
return nr;
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.close</code>
* to close the progress monitor as well as the stream.
*/
public void close() throws IOException {
in.close();
monitor.close();
}
/** {@collect.stats}
* Overrides <code>FilterInputStream.reset</code>
* to reset the progress monitor as well as the stream.
*/
public synchronized void reset() throws IOException {
in.reset();
nread = size - in.available();
monitor.setProgress(nread);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Set;
/** {@collect.stats}
* <code>ActionMap</code> provides mappings from
* <code>Object</code>s
* (called <em>keys</em> or <em><code>Action</code> names</em>)
* to <code>Action</code>s.
* An <code>ActionMap</code> is usually used with an <code>InputMap</code>
* to locate a particular action
* when a key is pressed. As with <code>InputMap</code>,
* an <code>ActionMap</code> can have a parent
* that is searched for keys not defined in the <code>ActionMap</code>.
* <p>As with <code>InputMap</code> if you create a cycle, eg:
* <pre>
* ActionMap am = new ActionMap();
* ActionMap bm = new ActionMap():
* am.setParent(bm);
* bm.setParent(am);
* </pre>
* some of the methods will cause a StackOverflowError to be thrown.
*
* @see InputMap
*
* @author Scott Violet
* @since 1.3
*/
public class ActionMap implements Serializable {
/** {@collect.stats} Handles the mapping between Action name and Action. */
private transient ArrayTable arrayTable;
/** {@collect.stats} Parent that handles any bindings we don't contain. */
private ActionMap parent;
/** {@collect.stats}
* Creates an <code>ActionMap</code> with no parent and no mappings.
*/
public ActionMap() {
}
/** {@collect.stats}
* Sets this <code>ActionMap</code>'s parent.
*
* @param map the <code>ActionMap</code> that is the parent of this one
*/
public void setParent(ActionMap map) {
this.parent = map;
}
/** {@collect.stats}
* Returns this <code>ActionMap</code>'s parent.
*
* @return the <code>ActionMap</code> that is the parent of this one,
* or null if this <code>ActionMap</code> has no parent
*/
public ActionMap getParent() {
return parent;
}
/** {@collect.stats}
* Adds a binding for <code>key</code> to <code>action</code>.
* If <code>action</code> is null, this removes the current binding
* for <code>key</code>.
* <p>In most instances, <code>key</code> will be
* <code>action.getValue(NAME)</code>.
*/
public void put(Object key, Action action) {
if (key == null) {
return;
}
if (action == null) {
remove(key);
}
else {
if (arrayTable == null) {
arrayTable = new ArrayTable();
}
arrayTable.put(key, action);
}
}
/** {@collect.stats}
* Returns the binding for <code>key</code>, messaging the
* parent <code>ActionMap</code> if the binding is not locally defined.
*/
public Action get(Object key) {
Action value = (arrayTable == null) ? null :
(Action)arrayTable.get(key);
if (value == null) {
ActionMap parent = getParent();
if (parent != null) {
return parent.get(key);
}
}
return value;
}
/** {@collect.stats}
* Removes the binding for <code>key</code> from this <code>ActionMap</code>.
*/
public void remove(Object key) {
if (arrayTable != null) {
arrayTable.remove(key);
}
}
/** {@collect.stats}
* Removes all the mappings from this <code>ActionMap</code>.
*/
public void clear() {
if (arrayTable != null) {
arrayTable.clear();
}
}
/** {@collect.stats}
* Returns the <code>Action</code> names that are bound in this <code>ActionMap</code>.
*/
public Object[] keys() {
if (arrayTable == null) {
return null;
}
return arrayTable.getKeys(null);
}
/** {@collect.stats}
* Returns the number of bindings in this {@code ActionMap}.
*
* @return the number of bindings in this {@code ActionMap}
*/
public int size() {
if (arrayTable == null) {
return 0;
}
return arrayTable.size();
}
/** {@collect.stats}
* Returns an array of the keys defined in this <code>ActionMap</code> and
* its parent. This method differs from <code>keys()</code> in that
* this method includes the keys defined in the parent.
*/
public Object[] allKeys() {
int count = size();
ActionMap parent = getParent();
if (count == 0) {
if (parent != null) {
return parent.allKeys();
}
return keys();
}
if (parent == null) {
return keys();
}
Object[] keys = keys();
Object[] pKeys = parent.allKeys();
if (pKeys == null) {
return keys;
}
if (keys == null) {
// Should only happen if size() != keys.length, which should only
// happen if mutated from multiple threads (or a bogus subclass).
return pKeys;
}
HashMap keyMap = new HashMap();
int counter;
for (counter = keys.length - 1; counter >= 0; counter--) {
keyMap.put(keys[counter], keys[counter]);
}
for (counter = pKeys.length - 1; counter >= 0; counter--) {
keyMap.put(pKeys[counter], pKeys[counter]);
}
return keyMap.keySet().toArray();
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
ArrayTable.writeArrayTable(s, arrayTable);
}
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
IOException {
s.defaultReadObject();
for (int counter = s.readInt() - 1; counter >= 0; counter--) {
put(s.readObject(), (Action)s.readObject());
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* A collection of constants generally used for positioning and orienting
* components on the screen.
*
* @author Jeff Dinkins
* @author Ralph Kar (orientation support)
*/
public interface SwingConstants {
/** {@collect.stats}
* The central position in an area. Used for
* both compass-direction constants (NORTH, etc.)
* and box-orientation constants (TOP, etc.).
*/
public static final int CENTER = 0;
//
// Box-orientation constant used to specify locations in a box.
//
/** {@collect.stats}
* Box-orientation constant used to specify the top of a box.
*/
public static final int TOP = 1;
/** {@collect.stats}
* Box-orientation constant used to specify the left side of a box.
*/
public static final int LEFT = 2;
/** {@collect.stats}
* Box-orientation constant used to specify the bottom of a box.
*/
public static final int BOTTOM = 3;
/** {@collect.stats}
* Box-orientation constant used to specify the right side of a box.
*/
public static final int RIGHT = 4;
//
// Compass-direction constants used to specify a position.
//
/** {@collect.stats}
* Compass-direction North (up).
*/
public static final int NORTH = 1;
/** {@collect.stats}
* Compass-direction north-east (upper right).
*/
public static final int NORTH_EAST = 2;
/** {@collect.stats}
* Compass-direction east (right).
*/
public static final int EAST = 3;
/** {@collect.stats}
* Compass-direction south-east (lower right).
*/
public static final int SOUTH_EAST = 4;
/** {@collect.stats}
* Compass-direction south (down).
*/
public static final int SOUTH = 5;
/** {@collect.stats}
* Compass-direction south-west (lower left).
*/
public static final int SOUTH_WEST = 6;
/** {@collect.stats}
* Compass-direction west (left).
*/
public static final int WEST = 7;
/** {@collect.stats}
* Compass-direction north west (upper left).
*/
public static final int NORTH_WEST = 8;
//
// These constants specify a horizontal or
// vertical orientation. For example, they are
// used by scrollbars and sliders.
//
/** {@collect.stats} Horizontal orientation. Used for scrollbars and sliders. */
public static final int HORIZONTAL = 0;
/** {@collect.stats} Vertical orientation. Used for scrollbars and sliders. */
public static final int VERTICAL = 1;
//
// Constants for orientation support, since some languages are
// left-to-right oriented and some are right-to-left oriented.
// This orientation is currently used by buttons and labels.
//
/** {@collect.stats}
* Identifies the leading edge of text for use with left-to-right
* and right-to-left languages. Used by buttons and labels.
*/
public static final int LEADING = 10;
/** {@collect.stats}
* Identifies the trailing edge of text for use with left-to-right
* and right-to-left languages. Used by buttons and labels.
*/
public static final int TRAILING = 11;
/** {@collect.stats}
* Identifies the next direction in a sequence.
*
* @since 1.4
*/
public static final int NEXT = 12;
/** {@collect.stats}
* Identifies the previous direction in a sequence.
*
* @since 1.4
*/
public static final int PREVIOUS = 13;
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import sun.awt.ModalExclude;
import sun.awt.SunToolkit;
/** {@collect.stats}
* Popups are used to display a <code>Component</code> to the user, typically
* on top of all the other <code>Component</code>s in a particular containment
* hierarchy. <code>Popup</code>s have a very small life cycle. Once you
* have obtained a <code>Popup</code>, and hidden it (invoked the
* <code>hide</code> method), you should no longer
* invoke any methods on it. This allows the <code>PopupFactory</code> to cache
* <code>Popup</code>s for later use.
* <p>
* The general contract is that if you need to change the size of the
* <code>Component</code>, or location of the <code>Popup</code>, you should
* obtain a new <code>Popup</code>.
* <p>
* <code>Popup</code> does not descend from <code>Component</code>, rather
* implementations of <code>Popup</code> are responsible for creating
* and maintaining their own <code>Component</code>s to render the
* requested <code>Component</code> to the user.
* <p>
* You typically do not explicitly create an instance of <code>Popup</code>,
* instead obtain one from a <code>PopupFactory</code>.
*
* @see PopupFactory
*
* @since 1.4
*/
public class Popup {
/** {@collect.stats}
* The Component representing the Popup.
*/
private Component component;
/** {@collect.stats}
* Creates a <code>Popup</code> for the Component <code>owner</code>
* containing the Component <code>contents</code>. <code>owner</code>
* is used to determine which <code>Window</code> the new
* <code>Popup</code> will parent the <code>Component</code> the
* <code>Popup</code> creates to.
* A null <code>owner</code> implies there is no valid parent.
* <code>x</code> and
* <code>y</code> specify the preferred initial location to place
* the <code>Popup</code> at. Based on screen size, or other paramaters,
* the <code>Popup</code> may not display at <code>x</code> and
* <code>y</code>.
*
* @param owner Component mouse coordinates are relative to, may be null
* @param contents Contents of the Popup
* @param x Initial x screen coordinate
* @param y Initial y screen coordinate
* @exception IllegalArgumentException if contents is null
*/
protected Popup(Component owner, Component contents, int x, int y) {
this();
if (contents == null) {
throw new IllegalArgumentException("Contents must be non-null");
}
reset(owner, contents, x, y);
}
/** {@collect.stats}
* Creates a <code>Popup</code>. This is provided for subclasses.
*/
protected Popup() {
}
/** {@collect.stats}
* Makes the <code>Popup</code> visible. If the <code>Popup</code> is
* currently visible, this has no effect.
*/
public void show() {
Component component = getComponent();
if (component != null) {
component.show();
}
}
/** {@collect.stats}
* Hides and disposes of the <code>Popup</code>. Once a <code>Popup</code>
* has been disposed you should no longer invoke methods on it. A
* <code>dispose</code>d <code>Popup</code> may be reclaimed and later used
* based on the <code>PopupFactory</code>. As such, if you invoke methods
* on a <code>disposed</code> <code>Popup</code>, indeterminate
* behavior will result.
*/
public void hide() {
Component component = getComponent();
if (component instanceof JWindow) {
component.hide();
((JWindow)component).getContentPane().removeAll();
}
dispose();
}
/** {@collect.stats}
* Frees any resources the <code>Popup</code> may be holding onto.
*/
void dispose() {
Component component = getComponent();
Window window = SwingUtilities.getWindowAncestor(component);
if (component instanceof JWindow) {
((Window)component).dispose();
component = null;
}
// If our parent is a DefaultFrame, we need to dispose it, too.
if (window instanceof DefaultFrame) {
window.dispose();
}
}
/** {@collect.stats}
* Resets the <code>Popup</code> to an initial state.
*/
void reset(Component owner, Component contents, int ownerX, int ownerY) {
if (getComponent() == null) {
component = createComponent(owner);
}
Component c = getComponent();
if (c instanceof JWindow) {
JWindow component = (JWindow)getComponent();
component.setLocation(ownerX, ownerY);
component.getContentPane().add(contents, BorderLayout.CENTER);
contents.invalidate();
if(component.isVisible()) {
// Do not call pack() if window is not visible to
// avoid early native peer creation
pack();
}
}
}
/** {@collect.stats}
* Causes the <code>Popup</code> to be sized to fit the preferred size
* of the <code>Component</code> it contains.
*/
void pack() {
Component component = getComponent();
if (component instanceof Window) {
((Window)component).pack();
}
}
/** {@collect.stats}
* Returns the <code>Window</code> to use as the parent of the
* <code>Window</code> created for the <code>Popup</code>. This creates
* a new <code>DefaultFrame</code>, if necessary.
*/
private Window getParentWindow(Component owner) {
Window window = null;
if (owner instanceof Window) {
window = (Window)owner;
}
else if (owner != null) {
window = SwingUtilities.getWindowAncestor(owner);
}
if (window == null) {
window = new DefaultFrame();
}
return window;
}
/** {@collect.stats}
* Creates the Component to use as the parent of the <code>Popup</code>.
* The default implementation creates a <code>Window</code>, subclasses
* should override.
*/
Component createComponent(Component owner) {
if (GraphicsEnvironment.isHeadless()) {
// Generally not useful, bail.
return null;
}
return new HeavyWeightWindow(getParentWindow(owner));
}
/** {@collect.stats}
* Returns the <code>Component</code> returned from
* <code>createComponent</code> that will hold the <code>Popup</code>.
*/
Component getComponent() {
return component;
}
/** {@collect.stats}
* Component used to house window.
*/
static class HeavyWeightWindow extends JWindow implements ModalExclude {
HeavyWeightWindow(Window parent) {
super(parent);
setFocusableWindowState(false);
Toolkit tk = Toolkit.getDefaultToolkit();
if (tk instanceof SunToolkit) {
// all the short-lived windows like Popups should be
// OverrideRedirect on X11 platforms
((SunToolkit)tk).setOverrideRedirect(this);
}
// Popups are typically transient and most likely won't benefit
// from true double buffering. Turn it off here.
getRootPane().setUseTrueDoubleBuffering(false);
// Try to set "always-on-top" for the popup window.
// Applets usually don't have sufficient permissions to do it.
// In this case simply ignore the exception.
try {
setAlwaysOnTop(true);
} catch (SecurityException se) {
// setAlwaysOnTop is restricted,
// the exception is ignored
}
}
public void update(Graphics g) {
paint(g);
}
public void show() {
this.pack();
if (getWidth() > 0 && getHeight() > 0) {
super.show();
}
}
}
/** {@collect.stats}
* Used if no valid Window ancestor of the supplied owner is found.
* <p>
* PopupFactory uses this as a way to know when the Popup shouldn't
* be cached based on the Window.
*/
static class DefaultFrame extends Frame {
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.beans.PropertyChangeListener;
import java.util.Locale;
import java.util.Vector;
import java.io.Serializable;
import javax.accessibility.*;
/** {@collect.stats}
* An extended version of <code>java.applet.Applet</code> that adds support for
* the JFC/Swing component architecture.
* You can find task-oriented documentation about using <code>JApplet</code>
* in <em>The Java Tutorial</em>,
* in the section
* <a
href="http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html">How to Make Applets</a>.
* <p>
* The <code>JApplet</code> class is slightly incompatible with
* <code>java.applet.Applet</code>. <code>JApplet</code> contains a
* <code>JRootPane</code> as its only child. The <code>contentPane</code>
* should be the parent of any children of the <code>JApplet</code>.
* As a convenience <code>add</code> and its variants, <code>remove</code> and
* <code>setLayout</code> have been overridden to forward to the
* <code>contentPane</code> as necessary. This means you can write:
* <pre>
* applet.add(child);
* </pre>
*
* And the child will be added to the <code>contentPane</code>.
* The <code>contentPane</code> will always be non-<code>null</code>.
* Attempting to set it to <code>null</code> will cause the
* <code>JApplet</code> to throw an exception. The default
* <code>contentPane</code> will have a <code>BorderLayout</code>
* manager set on it.
* Refer to {@link javax.swing.RootPaneContainer}
* for details on adding, removing and setting the <code>LayoutManager</code>
* of a <code>JApplet</code>.
* <p>
* Please see the <code>JRootPane</code> documentation for a
* complete description of the <code>contentPane</code>, <code>glassPane</code>,
* and <code>layeredPane</code> properties.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see javax.swing.RootPaneContainer
* @beaninfo
* attribute: isContainer true
* attribute: containerDelegate getContentPane
* description: Swing's Applet subclass.
*
* @author Arnaud Weber
*/
public class JApplet extends Applet implements Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
/** {@collect.stats}
* @see #getRootPane
* @see #setRootPane
*/
protected JRootPane rootPane;
/** {@collect.stats}
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>JApplet</code> is constructed.
*
* @see #isRootPaneCheckingEnabled
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean rootPaneCheckingEnabled = false;
/** {@collect.stats}
* The <code>TransferHandler</code> for this applet.
*/
private TransferHandler transferHandler;
/** {@collect.stats}
* Creates a swing applet instance.
* <p>
* This constructor sets the component's locale property to the value
* returned by <code>JComponent.getDefaultLocale</code>.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @see JComponent#getDefaultLocale
*/
public JApplet() throws HeadlessException {
super();
// Check the timerQ and restart if necessary.
TimerQueue q = TimerQueue.sharedInstance();
if(q != null) {
q.startIfNeeded();
}
/* Workaround for bug 4155072. The shared double buffer image
* may hang on to a reference to this applet; unfortunately
* Image.getGraphics() will continue to call JApplet.getForeground()
* and getBackground() even after this applet has been destroyed.
* So we ensure that these properties are non-null here.
*/
setForeground(Color.black);
setBackground(Color.white);
setLocale( JComponent.getDefaultLocale() );
setLayout(new BorderLayout());
setRootPane(createRootPane());
setRootPaneCheckingEnabled(true);
setFocusTraversalPolicyProvider(true);
sun.awt.SunToolkit.checkAndSetPolicy(this, true);
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
/** {@collect.stats} Called by the constructor methods to create the default rootPane. */
protected JRootPane createRootPane() {
JRootPane rp = new JRootPane();
// NOTE: this uses setOpaque vs LookAndFeel.installProperty as there
// is NO reason for the RootPane not to be opaque. For painting to
// work the contentPane must be opaque, therefor the RootPane can
// also be opaque.
rp.setOpaque(true);
return rp;
}
/** {@collect.stats}
* Sets the {@code transferHandler} property, which is a mechanism to
* support transfer of data into this component. Use {@code null}
* if the component does not support data transfer operations.
* <p>
* If the system property {@code suppressSwingDropSupport} is {@code false}
* (the default) and the current drop target on this component is either
* {@code null} or not a user-set drop target, this method will change the
* drop target as follows: If {@code newHandler} is {@code null} it will
* clear the drop target. If not {@code null} it will install a new
* {@code DropTarget}.
* <p>
* Note: When used with {@code JApplet}, {@code TransferHandler} only
* provides data import capability, as the data export related methods
* are currently typed to {@code JComponent}.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html">
* How to Use Drag and Drop and Data Transfer</a>, a section in
* <em>The Java Tutorial</em>, for more information.
*
* @param newHandler the new {@code TransferHandler}
*
* @see TransferHandler
* @see #getTransferHandler
* @see java.awt.Component#setDropTarget
* @since 1.6
*
* @beaninfo
* bound: true
* hidden: true
* description: Mechanism for transfer of data into the component
*/
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = transferHandler;
transferHandler = newHandler;
SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/** {@collect.stats}
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.6
*/
public TransferHandler getTransferHandler() {
return transferHandler;
}
/** {@collect.stats}
* Just calls <code>paint(g)</code>. This method was overridden to
* prevent an unnecessary call to clear the background.
*/
public void update(Graphics g) {
paint(g);
}
/** {@collect.stats}
* Sets the menubar for this applet.
* @param menuBar the menubar being placed in the applet
*
* @see #getJMenuBar
*
* @beaninfo
* hidden: true
* description: The menubar for accessing pulldown menus from this applet.
*/
public void setJMenuBar(JMenuBar menuBar) {
getRootPane().setMenuBar(menuBar);
}
/** {@collect.stats}
* Returns the menubar set on this applet.
*
* @see #setJMenuBar
*/
public JMenuBar getJMenuBar() {
return getRootPane().getMenuBar();
}
/** {@collect.stats}
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @return true if <code>add</code> and <code>setLayout</code>
* are fowarded; false otherwise
*
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/** {@collect.stats}
* Sets whether calls to <code>add</code> and
* <code>setLayout</code> are forwarded to the <code>contentPane</code>.
*
* @param enabled true if <code>add</code> and <code>setLayout</code>
* are forwarded, false if they should operate directly on the
* <code>JApplet</code>.
*
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
* @beaninfo
* hidden: true
* description: Whether the add and setLayout methods are forwarded
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/** {@collect.stats}
* Adds the specified child <code>Component</code>.
* This method is overridden to conditionally forward calls to the
* <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for
* details.
*
* @param comp the component to be enhanced
* @param constraints the constraints to be respected
* @param index the index
* @exception IllegalArgumentException if <code>index</code> is invalid
* @exception IllegalArgumentException if adding the container's parent
* to itself
* @exception IllegalArgumentException if adding a window to a container
*
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
protected void addImpl(Component comp, Object constraints, int index)
{
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/** {@collect.stats}
* Removes the specified component from the container. If
* <code>comp</code> is not the <code>rootPane</code>, this will forward
* the call to the <code>contentPane</code>. This will do nothing if
* <code>comp</code> is not a child of the <code>JFrame</code> or
* <code>contentPane</code>.
*
* @param comp the component to be removed
* @throws NullPointerException if <code>comp</code> is null
* @see #add
* @see javax.swing.RootPaneContainer
*/
public void remove(Component comp) {
if (comp == rootPane) {
super.remove(comp);
} else {
getContentPane().remove(comp);
}
}
/** {@collect.stats}
* Sets the <code>LayoutManager</code>.
* Overridden to conditionally forward the call to the
* <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for
* more information.
*
* @param manager the <code>LayoutManager</code>
* @see #setRootPaneCheckingEnabled
* @see javax.swing.RootPaneContainer
*/
public void setLayout(LayoutManager manager) {
if(isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
/** {@collect.stats}
* Returns the rootPane object for this applet.
*
* @see #setRootPane
* @see RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/** {@collect.stats}
* Sets the rootPane property. This method is called by the constructor.
* @param root the rootPane object for this applet
*
* @see #getRootPane
*
* @beaninfo
* hidden: true
* description: the RootPane object for this applet.
*/
protected void setRootPane(JRootPane root) {
if(rootPane != null) {
remove(rootPane);
}
rootPane = root;
if(rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
}
/** {@collect.stats}
* Returns the contentPane object for this applet.
*
* @see #setContentPane
* @see RootPaneContainer#getContentPane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/** {@collect.stats}
* Sets the contentPane property. This method is called by the constructor.
* @param contentPane the contentPane object for this applet
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is null
* @see #getContentPane
* @see RootPaneContainer#setContentPane
*
* @beaninfo
* hidden: true
* description: The client area of the applet where child
* components are normally inserted.
*/
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
/** {@collect.stats}
* Returns the layeredPane object for this applet.
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is null
* @see #setLayeredPane
* @see RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/** {@collect.stats}
* Sets the layeredPane property. This method is called by the constructor.
* @param layeredPane the layeredPane object for this applet
*
* @see #getLayeredPane
* @see RootPaneContainer#setLayeredPane
*
* @beaninfo
* hidden: true
* description: The pane which holds the various applet layers.
*/
public void setLayeredPane(JLayeredPane layeredPane) {
getRootPane().setLayeredPane(layeredPane);
}
/** {@collect.stats}
* Returns the glassPane object for this applet.
*
* @see #setGlassPane
* @see RootPaneContainer#getGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/** {@collect.stats}
* Sets the glassPane property.
* This method is called by the constructor.
* @param glassPane the glassPane object for this applet
*
* @see #getGlassPane
* @see RootPaneContainer#setGlassPane
*
* @beaninfo
* hidden: true
* description: A transparent pane used for menu rendering.
*/
public void setGlassPane(Component glassPane) {
getRootPane().setGlassPane(glassPane);
}
/** {@collect.stats}
* {@inheritDoc}
*
* @since 1.6
*/
public Graphics getGraphics() {
JComponent.getGraphicsInvoked(this);
return super.getGraphics();
}
/** {@collect.stats}
* Repaints the specified rectangle of this component within
* <code>time</code> milliseconds. Refer to <code>RepaintManager</code>
* for details on how the repaint is handled.
*
* @param time maximum time in milliseconds before update
* @param x the <i>x</i> coordinate
* @param y the <i>y</i> coordinate
* @param width the width
* @param height the height
* @see RepaintManager
* @since 1.6
*/
public void repaint(long time, int x, int y, int width, int height) {
if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) {
RepaintManager.currentManager(this).addDirtyRegion(
this, x, y, width, height);
}
else {
super.repaint(time, x, y, width, height);
}
}
/** {@collect.stats}
* Returns a string representation of this JApplet. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JApplet.
*/
protected String paramString() {
String rootPaneString = (rootPane != null ?
rootPane.toString() : "");
String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ?
"true" : "false");
return super.paramString() +
",rootPane=" + rootPaneString +
",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString;
}
/////////////////
// Accessibility support
////////////////
protected AccessibleContext accessibleContext = null;
/** {@collect.stats}
* Gets the AccessibleContext associated with this JApplet.
* For JApplets, the AccessibleContext takes the form of an
* AccessibleJApplet.
* A new AccessibleJApplet instance is created if necessary.
*
* @return an AccessibleJApplet that serves as the
* AccessibleContext of this JApplet
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJApplet();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JApplet</code> class.
*/
protected class AccessibleJApplet extends AccessibleApplet {
// everything moved to new parent, AccessibleApplet
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import sun.swing.SwingUtilities2;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* A component that lets the user switch between a group of components by
* clicking on a tab with a given title and/or icon.
* For examples and information on using tabbed panes see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html">How to Use Tabbed Panes</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Tabs/components are added to a <code>TabbedPane</code> object by using the
* <code>addTab</code> and <code>insertTab</code> methods.
* A tab is represented by an index corresponding
* to the position it was added in, where the first tab has an index equal to 0
* and the last tab has an index equal to the tab count minus 1.
* <p>
* The <code>TabbedPane</code> uses a <code>SingleSelectionModel</code>
* to represent the set
* of tab indices and the currently selected index. If the tab count
* is greater than 0, then there will always be a selected index, which
* by default will be initialized to the first tab. If the tab count is
* 0, then the selected index will be -1.
* <p>
* The tab title can be rendered by a <code>Component</code>.
* For example, the following produce similar results:
* <pre>
* // In this case the look and feel renders the title for the tab.
* tabbedPane.addTab("Tab", myComponent);
* // In this case the custom component is responsible for rendering the
* // title of the tab.
* tabbedPane.addTab(null, myComponent);
* tabbedPane.setTabComponentAt(0, new JLabel("Tab"));
* </pre>
* The latter is typically used when you want a more complex user interaction
* that requires custom components on the tab. For example, you could
* provide a custom component that animates or one that has widgets for
* closing the tab.
* <p>
* If you specify a component for a tab, the <code>JTabbedPane</code>
* will not render any text or icon you have specified for the tab.
* <p>
* <strong>Note:</strong>
* Do not use <code>setVisible</code> directly on a tab component to make it visible,
* use <code>setSelectedComponent</code> or <code>setSelectedIndex</code> methods instead.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer true
* description: A component which provides a tab folder metaphor for
* displaying one component from a set of components.
*
* @author Dave Moore
* @author Philip Milne
* @author Amy Fowler
*
* @see SingleSelectionModel
*/
public class JTabbedPane extends JComponent
implements Serializable, Accessible, SwingConstants {
/** {@collect.stats}
* The tab layout policy for wrapping tabs in multiple runs when all
* tabs will not fit within a single run.
*/
public static final int WRAP_TAB_LAYOUT = 0;
/** {@collect.stats}
* Tab layout policy for providing a subset of available tabs when all
* the tabs will not fit within a single run. If all the tabs do
* not fit within a single run the look and feel will provide a way
* to navigate to hidden tabs.
*/
public static final int SCROLL_TAB_LAYOUT = 1;
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TabbedPaneUI";
/** {@collect.stats}
* Where the tabs are placed.
* @see #setTabPlacement
*/
protected int tabPlacement = TOP;
private int tabLayoutPolicy;
/** {@collect.stats} The default selection model */
protected SingleSelectionModel model;
private boolean haveRegistered;
/** {@collect.stats}
* The <code>changeListener</code> is the listener we add to the
* model.
*/
protected ChangeListener changeListener = null;
private final java.util.List<Page> pages;
/* The component that is currently visible */
private Component visComp = null;
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per <code>TabPane</code>
* instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this".
*/
protected transient ChangeEvent changeEvent = null;
/** {@collect.stats}
* Creates an empty <code>TabbedPane</code> with a default
* tab placement of <code>JTabbedPane.TOP</code>.
* @see #addTab
*/
public JTabbedPane() {
this(TOP, WRAP_TAB_LAYOUT);
}
/** {@collect.stats}
* Creates an empty <code>TabbedPane</code> with the specified tab placement
* of either: <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>,
* <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>.
*
* @param tabPlacement the placement for the tabs relative to the content
* @see #addTab
*/
public JTabbedPane(int tabPlacement) {
this(tabPlacement, WRAP_TAB_LAYOUT);
}
/** {@collect.stats}
* Creates an empty <code>TabbedPane</code> with the specified tab placement
* and tab layout policy. Tab placement may be either:
* <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>,
* <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>.
* Tab layout policy may be either: <code>JTabbedPane.WRAP_TAB_LAYOUT</code>
* or <code>JTabbedPane.SCROLL_TAB_LAYOUT</code>.
*
* @param tabPlacement the placement for the tabs relative to the content
* @param tabLayoutPolicy the policy for laying out tabs when all tabs will not fit on one run
* @exception IllegalArgumentException if tab placement or tab layout policy are not
* one of the above supported values
* @see #addTab
* @since 1.4
*/
public JTabbedPane(int tabPlacement, int tabLayoutPolicy) {
setTabPlacement(tabPlacement);
setTabLayoutPolicy(tabLayoutPolicy);
pages = new ArrayList<Page>(1);
setModel(new DefaultSingleSelectionModel());
updateUI();
}
/** {@collect.stats}
* Returns the UI object which implements the L&F for this component.
*
* @return a <code>TabbedPaneUI</code> object
* @see #setUI
*/
public TabbedPaneUI getUI() {
return (TabbedPaneUI)ui;
}
/** {@collect.stats}
* Sets the UI object which implements the L&F for this component.
*
* @param ui the new UI object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the tabbedpane's LookAndFeel
*/
public void setUI(TabbedPaneUI ui) {
super.setUI(ui);
// disabled icons are generated by LF so they should be unset here
for (int i = 0; i < getTabCount(); i++) {
Icon icon = pages.get(i).disabledIcon;
if (icon instanceof UIResource) {
setDisabledIconAt(i, null);
}
}
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((TabbedPaneUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the UI class that implements the
* L&F for this component.
*
* @return the string "TabbedPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* We pass <code>ModelChanged</code> events along to the listeners with
* the tabbedpane (instead of the model itself) as the event source.
*/
protected class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
fireStateChanged();
}
}
/** {@collect.stats}
* Subclasses that want to handle <code>ChangeEvents</code> differently
* can override this to return a subclass of <code>ModelListener</code> or
* another <code>ChangeListener</code> implementation.
*
* @see #fireStateChanged
*/
protected ChangeListener createChangeListener() {
return new ModelListener();
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to this tabbedpane.
*
* @param l the <code>ChangeListener</code> to add
* @see #fireStateChanged
* @see #removeChangeListener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from this tabbedpane.
*
* @param l the <code>ChangeListener</code> to remove
* @see #fireStateChanged
* @see #addChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this <code>JTabbedPane</code> with <code>addChangeListener</code>.
*
* @return all of the <code>ChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Sends a {@code ChangeEvent}, with this {@code JTabbedPane} as the source,
* to each registered listener. This method is called each time there is
* a change to either the selected index or the selected tab in the
* {@code JTabbedPane}. Usually, the selected index and selected tab change
* together. However, there are some cases, such as tab addition, where the
* selected index changes and the same tab remains selected. There are other
* cases, such as deleting the selected tab, where the index remains the
* same, but a new tab moves to that index. Events are fired for all of
* these cases.
*
* @see #addChangeListener
* @see EventListenerList
*/
protected void fireStateChanged() {
/* --- Begin code to deal with visibility --- */
/* This code deals with changing the visibility of components to
* hide and show the contents for the selected tab. It duplicates
* logic already present in BasicTabbedPaneUI, logic that is
* processed during the layout pass. This code exists to allow
* developers to do things that are quite difficult to accomplish
* with the previous model of waiting for the layout pass to process
* visibility changes; such as requesting focus on the new visible
* component.
*
* For the average code, using the typical JTabbedPane methods,
* all visibility changes will now be processed here. However,
* the code in BasicTabbedPaneUI still exists, for the purposes
* of backward compatibility. Therefore, when making changes to
* this code, ensure that the BasicTabbedPaneUI code is kept in
* synch.
*/
int selIndex = getSelectedIndex();
/* if the selection is now nothing */
if (selIndex < 0) {
/* if there was a previous visible component */
if (visComp != null && visComp.isVisible()) {
/* make it invisible */
visComp.setVisible(false);
}
/* now there's no visible component */
visComp = null;
/* else - the selection is now something */
} else {
/* Fetch the component for the new selection */
Component newComp = getComponentAt(selIndex);
/* if the new component is non-null and different */
if (newComp != null && newComp != visComp) {
boolean shouldChangeFocus = false;
/* Note: the following (clearing of the old visible component)
* is inside this if-statement for good reason: Tabbed pane
* should continue to show the previously visible component
* if there is no component for the chosen tab.
*/
/* if there was a previous visible component */
if (visComp != null) {
shouldChangeFocus =
(SwingUtilities.findFocusOwner(visComp) != null);
/* if it's still visible */
if (visComp.isVisible()) {
/* make it invisible */
visComp.setVisible(false);
}
}
if (!newComp.isVisible()) {
newComp.setVisible(true);
}
if (shouldChangeFocus) {
SwingUtilities2.tabbedPaneChangeFocusTo(newComp);
}
visComp = newComp;
} /* else - the visible component shouldn't changed */
}
/* --- End code to deal with visibility --- */
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns the model associated with this tabbedpane.
*
* @see #setModel
*/
public SingleSelectionModel getModel() {
return model;
}
/** {@collect.stats}
* Sets the model to be used with this tabbedpane.
*
* @param model the model to be used
* @see #getModel
* @beaninfo
* bound: true
* description: The tabbedpane's SingleSelectionModel.
*/
public void setModel(SingleSelectionModel model) {
SingleSelectionModel oldModel = getModel();
if (oldModel != null) {
oldModel.removeChangeListener(changeListener);
changeListener = null;
}
this.model = model;
if (model != null) {
changeListener = createChangeListener();
model.addChangeListener(changeListener);
}
firePropertyChange("model", oldModel, model);
repaint();
}
/** {@collect.stats}
* Returns the placement of the tabs for this tabbedpane.
* @see #setTabPlacement
*/
public int getTabPlacement() {
return tabPlacement;
}
/** {@collect.stats}
* Sets the tab placement for this tabbedpane.
* Possible values are:<ul>
* <li><code>JTabbedPane.TOP</code>
* <li><code>JTabbedPane.BOTTOM</code>
* <li><code>JTabbedPane.LEFT</code>
* <li><code>JTabbedPane.RIGHT</code>
* </ul>
* The default value, if not set, is <code>SwingConstants.TOP</code>.
*
* @param tabPlacement the placement for the tabs relative to the content
* @exception IllegalArgumentException if tab placement value isn't one
* of the above valid values
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* enum: TOP JTabbedPane.TOP
* LEFT JTabbedPane.LEFT
* BOTTOM JTabbedPane.BOTTOM
* RIGHT JTabbedPane.RIGHT
* description: The tabbedpane's tab placement.
*
*/
public void setTabPlacement(int tabPlacement) {
if (tabPlacement != TOP && tabPlacement != LEFT &&
tabPlacement != BOTTOM && tabPlacement != RIGHT) {
throw new IllegalArgumentException("illegal tab placement: must be TOP, BOTTOM, LEFT, or RIGHT");
}
if (this.tabPlacement != tabPlacement) {
int oldValue = this.tabPlacement;
this.tabPlacement = tabPlacement;
firePropertyChange("tabPlacement", oldValue, tabPlacement);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the policy used by the tabbedpane to layout the tabs when all the
* tabs will not fit within a single run.
* @see #setTabLayoutPolicy
* @since 1.4
*/
public int getTabLayoutPolicy() {
return tabLayoutPolicy;
}
/** {@collect.stats}
* Sets the policy which the tabbedpane will use in laying out the tabs
* when all the tabs will not fit within a single run.
* Possible values are:
* <ul>
* <li><code>JTabbedPane.WRAP_TAB_LAYOUT</code>
* <li><code>JTabbedPane.SCROLL_TAB_LAYOUT</code>
* </ul>
*
* The default value, if not set by the UI, is <code>JTabbedPane.WRAP_TAB_LAYOUT</code>.
* <p>
* Some look and feels might only support a subset of the possible
* layout policies, in which case the value of this property may be
* ignored.
*
* @param tabLayoutPolicy the policy used to layout the tabs
* @exception IllegalArgumentException if layoutPolicy value isn't one
* of the above valid values
* @see #getTabLayoutPolicy
* @since 1.4
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* enum: WRAP_TAB_LAYOUT JTabbedPane.WRAP_TAB_LAYOUT
* SCROLL_TAB_LAYOUT JTabbedPane.SCROLL_TAB_LAYOUT
* description: The tabbedpane's policy for laying out the tabs
*
*/
public void setTabLayoutPolicy(int tabLayoutPolicy) {
if (tabLayoutPolicy != WRAP_TAB_LAYOUT && tabLayoutPolicy != SCROLL_TAB_LAYOUT) {
throw new IllegalArgumentException("illegal tab layout policy: must be WRAP_TAB_LAYOUT or SCROLL_TAB_LAYOUT");
}
if (this.tabLayoutPolicy != tabLayoutPolicy) {
int oldValue = this.tabLayoutPolicy;
this.tabLayoutPolicy = tabLayoutPolicy;
firePropertyChange("tabLayoutPolicy", oldValue, tabLayoutPolicy);
revalidate();
repaint();
}
}
/** {@collect.stats}
* Returns the currently selected index for this tabbedpane.
* Returns -1 if there is no currently selected tab.
*
* @return the index of the selected tab
* @see #setSelectedIndex
*/
public int getSelectedIndex() {
return model.getSelectedIndex();
}
/** {@collect.stats}
* Sets the selected index for this tabbedpane. The index must be
* a valid tab index or -1, which indicates that no tab should be selected
* (can also be used when there are no tabs in the tabbedpane). If a -1
* value is specified when the tabbedpane contains one or more tabs, then
* the results will be implementation defined.
*
* @param index the index to be selected
* @exception IndexOutOfBoundsException if index is out of range
* (index < -1 || index >= tab count)
*
* @see #getSelectedIndex
* @see SingleSelectionModel#setSelectedIndex
* @beaninfo
* preferred: true
* description: The tabbedpane's selected tab index.
*/
public void setSelectedIndex(int index) {
if (index != -1) {
checkIndex(index);
}
setSelectedIndexImpl(index, true);
}
private void setSelectedIndexImpl(int index, boolean doAccessibleChanges) {
int oldIndex = model.getSelectedIndex();
Page oldPage = null, newPage = null;
String oldName = null;
doAccessibleChanges = doAccessibleChanges && (oldIndex != index);
if (doAccessibleChanges) {
if (accessibleContext != null) {
oldName = accessibleContext.getAccessibleName();
}
if (oldIndex >= 0) {
oldPage = pages.get(oldIndex);
}
if (index >= 0) {
newPage = pages.get(index);
}
}
model.setSelectedIndex(index);
if (doAccessibleChanges) {
changeAccessibleSelection(oldPage, oldName, newPage);
}
}
private void changeAccessibleSelection(Page oldPage, String oldName, Page newPage) {
if (accessibleContext == null) {
return;
}
if (oldPage != null) {
oldPage.firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.SELECTED, null);
}
if (newPage != null) {
newPage.firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.SELECTED);
}
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_NAME_PROPERTY,
oldName,
accessibleContext.getAccessibleName());
}
/** {@collect.stats}
* Returns the currently selected component for this tabbedpane.
* Returns <code>null</code> if there is no currently selected tab.
*
* @return the component corresponding to the selected tab
* @see #setSelectedComponent
*/
public Component getSelectedComponent() {
int index = getSelectedIndex();
if (index == -1) {
return null;
}
return getComponentAt(index);
}
/** {@collect.stats}
* Sets the selected component for this tabbedpane. This
* will automatically set the <code>selectedIndex</code> to the index
* corresponding to the specified component.
*
* @exception IllegalArgumentException if component not found in tabbed
* pane
* @see #getSelectedComponent
* @beaninfo
* preferred: true
* description: The tabbedpane's selected component.
*/
public void setSelectedComponent(Component c) {
int index = indexOfComponent(c);
if (index != -1) {
setSelectedIndex(index);
} else {
throw new IllegalArgumentException("component not found in tabbed pane");
}
}
/** {@collect.stats}
* Inserts a new tab for the given component, at the given index,
* represented by the given title and/or icon, either of which may
* be {@code null}.
*
* @param title the title to be displayed on the tab
* @param icon the icon to be displayed on the tab
* @param component the component to be displayed when this tab is clicked.
* @param tip the tooltip to be displayed for this tab
* @param index the position to insert this new tab
* ({@code > 0 and <= getTabCount()})
*
* @throws IndexOutOfBoundsException if the index is out of range
* ({@code < 0 or > getTabCount()})
*
* @see #addTab
* @see #removeTabAt
*/
public void insertTab(String title, Icon icon, Component component, String tip, int index) {
int newIndex = index;
// If component already exists, remove corresponding
// tab so that new tab gets added correctly
// Note: we are allowing component=null because of compatibility,
// but we really should throw an exception because much of the
// rest of the JTabbedPane implementation isn't designed to deal
// with null components for tabs.
int removeIndex = indexOfComponent(component);
if (component != null && removeIndex != -1) {
removeTabAt(removeIndex);
if (newIndex > removeIndex) {
newIndex--;
}
}
int selectedIndex = getSelectedIndex();
pages.add(
newIndex,
new Page(this, title != null? title : "", icon, null, component, tip));
if (component != null) {
addImpl(component, null, -1);
component.setVisible(false);
} else {
firePropertyChange("indexForNullComponent", -1, index);
}
if (pages.size() == 1) {
setSelectedIndex(0);
}
if (selectedIndex >= newIndex) {
setSelectedIndexImpl(selectedIndex + 1, false);
}
if (!haveRegistered && tip != null) {
ToolTipManager.sharedInstance().registerComponent(this);
haveRegistered = true;
}
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
null, component);
}
revalidate();
repaint();
}
/** {@collect.stats}
* Adds a <code>component</code> and <code>tip</code>
* represented by a <code>title</code> and/or <code>icon</code>,
* either of which can be <code>null</code>.
* Cover method for <code>insertTab</code>.
*
* @param title the title to be displayed in this tab
* @param icon the icon to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
* @param tip the tooltip to be displayed for this tab
*
* @see #insertTab
* @see #removeTabAt
*/
public void addTab(String title, Icon icon, Component component, String tip) {
insertTab(title, icon, component, tip, pages.size());
}
/** {@collect.stats}
* Adds a <code>component</code> represented by a <code>title</code>
* and/or <code>icon</code>, either of which can be <code>null</code>.
* Cover method for <code>insertTab</code>.
*
* @param title the title to be displayed in this tab
* @param icon the icon to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
*
* @see #insertTab
* @see #removeTabAt
*/
public void addTab(String title, Icon icon, Component component) {
insertTab(title, icon, component, null, pages.size());
}
/** {@collect.stats}
* Adds a <code>component</code> represented by a <code>title</code>
* and no icon.
* Cover method for <code>insertTab</code>.
*
* @param title the title to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
*
* @see #insertTab
* @see #removeTabAt
*/
public void addTab(String title, Component component) {
insertTab(title, null, component, null, pages.size());
}
/** {@collect.stats}
* Adds a <code>component</code> with a tab title defaulting to
* the name of the component which is the result of calling
* <code>component.getName</code>.
* Cover method for <code>insertTab</code>.
*
* @param component the component to be displayed when this tab is clicked
* @return the component
*
* @see #insertTab
* @see #removeTabAt
*/
public Component add(Component component) {
if (!(component instanceof UIResource)) {
addTab(component.getName(), component);
} else {
super.add(component);
}
return component;
}
/** {@collect.stats}
* Adds a <code>component</code> with the specified tab title.
* Cover method for <code>insertTab</code>.
*
* @param title the title to be displayed in this tab
* @param component the component to be displayed when this tab is clicked
* @return the component
*
* @see #insertTab
* @see #removeTabAt
*/
public Component add(String title, Component component) {
if (!(component instanceof UIResource)) {
addTab(title, component);
} else {
super.add(title, component);
}
return component;
}
/** {@collect.stats}
* Adds a <code>component</code> at the specified tab index with a tab
* title defaulting to the name of the component.
* Cover method for <code>insertTab</code>.
*
* @param component the component to be displayed when this tab is clicked
* @param index the position to insert this new tab
* @return the component
*
* @see #insertTab
* @see #removeTabAt
*/
public Component add(Component component, int index) {
if (!(component instanceof UIResource)) {
// Container.add() interprets -1 as "append", so convert
// the index appropriately to be handled by the vector
insertTab(component.getName(), null, component, null,
index == -1? getTabCount() : index);
} else {
super.add(component, index);
}
return component;
}
/** {@collect.stats}
* Adds a <code>component</code> to the tabbed pane.
* If <code>constraints</code> is a <code>String</code> or an
* <code>Icon</code>, it will be used for the tab title,
* otherwise the component's name will be used as the tab title.
* Cover method for <code>insertTab</code>.
*
* @param component the component to be displayed when this tab is clicked
* @param constraints the object to be displayed in the tab
*
* @see #insertTab
* @see #removeTabAt
*/
public void add(Component component, Object constraints) {
if (!(component instanceof UIResource)) {
if (constraints instanceof String) {
addTab((String)constraints, component);
} else if (constraints instanceof Icon) {
addTab(null, (Icon)constraints, component);
} else {
add(component);
}
} else {
super.add(component, constraints);
}
}
/** {@collect.stats}
* Adds a <code>component</code> at the specified tab index.
* If <code>constraints</code> is a <code>String</code> or an
* <code>Icon</code>, it will be used for the tab title,
* otherwise the component's name will be used as the tab title.
* Cover method for <code>insertTab</code>.
*
* @param component the component to be displayed when this tab is clicked
* @param constraints the object to be displayed in the tab
* @param index the position to insert this new tab
*
* @see #insertTab
* @see #removeTabAt
*/
public void add(Component component, Object constraints, int index) {
if (!(component instanceof UIResource)) {
Icon icon = constraints instanceof Icon? (Icon)constraints : null;
String title = constraints instanceof String? (String)constraints : null;
// Container.add() interprets -1 as "append", so convert
// the index appropriately to be handled by the vector
insertTab(title, icon, component, null, index == -1? getTabCount() : index);
} else {
super.add(component, constraints, index);
}
}
/** {@collect.stats}
* Removes the tab at <code>index</code>.
* After the component associated with <code>index</code> is removed,
* its visibility is reset to true to ensure it will be visible
* if added to other containers.
* @param index the index of the tab to be removed
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #addTab
* @see #insertTab
*/
public void removeTabAt(int index) {
checkIndex(index);
Component component = getComponentAt(index);
boolean shouldChangeFocus = false;
int selected = getSelectedIndex();
String oldName = null;
/* if we're about to remove the visible component */
if (component == visComp) {
shouldChangeFocus = (SwingUtilities.findFocusOwner(visComp) != null);
visComp = null;
}
if (accessibleContext != null) {
/* if we're removing the selected page */
if (index == selected) {
/* fire an accessible notification that it's unselected */
pages.get(index).firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.SELECTED, null);
oldName = accessibleContext.getAccessibleName();
}
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
component, null);
}
// Force the tabComponent to be cleaned up.
setTabComponentAt(index, null);
pages.remove(index);
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
putClientProperty("__index_to_remove__", new Integer(index));
/* if the selected tab is after the removal */
if (selected > index) {
setSelectedIndexImpl(selected - 1, false);
/* if the selected tab is the last tab */
} else if (selected >= getTabCount()) {
setSelectedIndexImpl(selected - 1, false);
Page newSelected = (selected != 0)
? pages.get(selected - 1)
: null;
changeAccessibleSelection(null, oldName, newSelected);
/* selected index hasn't changed, but the associated tab has */
} else if (index == selected) {
fireStateChanged();
changeAccessibleSelection(null, oldName, pages.get(index));
}
// We can't assume the tab indices correspond to the
// container's children array indices, so make sure we
// remove the correct child!
if (component != null) {
Component components[] = getComponents();
for (int i = components.length; --i >= 0; ) {
if (components[i] == component) {
super.remove(i);
component.setVisible(true);
break;
}
}
}
if (shouldChangeFocus) {
SwingUtilities2.tabbedPaneChangeFocusTo(getSelectedComponent());
}
revalidate();
repaint();
}
/** {@collect.stats}
* Removes the specified <code>Component</code> from the
* <code>JTabbedPane</code>. The method does nothing
* if the <code>component</code> is null.
*
* @param component the component to remove from the tabbedpane
* @see #addTab
* @see #removeTabAt
*/
public void remove(Component component) {
int index = indexOfComponent(component);
if (index != -1) {
removeTabAt(index);
} else {
// Container#remove(comp) invokes Container#remove(int)
// so make sure JTabbedPane#remove(int) isn't called here
Component children[] = getComponents();
for (int i=0; i < children.length; i++) {
if (component == children[i]) {
super.remove(i);
break;
}
}
}
}
/** {@collect.stats}
* Removes the tab and component which corresponds to the specified index.
*
* @param index the index of the component to remove from the
* <code>tabbedpane</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
* @see #addTab
* @see #removeTabAt
*/
public void remove(int index) {
removeTabAt(index);
}
/** {@collect.stats}
* Removes all the tabs and their corresponding components
* from the <code>tabbedpane</code>.
*
* @see #addTab
* @see #removeTabAt
*/
public void removeAll() {
setSelectedIndexImpl(-1, true);
int tabCount = getTabCount();
// We invoke removeTabAt for each tab, otherwise we may end up
// removing Components added by the UI.
while (tabCount-- > 0) {
removeTabAt(tabCount);
}
}
/** {@collect.stats}
* Returns the number of tabs in this <code>tabbedpane</code>.
*
* @return an integer specifying the number of tabbed pages
*/
public int getTabCount() {
return pages.size();
}
/** {@collect.stats}
* Returns the number of tab runs currently used to display
* the tabs.
* @return an integer giving the number of rows if the
* <code>tabPlacement</code>
* is <code>TOP</code> or <code>BOTTOM</code>
* and the number of columns if
* <code>tabPlacement</code>
* is <code>LEFT</code> or <code>RIGHT</code>,
* or 0 if there is no UI set on this <code>tabbedpane</code>
*/
public int getTabRunCount() {
if (ui != null) {
return ((TabbedPaneUI)ui).getTabRunCount(this);
}
return 0;
}
// Getters for the Pages
/** {@collect.stats}
* Returns the tab title at <code>index</code>.
*
* @param index the index of the item being queried
* @return the title at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
* @see #setTitleAt
*/
public String getTitleAt(int index) {
return pages.get(index).title;
}
/** {@collect.stats}
* Returns the tab icon at <code>index</code>.
*
* @param index the index of the item being queried
* @return the icon at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setIconAt
*/
public Icon getIconAt(int index) {
return pages.get(index).icon;
}
/** {@collect.stats}
* Returns the tab disabled icon at <code>index</code>.
* If the tab disabled icon doesn't exist at <code>index</code>
* this will forward the call to the look and feel to construct
* an appropriate disabled Icon from the corresponding enabled
* Icon. Some look and feels might not render the disabled Icon,
* in which case it won't be created.
*
* @param index the index of the item being queried
* @return the icon at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setDisabledIconAt
*/
public Icon getDisabledIconAt(int index) {
Page page = pages.get(index);
if (page.disabledIcon == null) {
page.disabledIcon = UIManager.getLookAndFeel().getDisabledIcon(this, page.icon);
}
return page.disabledIcon;
}
/** {@collect.stats}
* Returns the tab tooltip text at <code>index</code>.
*
* @param index the index of the item being queried
* @return a string containing the tool tip text at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setToolTipTextAt
* @since 1.3
*/
public String getToolTipTextAt(int index) {
return pages.get(index).tip;
}
/** {@collect.stats}
* Returns the tab background color at <code>index</code>.
*
* @param index the index of the item being queried
* @return the <code>Color</code> of the tab background at
* <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setBackgroundAt
*/
public Color getBackgroundAt(int index) {
return pages.get(index).getBackground();
}
/** {@collect.stats}
* Returns the tab foreground color at <code>index</code>.
*
* @param index the index of the item being queried
* @return the <code>Color</code> of the tab foreground at
* <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setForegroundAt
*/
public Color getForegroundAt(int index) {
return pages.get(index).getForeground();
}
/** {@collect.stats}
* Returns whether or not the tab at <code>index</code> is
* currently enabled.
*
* @param index the index of the item being queried
* @return true if the tab at <code>index</code> is enabled;
* false otherwise
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setEnabledAt
*/
public boolean isEnabledAt(int index) {
return pages.get(index).isEnabled();
}
/** {@collect.stats}
* Returns the component at <code>index</code>.
*
* @param index the index of the item being queried
* @return the <code>Component</code> at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setComponentAt
*/
public Component getComponentAt(int index) {
return pages.get(index).component;
}
/** {@collect.stats}
* Returns the keyboard mnemonic for accessing the specified tab.
* The mnemonic is the key which when combined with the look and feel's
* mouseless modifier (usually Alt) will activate the specified
* tab.
*
* @since 1.4
* @param tabIndex the index of the tab that the mnemonic refers to
* @return the key code which represents the mnemonic;
* -1 if a mnemonic is not specified for the tab
* @exception IndexOutOfBoundsException if index is out of range
* (<code>tabIndex</code> < 0 ||
* <code>tabIndex</code> >= tab count)
* @see #setDisplayedMnemonicIndexAt(int,int)
* @see #setMnemonicAt(int,int)
*/
public int getMnemonicAt(int tabIndex) {
checkIndex(tabIndex);
Page page = pages.get(tabIndex);
return page.getMnemonic();
}
/** {@collect.stats}
* Returns the character, as an index, that the look and feel should
* provide decoration for as representing the mnemonic character.
*
* @since 1.4
* @param tabIndex the index of the tab that the mnemonic refers to
* @return index representing mnemonic character if one exists;
* otherwise returns -1
* @exception IndexOutOfBoundsException if index is out of range
* (<code>tabIndex</code> < 0 ||
* <code>tabIndex</code> >= tab count)
* @see #setDisplayedMnemonicIndexAt(int,int)
* @see #setMnemonicAt(int,int)
*/
public int getDisplayedMnemonicIndexAt(int tabIndex) {
checkIndex(tabIndex);
Page page = pages.get(tabIndex);
return page.getDisplayedMnemonicIndex();
}
/** {@collect.stats}
* Returns the tab bounds at <code>index</code>. If the tab at
* this index is not currently visible in the UI, then returns
* <code>null</code>.
* If there is no UI set on this <code>tabbedpane</code>,
* then returns <code>null</code>.
*
* @param index the index to be queried
* @return a <code>Rectangle</code> containing the tab bounds at
* <code>index</code>, or <code>null</code> if tab at
* <code>index</code> is not currently visible in the UI,
* or if there is no UI set on this <code>tabbedpane</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*/
public Rectangle getBoundsAt(int index) {
checkIndex(index);
if (ui != null) {
return ((TabbedPaneUI)ui).getTabBounds(this, index);
}
return null;
}
// Setters for the Pages
/** {@collect.stats}
* Sets the title at <code>index</code> to <code>title</code> which
* can be <code>null</code>.
* The title is not shown if a tab component for this tab was specified.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where the title should be set
* @param title the title to be displayed in the tab
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getTitleAt
* @see #setTabComponentAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The title at the specified tab index.
*/
public void setTitleAt(int index, String title) {
Page page = pages.get(index);
String oldTitle =page.title;
page.title = title;
if (oldTitle != title) {
firePropertyChange("indexForTitle", -1, index);
}
page.updateDisplayedMnemonicIndex();
if ((oldTitle != title) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldTitle, title);
}
if (title == null || oldTitle == null ||
!title.equals(oldTitle)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the icon at <code>index</code> to <code>icon</code> which can be
* <code>null</code>. This does not set disabled icon at <code>icon</code>.
* If the new Icon is different than the current Icon and disabled icon
* is not explicitly set, the LookAndFeel will be asked to generate a disabled
* Icon. To explicitly set disabled icon, use <code>setDisableIconAt()</code>.
* The icon is not shown if a tab component for this tab was specified.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where the icon should be set
* @param icon the icon to be displayed in the tab
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setDisabledIconAt
* @see #getIconAt
* @see #getDisabledIconAt
* @see #setTabComponentAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The icon at the specified tab index.
*/
public void setIconAt(int index, Icon icon) {
Page page = pages.get(index);
Icon oldIcon = page.icon;
if (icon != oldIcon) {
page.icon = icon;
/* If the default icon has really changed and we had
* generated the disabled icon for this page, then
* clear the disabledIcon field of the page.
*/
if (page.disabledIcon instanceof UIResource) {
page.disabledIcon = null;
}
// Fire the accessibility Visible data change
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldIcon, icon);
}
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the disabled icon at <code>index</code> to <code>icon</code>
* which can be <code>null</code>.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where the disabled icon should be set
* @param disabledIcon the icon to be displayed in the tab when disabled
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getDisabledIconAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The disabled icon at the specified tab index.
*/
public void setDisabledIconAt(int index, Icon disabledIcon) {
Icon oldIcon = pages.get(index).disabledIcon;
pages.get(index).disabledIcon = disabledIcon;
if (disabledIcon != oldIcon && !isEnabledAt(index)) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the tooltip text at <code>index</code> to <code>toolTipText</code>
* which can be <code>null</code>.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where the tooltip text should be set
* @param toolTipText the tooltip text to be displayed for the tab
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getToolTipTextAt
* @beaninfo
* preferred: true
* description: The tooltip text at the specified tab index.
* @since 1.3
*/
public void setToolTipTextAt(int index, String toolTipText) {
String oldToolTipText = pages.get(index).tip;
pages.get(index).tip = toolTipText;
if ((oldToolTipText != toolTipText) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
oldToolTipText, toolTipText);
}
if (!haveRegistered && toolTipText != null) {
ToolTipManager.sharedInstance().registerComponent(this);
haveRegistered = true;
}
}
/** {@collect.stats}
* Sets the background color at <code>index</code> to
* <code>background</code>
* which can be <code>null</code>, in which case the tab's background color
* will default to the background color of the <code>tabbedpane</code>.
* An internal exception is raised if there is no tab at that index.
* @param index the tab index where the background should be set
* @param background the color to be displayed in the tab's background
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getBackgroundAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The background color at the specified tab index.
*/
public void setBackgroundAt(int index, Color background) {
Color oldBg = pages.get(index).background;
pages.get(index).setBackground(background);
if (background == null || oldBg == null ||
!background.equals(oldBg)) {
Rectangle tabBounds = getBoundsAt(index);
if (tabBounds != null) {
repaint(tabBounds);
}
}
}
/** {@collect.stats}
* Sets the foreground color at <code>index</code> to
* <code>foreground</code> which can be
* <code>null</code>, in which case the tab's foreground color
* will default to the foreground color of this <code>tabbedpane</code>.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where the foreground should be set
* @param foreground the color to be displayed as the tab's foreground
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getForegroundAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The foreground color at the specified tab index.
*/
public void setForegroundAt(int index, Color foreground) {
Color oldFg = pages.get(index).foreground;
pages.get(index).setForeground(foreground);
if (foreground == null || oldFg == null ||
!foreground.equals(oldFg)) {
Rectangle tabBounds = getBoundsAt(index);
if (tabBounds != null) {
repaint(tabBounds);
}
}
}
/** {@collect.stats}
* Sets whether or not the tab at <code>index</code> is enabled.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index which should be enabled/disabled
* @param enabled whether or not the tab should be enabled
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #isEnabledAt
*/
public void setEnabledAt(int index, boolean enabled) {
boolean oldEnabled = pages.get(index).isEnabled();
pages.get(index).setEnabled(enabled);
if (enabled != oldEnabled) {
revalidate();
repaint();
}
}
/** {@collect.stats}
* Sets the component at <code>index</code> to <code>component</code>.
* An internal exception is raised if there is no tab at that index.
*
* @param index the tab index where this component is being placed
* @param component the component for the tab
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #getComponentAt
* @beaninfo
* attribute: visualUpdate true
* description: The component at the specified tab index.
*/
public void setComponentAt(int index, Component component) {
Page page = pages.get(index);
if (component != page.component) {
boolean shouldChangeFocus = false;
if (page.component != null) {
shouldChangeFocus =
(SwingUtilities.findFocusOwner(page.component) != null);
// REMIND(aim): this is really silly;
// why not if (page.component.getParent() == this) remove(component)
synchronized(getTreeLock()) {
int count = getComponentCount();
Component children[] = getComponents();
for (int i = 0; i < count; i++) {
if (children[i] == page.component) {
super.remove(i);
}
}
}
}
page.component = component;
boolean selectedPage = (getSelectedIndex() == index);
if (selectedPage) {
this.visComp = component;
}
if (component != null) {
component.setVisible(selectedPage);
addImpl(component, null, -1);
if (shouldChangeFocus) {
SwingUtilities2.tabbedPaneChangeFocusTo(component);
}
} else {
repaint();
}
revalidate();
}
}
/** {@collect.stats}
* Provides a hint to the look and feel as to which character in the
* text should be decorated to represent the mnemonic. Not all look and
* feels may support this. A value of -1 indicates either there is
* no mnemonic for this tab, or you do not wish the mnemonic to be
* displayed for this tab.
* <p>
* The value of this is updated as the properties relating to the
* mnemonic change (such as the mnemonic itself, the text...).
* You should only ever have to call this if
* you do not wish the default character to be underlined. For example, if
* the text at tab index 3 was 'Apple Price', with a mnemonic of 'p',
* and you wanted the 'P'
* to be decorated, as 'Apple <u>P</u>rice', you would have to invoke
* <code>setDisplayedMnemonicIndex(3, 6)</code> after invoking
* <code>setMnemonicAt(3, KeyEvent.VK_P)</code>.
* <p>Note that it is the programmer's responsibility to ensure
* that each tab has a unique mnemonic or unpredictable results may
* occur.
*
* @since 1.4
* @param tabIndex the index of the tab that the mnemonic refers to
* @param mnemonicIndex index into the <code>String</code> to underline
* @exception IndexOutOfBoundsException if <code>tabIndex</code> is
* out of range (<code>tabIndex < 0 || tabIndex >= tab
* count</code>)
* @exception IllegalArgumentException will be thrown if
* <code>mnemonicIndex</code> is >= length of the tab
* title , or < -1
* @see #setMnemonicAt(int,int)
* @see #getDisplayedMnemonicIndexAt(int)
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: the index into the String to draw the keyboard character
* mnemonic at
*/
public void setDisplayedMnemonicIndexAt(int tabIndex, int mnemonicIndex) {
checkIndex(tabIndex);
Page page = pages.get(tabIndex);
page.setDisplayedMnemonicIndex(mnemonicIndex);
}
/** {@collect.stats}
* Sets the keyboard mnemonic for accessing the specified tab.
* The mnemonic is the key which when combined with the look and feel's
* mouseless modifier (usually Alt) will activate the specified
* tab.
* <p>
* A mnemonic must correspond to a single key on the keyboard
* and should be specified using one of the <code>VK_XXX</code>
* keycodes defined in <code>java.awt.event.KeyEvent</code>.
* Mnemonics are case-insensitive, therefore a key event
* with the corresponding keycode would cause the button to be
* activated whether or not the Shift modifier was pressed.
* <p>
* This will update the displayed mnemonic property for the specified
* tab.
*
* @since 1.4
* @param tabIndex the index of the tab that the mnemonic refers to
* @param mnemonic the key code which represents the mnemonic
* @exception IndexOutOfBoundsException if <code>tabIndex</code> is out
* of range (<code>tabIndex < 0 || tabIndex >= tab count</code>)
* @see #getMnemonicAt(int)
* @see #setDisplayedMnemonicIndexAt(int,int)
*
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The keyboard mnenmonic, as a KeyEvent VK constant,
* for the specified tab
*/
public void setMnemonicAt(int tabIndex, int mnemonic) {
checkIndex(tabIndex);
Page page = pages.get(tabIndex);
page.setMnemonic(mnemonic);
firePropertyChange("mnemonicAt", null, null);
}
// end of Page setters
/** {@collect.stats}
* Returns the first tab index with a given <code>title</code>, or
* -1 if no tab has this title.
*
* @param title the title for the tab
* @return the first tab index which matches <code>title</code>, or
* -1 if no tab has this title
*/
public int indexOfTab(String title) {
for(int i = 0; i < getTabCount(); i++) {
if (getTitleAt(i).equals(title == null? "" : title)) {
return i;
}
}
return -1;
}
/** {@collect.stats}
* Returns the first tab index with a given <code>icon</code>,
* or -1 if no tab has this icon.
*
* @param icon the icon for the tab
* @return the first tab index which matches <code>icon</code>,
* or -1 if no tab has this icon
*/
public int indexOfTab(Icon icon) {
for(int i = 0; i < getTabCount(); i++) {
Icon tabIcon = getIconAt(i);
if ((tabIcon != null && tabIcon.equals(icon)) ||
(tabIcon == null && tabIcon == icon)) {
return i;
}
}
return -1;
}
/** {@collect.stats}
* Returns the index of the tab for the specified component.
* Returns -1 if there is no tab for this component.
*
* @param component the component for the tab
* @return the first tab which matches this component, or -1
* if there is no tab for this component
*/
public int indexOfComponent(Component component) {
for(int i = 0; i < getTabCount(); i++) {
Component c = getComponentAt(i);
if ((c != null && c.equals(component)) ||
(c == null && c == component)) {
return i;
}
}
return -1;
}
/** {@collect.stats}
* Returns the tab index corresponding to the tab whose bounds
* intersect the specified location. Returns -1 if no tab
* intersects the location.
*
* @param x the x location relative to this tabbedpane
* @param y the y location relative to this tabbedpane
* @return the tab index which intersects the location, or
* -1 if no tab intersects the location
* @since 1.4
*/
public int indexAtLocation(int x, int y) {
if (ui != null) {
return ((TabbedPaneUI)ui).tabForCoordinate(this, x, y);
}
return -1;
}
/** {@collect.stats}
* Returns the tooltip text for the component determined by the
* mouse event location.
*
* @param event the <code>MouseEvent</code> that tells where the
* cursor is lingering
* @return the <code>String</code> containing the tooltip text
*/
public String getToolTipText(MouseEvent event) {
if (ui != null) {
int index = ((TabbedPaneUI)ui).tabForCoordinate(this, event.getX(), event.getY());
if (index != -1) {
return pages.get(index).tip;
}
}
return super.getToolTipText(event);
}
private void checkIndex(int index) {
if (index < 0 || index >= pages.size()) {
throw new IndexOutOfBoundsException("Index: "+index+", Tab count: "+pages.size());
}
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/* Called from the <code>JComponent</code>'s
* <code>EnableSerializationFocusListener</code> to
* do any Swing-specific pre-serialization configuration.
*/
void compWriteObjectNotify() {
super.compWriteObjectNotify();
// If ToolTipText != null, then the tooltip has already been
// unregistered by JComponent.compWriteObjectNotify()
if (getToolTipText() == null && haveRegistered) {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
if ((ui != null) && (getUIClassID().equals(uiClassID))) {
ui.installUI(this);
}
// If ToolTipText != null, then the tooltip has already been
// registered by JComponent.readObject()
if (getToolTipText() == null && haveRegistered) {
ToolTipManager.sharedInstance().registerComponent(this);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JTabbedPane</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JTabbedPane.
*/
protected String paramString() {
String tabPlacementString;
if (tabPlacement == TOP) {
tabPlacementString = "TOP";
} else if (tabPlacement == BOTTOM) {
tabPlacementString = "BOTTOM";
} else if (tabPlacement == LEFT) {
tabPlacementString = "LEFT";
} else if (tabPlacement == RIGHT) {
tabPlacementString = "RIGHT";
} else tabPlacementString = "";
String haveRegisteredString = (haveRegistered ?
"true" : "false");
return super.paramString() +
",haveRegistered=" + haveRegisteredString +
",tabPlacement=" + tabPlacementString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JTabbedPane.
* For tabbed panes, the AccessibleContext takes the form of an
* AccessibleJTabbedPane.
* A new AccessibleJTabbedPane instance is created if necessary.
*
* @return an AccessibleJTabbedPane that serves as the
* AccessibleContext of this JTabbedPane
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTabbedPane();
// initialize AccessibleContext for the existing pages
int count = getTabCount();
for (int i = 0; i < count; i++) {
pages.get(i).initAccessibleContext();
}
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTabbedPane</code> class. It provides an implementation of the
* Java Accessibility API appropriate to tabbed pane user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJTabbedPane extends AccessibleJComponent
implements AccessibleSelection, ChangeListener {
/** {@collect.stats}
* Returns the accessible name of this object, or {@code null} if
* there is no accessible name.
*
* @return the accessible name of this object, nor {@code null}.
* @since 1.6
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
}
String cp = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
if (cp != null) {
return cp;
}
int index = getSelectedIndex();
if (index >= 0) {
return pages.get(index).getAccessibleName();
}
return super.getAccessibleName();
}
/** {@collect.stats}
* Constructs an AccessibleJTabbedPane
*/
public AccessibleJTabbedPane() {
super();
JTabbedPane.this.model.addChangeListener(this);
}
public void stateChanged(ChangeEvent e) {
Object o = e.getSource();
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
null, o);
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of
* the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PAGE_TAB_LIST;
}
/** {@collect.stats}
* Returns the number of accessible children in the object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return getTabCount();
}
/** {@collect.stats}
* Return the specified Accessible child of the object.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @exception IllegalArgumentException if index is out of bounds
*/
public Accessible getAccessibleChild(int i) {
if (i < 0 || i >= getTabCount()) {
return null;
}
return pages.get(i);
}
/** {@collect.stats}
* Gets the <code>AccessibleSelection</code> associated with
* this object. In the implementation of the Java
* Accessibility API for this class,
* returns this object, which is responsible for implementing the
* <code>AccessibleSelection</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child contained at
* the local coordinate <code>Point</code>, if one exists.
* Otherwise returns the currently selected tab.
*
* @return the <code>Accessible</code> at the specified
* location, if it exists
*/
public Accessible getAccessibleAt(Point p) {
int tab = ((TabbedPaneUI) ui).tabForCoordinate(JTabbedPane.this,
p.x, p.y);
if (tab == -1) {
tab = getSelectedIndex();
}
return getAccessibleChild(tab);
}
public int getAccessibleSelectionCount() {
return 1;
}
public Accessible getAccessibleSelection(int i) {
int index = getSelectedIndex();
if (index == -1) {
return null;
}
return pages.get(index);
}
public boolean isAccessibleChildSelected(int i) {
return (i == getSelectedIndex());
}
public void addAccessibleSelection(int i) {
setSelectedIndex(i);
}
public void removeAccessibleSelection(int i) {
// can't do
}
public void clearAccessibleSelection() {
// can't do
}
public void selectAllAccessibleSelection() {
// can't do
}
}
private class Page extends AccessibleContext
implements Serializable, Accessible, AccessibleComponent {
String title;
Color background;
Color foreground;
Icon icon;
Icon disabledIcon;
JTabbedPane parent;
Component component;
String tip;
boolean enabled = true;
boolean needsUIUpdate;
int mnemonic = -1;
int mnemonicIndex = -1;
Component tabComponent;
Page(JTabbedPane parent,
String title, Icon icon, Icon disabledIcon, Component component, String tip) {
this.title = title;
this.icon = icon;
this.disabledIcon = disabledIcon;
this.parent = parent;
this.setAccessibleParent(parent);
this.component = component;
this.tip = tip;
initAccessibleContext();
}
/*
* initializes the AccessibleContext for the page
*/
void initAccessibleContext() {
if (JTabbedPane.this.accessibleContext != null &&
component instanceof Accessible) {
/*
* Do initialization if the AccessibleJTabbedPane
* has been instantiated. We do not want to load
* Accessibility classes unnecessarily.
*/
AccessibleContext ac;
ac = ((Accessible) component).getAccessibleContext();
if (ac != null) {
ac.setAccessibleParent(this);
}
}
}
void setMnemonic(int mnemonic) {
this.mnemonic = mnemonic;
updateDisplayedMnemonicIndex();
}
int getMnemonic() {
return mnemonic;
}
/*
* Sets the page displayed mnemonic index
*/
void setDisplayedMnemonicIndex(int mnemonicIndex) {
if (this.mnemonicIndex != mnemonicIndex) {
if (mnemonicIndex != -1 && (title == null ||
mnemonicIndex < 0 ||
mnemonicIndex >= title.length())) {
throw new IllegalArgumentException(
"Invalid mnemonic index: " + mnemonicIndex);
}
this.mnemonicIndex = mnemonicIndex;
JTabbedPane.this.firePropertyChange("displayedMnemonicIndexAt",
null, null);
}
}
/*
* Returns the page displayed mnemonic index
*/
int getDisplayedMnemonicIndex() {
return this.mnemonicIndex;
}
void updateDisplayedMnemonicIndex() {
setDisplayedMnemonicIndex(
SwingUtilities.findDisplayedMnemonicIndex(title, mnemonic));
}
/////////////////
// Accessibility support
////////////////
public AccessibleContext getAccessibleContext() {
return this;
}
// AccessibleContext methods
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else if (title != null) {
return title;
}
return null;
}
public String getAccessibleDescription() {
if (accessibleDescription != null) {
return accessibleDescription;
} else if (tip != null) {
return tip;
}
return null;
}
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PAGE_TAB;
}
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states;
states = parent.getAccessibleContext().getAccessibleStateSet();
states.add(AccessibleState.SELECTABLE);
int i = parent.indexOfTab(title);
if (i == parent.getSelectedIndex()) {
states.add(AccessibleState.SELECTED);
}
return states;
}
public int getAccessibleIndexInParent() {
return parent.indexOfTab(title);
}
public int getAccessibleChildrenCount() {
if (component instanceof Accessible) {
return 1;
} else {
return 0;
}
}
public Accessible getAccessibleChild(int i) {
if (component instanceof Accessible) {
return (Accessible) component;
} else {
return null;
}
}
public Locale getLocale() {
return parent.getLocale();
}
public AccessibleComponent getAccessibleComponent() {
return this;
}
// AccessibleComponent methods
public Color getBackground() {
return background != null? background : parent.getBackground();
}
public void setBackground(Color c) {
background = c;
}
public Color getForeground() {
return foreground != null? foreground : parent.getForeground();
}
public void setForeground(Color c) {
foreground = c;
}
public Cursor getCursor() {
return parent.getCursor();
}
public void setCursor(Cursor c) {
parent.setCursor(c);
}
public Font getFont() {
return parent.getFont();
}
public void setFont(Font f) {
parent.setFont(f);
}
public FontMetrics getFontMetrics(Font f) {
return parent.getFontMetrics(f);
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean b) {
enabled = b;
}
public boolean isVisible() {
return parent.isVisible();
}
public void setVisible(boolean b) {
parent.setVisible(b);
}
public boolean isShowing() {
return parent.isShowing();
}
public boolean contains(Point p) {
Rectangle r = getBounds();
return r.contains(p);
}
public Point getLocationOnScreen() {
Point parentLocation = parent.getLocationOnScreen();
Point componentLocation = getLocation();
componentLocation.translate(parentLocation.x, parentLocation.y);
return componentLocation;
}
public Point getLocation() {
Rectangle r = getBounds();
return new Point(r.x, r.y);
}
public void setLocation(Point p) {
// do nothing
}
public Rectangle getBounds() {
return parent.getUI().getTabBounds(parent,
parent.indexOfTab(title));
}
public void setBounds(Rectangle r) {
// do nothing
}
public Dimension getSize() {
Rectangle r = getBounds();
return new Dimension(r.width, r.height);
}
public void setSize(Dimension d) {
// do nothing
}
public Accessible getAccessibleAt(Point p) {
if (component instanceof Accessible) {
return (Accessible) component;
} else {
return null;
}
}
public boolean isFocusTraversable() {
return false;
}
public void requestFocus() {
// do nothing
}
public void addFocusListener(FocusListener l) {
// do nothing
}
public void removeFocusListener(FocusListener l) {
// do nothing
}
// TIGER - 4732339
/** {@collect.stats}
* Returns an AccessibleIcon
*
* @return the enabled icon if one exists and the page
* is enabled. Otherwise, returns the disabled icon if
* one exists and the page is disabled. Otherwise, null
* is returned.
*/
public AccessibleIcon [] getAccessibleIcon() {
AccessibleIcon accessibleIcon = null;
if (enabled && icon instanceof ImageIcon) {
AccessibleContext ac =
((ImageIcon)icon).getAccessibleContext();
accessibleIcon = (AccessibleIcon)ac;
} else if (!enabled && disabledIcon instanceof ImageIcon) {
AccessibleContext ac =
((ImageIcon)disabledIcon).getAccessibleContext();
accessibleIcon = (AccessibleIcon)ac;
}
if (accessibleIcon != null) {
AccessibleIcon [] returnIcons = new AccessibleIcon[1];
returnIcons[0] = accessibleIcon;
return returnIcons;
} else {
return null;
}
}
}
/** {@collect.stats}
* Sets the component that is responsible for rendering the
* title for the specified tab. A null value means
* <code>JTabbedPane</code> will render the title and/or icon for
* the specified tab. A non-null value means the component will
* render the title and <code>JTabbedPane</code> will not render
* the title and/or icon.
* <p>
* Note: The component must not be one that the developer has
* already added to the tabbed pane.
*
* @param index the tab index where the component should be set
* @param component the component to render the title for the
* specified tab
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
* @exception IllegalArgumentException if component has already been
* added to this <code>JTabbedPane</code>
*
* @see #getTabComponentAt
* @beaninfo
* preferred: true
* attribute: visualUpdate true
* description: The tab component at the specified tab index.
* @since 1.6
*/
public void setTabComponentAt(int index, Component component) {
if (component != null && indexOfComponent(component) != -1) {
throw new IllegalArgumentException("Component is already added to this JTabbedPane");
}
Component oldValue = getTabComponentAt(index);
if (component != oldValue) {
int tabComponentIndex = indexOfTabComponent(component);
if (tabComponentIndex != -1) {
setTabComponentAt(tabComponentIndex, null);
}
pages.get(index).tabComponent = component;
firePropertyChange("indexForTabComponent", -1, index);
}
}
/** {@collect.stats}
* Returns the tab component at <code>index</code>.
*
* @param index the index of the item being queried
* @return the tab component at <code>index</code>
* @exception IndexOutOfBoundsException if index is out of range
* (index < 0 || index >= tab count)
*
* @see #setTabComponentAt
* @since 1.6
*/
public Component getTabComponentAt(int index) {
return pages.get(index).tabComponent;
}
/** {@collect.stats}
* Returns the index of the tab for the specified tab component.
* Returns -1 if there is no tab for this tab component.
*
* @param tabComponent the tab component for the tab
* @return the first tab which matches this tab component, or -1
* if there is no tab for this tab component
* @see #setTabComponentAt
* @see #getTabComponentAt
* @since 1.6
*/
public int indexOfTabComponent(Component tabComponent) {
for(int i = 0; i < getTabCount(); i++) {
Component c = getTabComponentAt(i);
if (c == tabComponent) {
return i;
}
}
return -1;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.lang.Integer;
import java.awt.Color;
import java.awt.Component;
import java.io.Serializable;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/** {@collect.stats}
* A <code>TableColumn</code> represents all the attributes of a column in a
* <code>JTable</code>, such as width, resizibility, minimum and maximum width.
* In addition, the <code>TableColumn</code> provides slots for a renderer and
* an editor that can be used to display and edit the values in this column.
* <p>
* It is also possible to specify renderers and editors on a per type basis
* rather than a per column basis - see the
* <code>setDefaultRenderer</code> method in the <code>JTable</code> class.
* This default mechanism is only used when the renderer (or
* editor) in the <code>TableColumn</code> is <code>null</code>.
* <p>
* The <code>TableColumn</code> stores the link between the columns in the
* <code>JTable</code> and the columns in the <code>TableModel</code>.
* The <code>modelIndex</code> is the column in the
* <code>TableModel</code>, which will be queried for the data values for the
* cells in this column. As the column moves around in the view this
* <code>modelIndex</code> does not change.
* <p>
* <b>Note:</b> Some implementations may assume that all
* <code>TableColumnModel</code>s are unique, therefore we would
* recommend that the same <code>TableColumn</code> instance
* not be added more than once to a <code>TableColumnModel</code>.
* To show <code>TableColumn</code>s with the same column of
* data from the model, create a new instance with the same
* <code>modelIndex</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
* @see javax.swing.table.TableColumnModel
*
* @see javax.swing.table.DefaultTableColumnModel
* @see javax.swing.table.JTableHeader#getDefaultRenderer()
* @see JTable#getDefaultRenderer(Class)
* @see JTable#getDefaultEditor(Class)
* @see JTable#getCellRenderer(int, int)
* @see JTable#getCellEditor(int, int)
*/
public class TableColumn extends Object implements Serializable {
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use string literals to identify
* properties.
*/
/*
* Warning: The value of this constant, "columWidth" is wrong as the
* name of the property is "columnWidth".
*/
public final static String COLUMN_WIDTH_PROPERTY = "columWidth";
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use string literals to identify
* properties.
*/
public final static String HEADER_VALUE_PROPERTY = "headerValue";
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use string literals to identify
* properties.
*/
public final static String HEADER_RENDERER_PROPERTY = "headerRenderer";
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use string literals to identify
* properties.
*/
public final static String CELL_RENDERER_PROPERTY = "cellRenderer";
//
// Instance Variables
//
/** {@collect.stats}
* The index of the column in the model which is to be displayed by
* this <code>TableColumn</code>. As columns are moved around in the
* view <code>modelIndex</code> remains constant.
*/
protected int modelIndex;
/** {@collect.stats}
* This object is not used internally by the drawing machinery of
* the <code>JTable</code>; identifiers may be set in the
* <code>TableColumn</code> as as an
* optional way to tag and locate table columns. The table package does
* not modify or invoke any methods in these identifier objects other
* than the <code>equals</code> method which is used in the
* <code>getColumnIndex()</code> method in the
* <code>DefaultTableColumnModel</code>.
*/
protected Object identifier;
/** {@collect.stats} The width of the column. */
protected int width;
/** {@collect.stats} The minimum width of the column. */
protected int minWidth;
/** {@collect.stats} The preferred width of the column. */
private int preferredWidth;
/** {@collect.stats} The maximum width of the column. */
protected int maxWidth;
/** {@collect.stats} The renderer used to draw the header of the column. */
protected TableCellRenderer headerRenderer;
/** {@collect.stats} The header value of the column. */
protected Object headerValue;
/** {@collect.stats} The renderer used to draw the data cells of the column. */
protected TableCellRenderer cellRenderer;
/** {@collect.stats} The editor used to edit the data cells of the column. */
protected TableCellEditor cellEditor;
/** {@collect.stats} If true, the user is allowed to resize the column; the default is true. */
protected boolean isResizable;
/** {@collect.stats}
* This field was not used in previous releases and there are
* currently no plans to support it in the future.
*
* @deprecated as of Java 2 platform v1.3
*/
/*
* Counter used to disable posting of resizing notifications until the
* end of the resize.
*/
@Deprecated
transient protected int resizedPostingDisableCount;
/** {@collect.stats}
* If any <code>PropertyChangeListeners</code> have been registered, the
* <code>changeSupport</code> field describes them.
*/
private SwingPropertyChangeSupport changeSupport;
//
// Constructors
//
/** {@collect.stats}
* Cover method, using a default model index of 0,
* default width of 75, a <code>null</code> renderer and a
* <code>null</code> editor.
* This method is intended for serialization.
* @see #TableColumn(int, int, TableCellRenderer, TableCellEditor)
*/
public TableColumn() {
this(0);
}
/** {@collect.stats}
* Cover method, using a default width of 75, a <code>null</code>
* renderer and a <code>null</code> editor.
* @see #TableColumn(int, int, TableCellRenderer, TableCellEditor)
*/
public TableColumn(int modelIndex) {
this(modelIndex, 75, null, null);
}
/** {@collect.stats}
* Cover method, using a <code>null</code> renderer and a
* <code>null</code> editor.
* @see #TableColumn(int, int, TableCellRenderer, TableCellEditor)
*/
public TableColumn(int modelIndex, int width) {
this(modelIndex, width, null, null);
}
/** {@collect.stats}
* Creates and initializes an instance of
* <code>TableColumn</code> with the specified model index,
* width, cell renderer, and cell editor;
* all <code>TableColumn</code> constructors delegate to this one.
* The value of <code>width</code> is used
* for both the initial and preferred width;
* if <code>width</code> is negative,
* they're set to 0.
* The minimum width is set to 15 unless the initial width is less,
* in which case the minimum width is set to
* the initial width.
*
* <p>
* When the <code>cellRenderer</code>
* or <code>cellEditor</code> parameter is <code>null</code>,
* a default value provided by the <code>JTable</code>
* <code>getDefaultRenderer</code>
* or <code>getDefaultEditor</code> method, respectively,
* is used to
* provide defaults based on the type of the data in this column.
* This column-centric rendering strategy can be circumvented by overriding
* the <code>getCellRenderer</code> methods in <code>JTable</code>.
*
* @param modelIndex the index of the column
* in the model that supplies the data for this column in the table;
* the model index remains the same
* even when columns are reordered in the view
* @param width this column's preferred width and initial width
* @param cellRenderer the object used to render values in this column
* @param cellEditor the object used to edit values in this column
* @see #getMinWidth()
* @see JTable#getDefaultRenderer(Class)
* @see JTable#getDefaultEditor(Class)
* @see JTable#getCellRenderer(int, int)
* @see JTable#getCellEditor(int, int)
*/
public TableColumn(int modelIndex, int width,
TableCellRenderer cellRenderer,
TableCellEditor cellEditor) {
super();
this.modelIndex = modelIndex;
preferredWidth = this.width = Math.max(width, 0);
this.cellRenderer = cellRenderer;
this.cellEditor = cellEditor;
// Set other instance variables to default values.
minWidth = Math.min(15, this.width);
maxWidth = Integer.MAX_VALUE;
isResizable = true;
resizedPostingDisableCount = 0;
headerValue = null;
}
//
// Modifying and Querying attributes
//
private void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (changeSupport != null) {
changeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
private void firePropertyChange(String propertyName, int oldValue, int newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, new Integer(oldValue), new Integer(newValue));
}
}
private void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
}
/** {@collect.stats}
* Sets the model index for this column. The model index is the
* index of the column in the model that will be displayed by this
* <code>TableColumn</code>. As the <code>TableColumn</code>
* is moved around in the view the model index remains constant.
* @param modelIndex the new modelIndex
* @beaninfo
* bound: true
* description: The model index.
*/
public void setModelIndex(int modelIndex) {
int old = this.modelIndex;
this.modelIndex = modelIndex;
firePropertyChange("modelIndex", old, modelIndex);
}
/** {@collect.stats}
* Returns the model index for this column.
* @return the <code>modelIndex</code> property
*/
public int getModelIndex() {
return modelIndex;
}
/** {@collect.stats}
* Sets the <code>TableColumn</code>'s identifier to
* <code>anIdentifier</code>. <p>
* Note: identifiers are not used by the <code>JTable</code>,
* they are purely a
* convenience for the external tagging and location of columns.
*
* @param identifier an identifier for this column
* @see #getIdentifier
* @beaninfo
* bound: true
* description: A unique identifier for this column.
*/
public void setIdentifier(Object identifier) {
Object old = this.identifier;
this.identifier = identifier;
firePropertyChange("identifier", old, identifier);
}
/** {@collect.stats}
* Returns the <code>identifier</code> object for this column.
* Note identifiers are not used by <code>JTable</code>,
* they are purely a convenience for external use.
* If the <code>identifier</code> is <code>null</code>,
* <code>getIdentifier()</code> returns <code>getHeaderValue</code>
* as a default.
*
* @return the <code>identifier</code> property
* @see #setIdentifier
*/
public Object getIdentifier() {
return (identifier != null) ? identifier : getHeaderValue();
}
/** {@collect.stats}
* Sets the <code>Object</code> whose string representation will be
* used as the value for the <code>headerRenderer</code>. When the
* <code>TableColumn</code> is created, the default <code>headerValue</code>
* is <code>null</code>.
* @param headerValue the new headerValue
* @see #getHeaderValue
* @beaninfo
* bound: true
* description: The text to be used by the header renderer.
*/
public void setHeaderValue(Object headerValue) {
Object old = this.headerValue;
this.headerValue = headerValue;
firePropertyChange("headerValue", old, headerValue);
}
/** {@collect.stats}
* Returns the <code>Object</code> used as the value for the header
* renderer.
*
* @return the <code>headerValue</code> property
* @see #setHeaderValue
*/
public Object getHeaderValue() {
return headerValue;
}
//
// Renderers and Editors
//
/** {@collect.stats}
* Sets the <code>TableCellRenderer</code> used to draw the
* <code>TableColumn</code>'s header to <code>headerRenderer</code>.
* <p>
* It is the header renderers responsibility to render the sorting
* indicator. If you are using sorting and specify a renderer your
* renderer must render the sorting indication.
*
* @param headerRenderer the new headerRenderer
*
* @see #getHeaderRenderer
* @beaninfo
* bound: true
* description: The header renderer.
*/
public void setHeaderRenderer(TableCellRenderer headerRenderer) {
TableCellRenderer old = this.headerRenderer;
this.headerRenderer = headerRenderer;
firePropertyChange("headerRenderer", old, headerRenderer);
}
/** {@collect.stats}
* Returns the <code>TableCellRenderer</code> used to draw the header of the
* <code>TableColumn</code>. When the <code>headerRenderer</code> is
* <code>null</code>, the <code>JTableHeader</code>
* uses its <code>defaultRenderer</code>. The default value for a
* <code>headerRenderer</code> is <code>null</code>.
*
* @return the <code>headerRenderer</code> property
* @see #setHeaderRenderer
* @see #setHeaderValue
* @see javax.swing.table.JTableHeader#getDefaultRenderer()
*/
public TableCellRenderer getHeaderRenderer() {
return headerRenderer;
}
/** {@collect.stats}
* Sets the <code>TableCellRenderer</code> used by <code>JTable</code>
* to draw individual values for this column.
*
* @param cellRenderer the new cellRenderer
* @see #getCellRenderer
* @beaninfo
* bound: true
* description: The renderer to use for cell values.
*/
public void setCellRenderer(TableCellRenderer cellRenderer) {
TableCellRenderer old = this.cellRenderer;
this.cellRenderer = cellRenderer;
firePropertyChange("cellRenderer", old, cellRenderer);
}
/** {@collect.stats}
* Returns the <code>TableCellRenderer</code> used by the
* <code>JTable</code> to draw
* values for this column. The <code>cellRenderer</code> of the column
* not only controls the visual look for the column, but is also used to
* interpret the value object supplied by the <code>TableModel</code>.
* When the <code>cellRenderer</code> is <code>null</code>,
* the <code>JTable</code> uses a default renderer based on the
* class of the cells in that column. The default value for a
* <code>cellRenderer</code> is <code>null</code>.
*
* @return the <code>cellRenderer</code> property
* @see #setCellRenderer
* @see JTable#setDefaultRenderer
*/
public TableCellRenderer getCellRenderer() {
return cellRenderer;
}
/** {@collect.stats}
* Sets the editor to used by when a cell in this column is edited.
*
* @param cellEditor the new cellEditor
* @see #getCellEditor
* @beaninfo
* bound: true
* description: The editor to use for cell values.
*/
public void setCellEditor(TableCellEditor cellEditor){
TableCellEditor old = this.cellEditor;
this.cellEditor = cellEditor;
firePropertyChange("cellEditor", old, cellEditor);
}
/** {@collect.stats}
* Returns the <code>TableCellEditor</code> used by the
* <code>JTable</code> to edit values for this column. When the
* <code>cellEditor</code> is <code>null</code>, the <code>JTable</code>
* uses a default editor based on the
* class of the cells in that column. The default value for a
* <code>cellEditor</code> is <code>null</code>.
*
* @return the <code>cellEditor</code> property
* @see #setCellEditor
* @see JTable#setDefaultEditor
*/
public TableCellEditor getCellEditor() {
return cellEditor;
}
/** {@collect.stats}
* This method should not be used to set the widths of columns in the
* <code>JTable</code>, use <code>setPreferredWidth</code> instead.
* Like a layout manager in the
* AWT, the <code>JTable</code> adjusts a column's width automatically
* whenever the
* table itself changes size, or a column's preferred width is changed.
* Setting widths programmatically therefore has no long term effect.
* <p>
* This method sets this column's width to <code>width</code>.
* If <code>width</code> exceeds the minimum or maximum width,
* it is adjusted to the appropriate limiting value.
* @param width the new width
* @see #getWidth
* @see #setMinWidth
* @see #setMaxWidth
* @see #setPreferredWidth
* @see JTable#doLayout()
* @beaninfo
* bound: true
* description: The width of the column.
*/
public void setWidth(int width) {
int old = this.width;
this.width = Math.min(Math.max(width, minWidth), maxWidth);
firePropertyChange("width", old, this.width);
}
/** {@collect.stats}
* Returns the width of the <code>TableColumn</code>. The default width is
* 75.
*
* @return the <code>width</code> property
* @see #setWidth
*/
public int getWidth() {
return width;
}
/** {@collect.stats}
* Sets this column's preferred width to <code>preferredWidth</code>.
* If <code>preferredWidth</code> exceeds the minimum or maximum width,
* it is adjusted to the appropriate limiting value.
* <p>
* For details on how the widths of columns in the <code>JTable</code>
* (and <code>JTableHeader</code>) are calculated from the
* <code>preferredWidth</code>,
* see the <code>doLayout</code> method in <code>JTable</code>.
*
* @param preferredWidth the new preferred width
* @see #getPreferredWidth
* @see JTable#doLayout()
* @beaninfo
* bound: true
* description: The preferred width of the column.
*/
public void setPreferredWidth(int preferredWidth) {
int old = this.preferredWidth;
this.preferredWidth = Math.min(Math.max(preferredWidth, minWidth), maxWidth);
firePropertyChange("preferredWidth", old, this.preferredWidth);
}
/** {@collect.stats}
* Returns the preferred width of the <code>TableColumn</code>.
* The default preferred width is 75.
*
* @return the <code>preferredWidth</code> property
* @see #setPreferredWidth
*/
public int getPreferredWidth() {
return preferredWidth;
}
/** {@collect.stats}
* Sets the <code>TableColumn</code>'s minimum width to
* <code>minWidth</code>,
* adjusting the new minimum width if necessary to ensure that
* 0 <= <code>minWidth</code> <= <code>maxWidth</code>.
* For example, if the <code>minWidth</code> argument is negative,
* this method sets the <code>minWidth</code> property to 0.
*
* <p>
* If the value of the
* <code>width</code> or <code>preferredWidth</code> property
* is less than the new minimum width,
* this method sets that property to the new minimum width.
*
* @param minWidth the new minimum width
* @see #getMinWidth
* @see #setPreferredWidth
* @see #setMaxWidth
* @beaninfo
* bound: true
* description: The minimum width of the column.
*/
public void setMinWidth(int minWidth) {
int old = this.minWidth;
this.minWidth = Math.max(Math.min(minWidth, maxWidth), 0);
if (width < this.minWidth) {
setWidth(this.minWidth);
}
if (preferredWidth < this.minWidth) {
setPreferredWidth(this.minWidth);
}
firePropertyChange("minWidth", old, this.minWidth);
}
/** {@collect.stats}
* Returns the minimum width for the <code>TableColumn</code>. The
* <code>TableColumn</code>'s width can't be made less than this either
* by the user or programmatically.
*
* @return the <code>minWidth</code> property
* @see #setMinWidth
* @see #TableColumn(int, int, TableCellRenderer, TableCellEditor)
*/
public int getMinWidth() {
return minWidth;
}
/** {@collect.stats}
* Sets the <code>TableColumn</code>'s maximum width to
* <code>maxWidth</code> or,
* if <code>maxWidth</code> is less than the minimum width,
* to the minimum width.
*
* <p>
* If the value of the
* <code>width</code> or <code>preferredWidth</code> property
* is more than the new maximum width,
* this method sets that property to the new maximum width.
*
* @param maxWidth the new maximum width
* @see #getMaxWidth
* @see #setPreferredWidth
* @see #setMinWidth
* @beaninfo
* bound: true
* description: The maximum width of the column.
*/
public void setMaxWidth(int maxWidth) {
int old = this.maxWidth;
this.maxWidth = Math.max(minWidth, maxWidth);
if (width > this.maxWidth) {
setWidth(this.maxWidth);
}
if (preferredWidth > this.maxWidth) {
setPreferredWidth(this.maxWidth);
}
firePropertyChange("maxWidth", old, this.maxWidth);
}
/** {@collect.stats}
* Returns the maximum width for the <code>TableColumn</code>. The
* <code>TableColumn</code>'s width can't be made larger than this
* either by the user or programmatically. The default maxWidth
* is Integer.MAX_VALUE.
*
* @return the <code>maxWidth</code> property
* @see #setMaxWidth
*/
public int getMaxWidth() {
return maxWidth;
}
/** {@collect.stats}
* Sets whether this column can be resized.
*
* @param isResizable if true, resizing is allowed; otherwise false
* @see #getResizable
* @beaninfo
* bound: true
* description: Whether or not this column can be resized.
*/
public void setResizable(boolean isResizable) {
boolean old = this.isResizable;
this.isResizable = isResizable;
firePropertyChange("isResizable", old, this.isResizable);
}
/** {@collect.stats}
* Returns true if the user is allowed to resize the
* <code>TableColumn</code>'s
* width, false otherwise. You can change the width programmatically
* regardless of this setting. The default is true.
*
* @return the <code>isResizable</code> property
* @see #setResizable
*/
public boolean getResizable() {
return isResizable;
}
/** {@collect.stats}
* Resizes the <code>TableColumn</code> to fit the width of its header cell.
* This method does nothing if the header renderer is <code>null</code>
* (the default case). Otherwise, it sets the minimum, maximum and preferred
* widths of this column to the widths of the minimum, maximum and preferred
* sizes of the Component delivered by the header renderer.
* The transient "width" property of this TableColumn is also set to the
* preferred width. Note this method is not used internally by the table
* package.
*
* @see #setPreferredWidth
*/
public void sizeWidthToFit() {
if (headerRenderer == null) {
return;
}
Component c = headerRenderer.getTableCellRendererComponent(null,
getHeaderValue(), false, false, 0, 0);
setMinWidth(c.getMinimumSize().width);
setMaxWidth(c.getMaximumSize().width);
setPreferredWidth(c.getPreferredSize().width);
setWidth(getPreferredWidth());
}
/** {@collect.stats}
* This field was not used in previous releases and there are
* currently no plans to support it in the future.
*
* @deprecated as of Java 2 platform v1.3
*/
@Deprecated
public void disableResizedPosting() {
resizedPostingDisableCount++;
}
/** {@collect.stats}
* This field was not used in previous releases and there are
* currently no plans to support it in the future.
*
* @deprecated as of Java 2 platform v1.3
*/
@Deprecated
public void enableResizedPosting() {
resizedPostingDisableCount--;
}
//
// Property Change Support
//
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
* <p>
* A <code>PropertyChangeEvent</code> will get fired in response to an
* explicit call to <code>setFont</code>, <code>setBackground</code>,
* or <code>setForeground</code> on the
* current component. Note that if the current component is
* inheriting its foreground, background, or font from its
* container, then no event will be fired in response to a
* change in the inherited property.
*
* @param listener the listener to be added
*
*/
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the listener list.
* The <code>PropertyChangeListener</code> to be removed was registered
* for all properties.
*
* @param listener the listener to be removed
*
*/
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
/** {@collect.stats}
* Returns an array of all the <code>PropertyChangeListener</code>s added
* to this TableColumn with addPropertyChangeListener().
*
* @return all of the <code>PropertyChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners();
}
//
// Protected Methods
//
/** {@collect.stats}
* As of Java 2 platform v1.3, this method is not called by the <code>TableColumn</code>
* constructor. Previously this method was used by the
* <code>TableColumn</code> to create a default header renderer.
* As of Java 2 platform v1.3, the default header renderer is <code>null</code>.
* <code>JTableHeader</code> now provides its own shared default
* renderer, just as the <code>JTable</code> does for its cell renderers.
*
* @return the default header renderer
* @see javax.swing.table.JTableHeader#createDefaultRenderer()
*/
protected TableCellRenderer createDefaultHeaderRenderer() {
DefaultTableCellRenderer label = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
}
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
}
};
label.setHorizontalAlignment(JLabel.CENTER);
return label;
}
} // End of class TableColumn
|
Java
|
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import java.text.Collator;
import java.util.*;
import javax.swing.DefaultRowSorter;
import javax.swing.RowFilter;
import javax.swing.SortOrder;
/** {@collect.stats}
* An implementation of <code>RowSorter</code> that provides sorting
* and filtering using a <code>TableModel</code>.
* The following example shows adding sorting to a <code>JTable</code>:
* <pre>
* TableModel myModel = createMyTableModel();
* JTable table = new JTable(myModel);
* table.setRowSorter(new TableRowSorter(myModel));
* </pre>
* This will do all the wiring such that when the user does the appropriate
* gesture, such as clicking on the column header, the table will
* visually sort.
* <p>
* <code>JTable</code>'s row-based methods and <code>JTable</code>'s
* selection model refer to the view and not the underlying
* model. Therefore, it is necessary to convert between the two. For
* example, to get the selection in terms of <code>myModel</code>
* you need to convert the indices:
* <pre>
* int[] selection = table.getSelectedRows();
* for (int i = 0; i < selection.length; i++) {
* selection[i] = table.convertRowIndexToModel(selection[i]);
* }
* </pre>
* Similarly to select a row in <code>JTable</code> based on
* a coordinate from the underlying model do the inverse:
* <pre>
* table.setRowSelectionInterval(table.convertRowIndexToView(row),
* table.convertRowIndexToView(row));
* </pre>
* <p>
* The previous example assumes you have not enabled filtering. If you
* have enabled filtering <code>convertRowIndexToView</code> will return
* -1 for locations that are not visible in the view.
* <p>
* <code>TableRowSorter</code> uses <code>Comparator</code>s for doing
* comparisons. The following defines how a <code>Comparator</code> is
* chosen for a column:
* <ol>
* <li>If a <code>Comparator</code> has been specified for the column by the
* <code>setComparator</code> method, use it.
* <li>If the column class as returned by <code>getColumnClass</code> is
* <code>String</code>, use the <code>Comparator</code> returned by
* <code>Collator.getInstance()</code>.
* <li>If the column class implements <code>Comparable</code>, use a
* <code>Comparator</code> that invokes the <code>compareTo</code>
* method.
* <li>If a <code>TableStringConverter</code> has been specified, use it
* to convert the values to <code>String</code>s and then use the
* <code>Comparator</code> returned by <code>Collator.getInstance()</code>.
* <li>Otherwise use the <code>Comparator</code> returned by
* <code>Collator.getInstance()</code> on the results from
* calling <code>toString</code> on the objects.
* </ol>
* <p>
* In addition to sorting <code>TableRowSorter</code> provides the ability
* to filter. A filter is specified using the <code>setFilter</code>
* method. The following example will only show rows containing the string
* "foo":
* <pre>
* TableModel myModel = createMyTableModel();
* TableRowSorter sorter = new TableRowSorter(myModel);
* sorter.setRowFilter(RowFilter.regexFilter(".*foo.*"));
* JTable table = new JTable(myModel);
* table.setRowSorter(sorter);
* </pre>
* <p>
* If the underlying model structure changes (the
* <code>modelStructureChanged</code> method is invoked) the following
* are reset to their default values: <code>Comparator</code>s by
* column, current sort order, and whether each column is sortable. The default
* sort order is natural (the same as the model), and columns are
* sortable by default.
* <p>
* <code>TableRowSorter</code> has one formal type parameter: the type
* of the model. Passing in a type that corresponds exactly to your
* model allows you to filter based on your model without casting.
* Refer to the documentation of <code>RowFilter</code> for an example
* of this.
* <p>
* <b>WARNING:</b> <code>DefaultTableModel</code> returns a column
* class of <code>Object</code>. As such all comparisons will
* be done using <code>toString</code>. This may be unnecessarily
* expensive. If the column only contains one type of value, such as
* an <code>Integer</code>, you should override <code>getColumnClass</code> and
* return the appropriate <code>Class</code>. This will dramatically
* increase the performance of this class.
*
* @param <M> the type of the model, which must be an implementation of
* <code>TableModel</code>
* @see javax.swing.JTable
* @see javax.swing.RowFilter
* @see javax.swing.table.DefaultTableModel
* @see java.text.Collator
* @see java.util.Comparator
* @since 1.6
*/
public class TableRowSorter<M extends TableModel> extends DefaultRowSorter<M, Integer> {
/** {@collect.stats}
* Comparator that uses compareTo on the contents.
*/
private static final Comparator COMPARABLE_COMPARATOR =
new ComparableComparator();
/** {@collect.stats}
* Underlying model.
*/
private M tableModel;
/** {@collect.stats}
* For toString conversions.
*/
private TableStringConverter stringConverter;
/** {@collect.stats}
* Creates a <code>TableRowSorter</code> with an empty model.
*/
public TableRowSorter() {
this(null);
}
/** {@collect.stats}
* Creates a <code>TableRowSorter</code> using <code>model</code>
* as the underlying <code>TableModel</code>.
*
* @param model the underlying <code>TableModel</code> to use,
* <code>null</code> is treated as an empty model
*/
public TableRowSorter(M model) {
setModel(model);
}
/** {@collect.stats}
* Sets the <code>TableModel</code> to use as the underlying model
* for this <code>TableRowSorter</code>. A value of <code>null</code>
* can be used to set an empty model.
*
* @param model the underlying model to use, or <code>null</code>
*/
public void setModel(M model) {
tableModel = model;
setModelWrapper(new TableRowSorterModelWrapper());
}
/** {@collect.stats}
* Sets the object responsible for converting values from the
* model to strings. If non-<code>null</code> this
* is used to convert any object values, that do not have a
* registered <code>Comparator</code>, to strings.
*
* @param stringConverter the object responsible for converting values
* from the model to strings
*/
public void setStringConverter(TableStringConverter stringConverter) {
this.stringConverter = stringConverter;
}
/** {@collect.stats}
* Returns the object responsible for converting values from the
* model to strings.
*
* @return object responsible for converting values to strings.
*/
public TableStringConverter getStringConverter() {
return stringConverter;
}
/** {@collect.stats}
* Returns the <code>Comparator</code> for the specified
* column. If a <code>Comparator</code> has not been specified using
* the <code>setComparator</code> method a <code>Comparator</code>
* will be returned based on the column class
* (<code>TableModel.getColumnClass</code>) of the specified column.
* If the column class is <code>String</code>,
* <code>Collator.getInstance</code> is returned. If the
* column class implements <code>Comparable</code> a private
* <code>Comparator</code> is returned that invokes the
* <code>compareTo</code> method. Otherwise
* <code>Collator.getInstance</code> is returned.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public Comparator<?> getComparator(int column) {
Comparator comparator = super.getComparator(column);
if (comparator != null) {
return comparator;
}
Class columnClass = getModel().getColumnClass(column);
if (columnClass == String.class) {
return Collator.getInstance();
}
if (Comparable.class.isAssignableFrom(columnClass)) {
return COMPARABLE_COMPARATOR;
}
return Collator.getInstance();
}
/** {@collect.stats}
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
protected boolean useToString(int column) {
Comparator comparator = super.getComparator(column);
if (comparator != null) {
return false;
}
Class columnClass = getModel().getColumnClass(column);
if (columnClass == String.class) {
return false;
}
if (Comparable.class.isAssignableFrom(columnClass)) {
return false;
}
return true;
}
/** {@collect.stats}
* Implementation of DefaultRowSorter.ModelWrapper that delegates to a
* TableModel.
*/
private class TableRowSorterModelWrapper extends ModelWrapper<M,Integer> {
public M getModel() {
return tableModel;
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(row, column);
}
public String getStringValueAt(int row, int column) {
TableStringConverter converter = getStringConverter();
if (converter != null) {
// Use the converter
String value = converter.toString(
tableModel, row, column);
if (value != null) {
return value;
}
return "";
}
// No converter, use getValueAt followed by toString
Object o = getValueAt(row, column);
if (o == null) {
return "";
}
String string = o.toString();
if (string == null) {
return "";
}
return string;
}
public Integer getIdentifier(int index) {
return index;
}
}
private static class ComparableComparator implements Comparator {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable)o1).compareTo(o2);
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import java.awt.Component;
import javax.swing.CellEditor;
import javax.swing.*;
/** {@collect.stats}
* This interface defines the method any object that would like to be
* an editor of values for components such as <code>JListBox</code>,
* <code>JComboBox</code>, <code>JTree</code>, or <code>JTable</code>
* needs to implement.
*
* @author Alan Chung
*/
public interface TableCellEditor extends CellEditor {
/** {@collect.stats}
* Sets an initial <code>value</code> for the editor. This will cause
* the editor to <code>stopEditing</code> and lose any partially
* edited value if the editor is editing when this method is called. <p>
*
* Returns the component that should be added to the client's
* <code>Component</code> hierarchy. Once installed in the client's
* hierarchy this component will then be able to draw and receive
* user input.
*
* @param table the <code>JTable</code> that is asking the
* editor to edit; can be <code>null</code>
* @param value the value of the cell to be edited; it is
* up to the specific editor to interpret
* and draw the value. For example, if value is
* the string "true", it could be rendered as a
* string or it could be rendered as a check
* box that is checked. <code>null</code>
* is a valid value
* @param isSelected true if the cell is to be rendered with
* highlighting
* @param row the row of the cell being edited
* @param column the column of the cell being edited
* @return the component for editing
*/
Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column);
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import javax.swing.*;
import javax.swing.event.*;
import java.io.Serializable;
import java.util.EventListener;
/** {@collect.stats}
* This abstract class provides default implementations for most of
* the methods in the <code>TableModel</code> interface. It takes care of
* the management of listeners and provides some conveniences for generating
* <code>TableModelEvents</code> and dispatching them to the listeners.
* To create a concrete <code>TableModel</code> as a subclass of
* <code>AbstractTableModel</code> you need only provide implementations
* for the following three methods:
*
* <pre>
* public int getRowCount();
* public int getColumnCount();
* public Object getValueAt(int row, int column);
* </pre>
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
*/
public abstract class AbstractTableModel implements TableModel, Serializable
{
//
// Instance Variables
//
/** {@collect.stats} List of listeners */
protected EventListenerList listenerList = new EventListenerList();
//
// Default Implementation of the Interface
//
/** {@collect.stats}
* Returns a default name for the column using spreadsheet conventions:
* A, B, C, ... Z, AA, AB, etc. If <code>column</code> cannot be found,
* returns an empty string.
*
* @param column the column being queried
* @return a string containing the default name of <code>column</code>
*/
public String getColumnName(int column) {
String result = "";
for (; column >= 0; column = column / 26 - 1) {
result = (char)((char)(column%26)+'A') + result;
}
return result;
}
/** {@collect.stats}
* Returns a column given its name.
* Implementation is naive so this should be overridden if
* this method is to be called often. This method is not
* in the <code>TableModel</code> interface and is not used by the
* <code>JTable</code>.
*
* @param columnName string containing name of column to be located
* @return the column with <code>columnName</code>, or -1 if not found
*/
public int findColumn(String columnName) {
for (int i = 0; i < getColumnCount(); i++) {
if (columnName.equals(getColumnName(i))) {
return i;
}
}
return -1;
}
/** {@collect.stats}
* Returns <code>Object.class</code> regardless of <code>columnIndex</code>.
*
* @param columnIndex the column being queried
* @return the Object.class
*/
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
/** {@collect.stats}
* Returns false. This is the default implementation for all cells.
*
* @param rowIndex the row being queried
* @param columnIndex the column being queried
* @return false
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
/** {@collect.stats}
* This empty implementation is provided so users don't have to implement
* this method if their data model is not editable.
*
* @param aValue value to assign to cell
* @param rowIndex row of cell
* @param columnIndex column of cell
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
//
// Managing Listeners
//
/** {@collect.stats}
* Adds a listener to the list that's notified each time a change
* to the data model occurs.
*
* @param l the TableModelListener
*/
public void addTableModelListener(TableModelListener l) {
listenerList.add(TableModelListener.class, l);
}
/** {@collect.stats}
* Removes a listener from the list that's notified each time a
* change to the data model occurs.
*
* @param l the TableModelListener
*/
public void removeTableModelListener(TableModelListener l) {
listenerList.remove(TableModelListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the table model listeners
* registered on this model.
*
* @return all of this model's <code>TableModelListener</code>s
* or an empty
* array if no table model listeners are currently registered
*
* @see #addTableModelListener
* @see #removeTableModelListener
*
* @since 1.4
*/
public TableModelListener[] getTableModelListeners() {
return (TableModelListener[])listenerList.getListeners(
TableModelListener.class);
}
//
// Fire methods
//
/** {@collect.stats}
* Notifies all listeners that all cell values in the table's
* rows may have changed. The number of rows may also have changed
* and the <code>JTable</code> should redraw the
* table from scratch. The structure of the table (as in the order of the
* columns) is assumed to be the same.
*
* @see TableModelEvent
* @see EventListenerList
* @see javax.swing.JTable#tableChanged(TableModelEvent)
*/
public void fireTableDataChanged() {
fireTableChanged(new TableModelEvent(this));
}
/** {@collect.stats}
* Notifies all listeners that the table's structure has changed.
* The number of columns in the table, and the names and types of
* the new columns may be different from the previous state.
* If the <code>JTable</code> receives this event and its
* <code>autoCreateColumnsFromModel</code>
* flag is set it discards any table columns that it had and reallocates
* default columns in the order they appear in the model. This is the
* same as calling <code>setModel(TableModel)</code> on the
* <code>JTable</code>.
*
* @see TableModelEvent
* @see EventListenerList
*/
public void fireTableStructureChanged() {
fireTableChanged(new TableModelEvent(this, TableModelEvent.HEADER_ROW));
}
/** {@collect.stats}
* Notifies all listeners that rows in the range
* <code>[firstRow, lastRow]</code>, inclusive, have been inserted.
*
* @param firstRow the first row
* @param lastRow the last row
*
* @see TableModelEvent
* @see EventListenerList
*
*/
public void fireTableRowsInserted(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
}
/** {@collect.stats}
* Notifies all listeners that rows in the range
* <code>[firstRow, lastRow]</code>, inclusive, have been updated.
*
* @param firstRow the first row
* @param lastRow the last row
*
* @see TableModelEvent
* @see EventListenerList
*/
public void fireTableRowsUpdated(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE));
}
/** {@collect.stats}
* Notifies all listeners that rows in the range
* <code>[firstRow, lastRow]</code>, inclusive, have been deleted.
*
* @param firstRow the first row
* @param lastRow the last row
*
* @see TableModelEvent
* @see EventListenerList
*/
public void fireTableRowsDeleted(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
}
/** {@collect.stats}
* Notifies all listeners that the value of the cell at
* <code>[row, column]</code> has been updated.
*
* @param row row of cell which has been updated
* @param column column of cell which has been updated
* @see TableModelEvent
* @see EventListenerList
*/
public void fireTableCellUpdated(int row, int column) {
fireTableChanged(new TableModelEvent(this, row, row, column));
}
/** {@collect.stats}
* Forwards the given notification event to all
* <code>TableModelListeners</code> that registered
* themselves as listeners for this table model.
*
* @param e the event to be forwarded
*
* @see #addTableModelListener
* @see TableModelEvent
* @see EventListenerList
*/
public void fireTableChanged(TableModelEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableModelListener.class) {
((TableModelListener)listeners[i+1]).tableChanged(e);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>AbstractTableModel</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
*
* You can specify the <code>listenerType</code> argument
* with a class literal,
* such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* model <code>m</code>
* for its table model listeners with the following code:
*
* <pre>TableModelListener[] tmls = (TableModelListener[])(m.getListeners(TableModelListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this component,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getTableModelListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
} // End of class AbstractTableModel
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import sun.swing.table.DefaultTableCellHeaderRenderer;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.beans.PropertyChangeListener;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* This is the object which manages the header of the <code>JTable</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
* @see javax.swing.JTable
*/
public class JTableHeader extends JComponent implements TableColumnModelListener, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TableHeaderUI";
//
// Instance Variables
//
/** {@collect.stats}
* The table for which this object is the header;
* the default is <code>null</code>.
*/
protected JTable table;
/** {@collect.stats}
* The <code>TableColumnModel</code> of the table header.
*/
protected TableColumnModel columnModel;
/** {@collect.stats}
* If true, reordering of columns are allowed by the user;
* the default is true.
*/
protected boolean reorderingAllowed;
/** {@collect.stats}
* If true, resizing of columns are allowed by the user;
* the default is true.
*/
protected boolean resizingAllowed;
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Real time repaints, in response
* to column dragging or resizing, are now unconditional.
*/
/*
* If this flag is true, then the header will repaint the table as
* a column is dragged or resized; the default is true.
*/
protected boolean updateTableInRealTime;
/** {@collect.stats} The index of the column being resized. <code>null</code> if not resizing. */
transient protected TableColumn resizingColumn;
/** {@collect.stats} The index of the column being dragged. <code>null</code> if not dragging. */
transient protected TableColumn draggedColumn;
/** {@collect.stats} The distance from its original position the column has been dragged. */
transient protected int draggedDistance;
/** {@collect.stats}
* The default renderer to be used when a <code>TableColumn</code>
* does not define a <code>headerRenderer</code>.
*/
private TableCellRenderer defaultRenderer;
//
// Constructors
//
/** {@collect.stats}
* Constructs a <code>JTableHeader</code> with a default
* <code>TableColumnModel</code>.
*
* @see #createDefaultColumnModel
*/
public JTableHeader() {
this(null);
}
/** {@collect.stats}
* Constructs a <code>JTableHeader</code> which is initialized with
* <code>cm</code> as the column model. If <code>cm</code> is
* <code>null</code> this method will initialize the table header
* with a default <code>TableColumnModel</code>.
*
* @param cm the column model for the table
* @see #createDefaultColumnModel
*/
public JTableHeader(TableColumnModel cm) {
super();
//setFocusable(false); // for strict win/mac compatibility mode,
// this method should be invoked
if (cm == null)
cm = createDefaultColumnModel();
setColumnModel(cm);
// Initialize local ivars
initializeLocalVars();
// Get UI going
updateUI();
}
//
// Local behavior attributes
//
/** {@collect.stats}
* Sets the table associated with this header.
* @param table the new table
* @beaninfo
* bound: true
* description: The table associated with this header.
*/
public void setTable(JTable table) {
JTable old = this.table;
this.table = table;
firePropertyChange("table", old, table);
}
/** {@collect.stats}
* Returns the table associated with this header.
* @return the <code>table</code> property
*/
public JTable getTable() {
return table;
}
/** {@collect.stats}
* Sets whether the user can drag column headers to reorder columns.
*
* @param reorderingAllowed true if the table view should allow
* reordering; otherwise false
* @see #getReorderingAllowed
* @beaninfo
* bound: true
* description: Whether the user can drag column headers to reorder columns.
*/
public void setReorderingAllowed(boolean reorderingAllowed) {
boolean old = this.reorderingAllowed;
this.reorderingAllowed = reorderingAllowed;
firePropertyChange("reorderingAllowed", old, reorderingAllowed);
}
/** {@collect.stats}
* Returns true if the user is allowed to rearrange columns by
* dragging their headers, false otherwise. The default is true. You can
* rearrange columns programmatically regardless of this setting.
*
* @return the <code>reorderingAllowed</code> property
* @see #setReorderingAllowed
*/
public boolean getReorderingAllowed() {
return reorderingAllowed;
}
/** {@collect.stats}
* Sets whether the user can resize columns by dragging between headers.
*
* @param resizingAllowed true if table view should allow
* resizing
* @see #getResizingAllowed
* @beaninfo
* bound: true
* description: Whether the user can resize columns by dragging between headers.
*/
public void setResizingAllowed(boolean resizingAllowed) {
boolean old = this.resizingAllowed;
this.resizingAllowed = resizingAllowed;
firePropertyChange("resizingAllowed", old, resizingAllowed);
}
/** {@collect.stats}
* Returns true if the user is allowed to resize columns by dragging
* between their headers, false otherwise. The default is true. You can
* resize columns programmatically regardless of this setting.
*
* @return the <code>resizingAllowed</code> property
* @see #setResizingAllowed
*/
public boolean getResizingAllowed() {
return resizingAllowed;
}
/** {@collect.stats}
* Returns the the dragged column, if and only if, a drag is in
* process, otherwise returns <code>null</code>.
*
* @return the dragged column, if a drag is in
* process, otherwise returns <code>null</code>
* @see #getDraggedDistance
*/
public TableColumn getDraggedColumn() {
return draggedColumn;
}
/** {@collect.stats}
* Returns the column's horizontal distance from its original
* position, if and only if, a drag is in process. Otherwise, the
* the return value is meaningless.
*
* @return the column's horizontal distance from its original
* position, if a drag is in process, otherwise the return
* value is meaningless
* @see #getDraggedColumn
*/
public int getDraggedDistance() {
return draggedDistance;
}
/** {@collect.stats}
* Returns the resizing column. If no column is being
* resized this method returns <code>null</code>.
*
* @return the resizing column, if a resize is in process, otherwise
* returns <code>null</code>
*/
public TableColumn getResizingColumn() {
return resizingColumn;
}
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Real time repaints, in response to
* column dragging or resizing, are now unconditional.
*/
/*
* Sets whether the body of the table updates in real time when
* a column is resized or dragged.
*
* @param flag true if tableView should update
* the body of the table in real time
* @see #getUpdateTableInRealTime
*/
public void setUpdateTableInRealTime(boolean flag) {
updateTableInRealTime = flag;
}
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Real time repaints, in response to
* column dragging or resizing, are now unconditional.
*/
/*
* Returns true if the body of the table view updates in real
* time when a column is resized or dragged. User can set this flag to
* false to speed up the table's response to user resize or drag actions.
* The default is true.
*
* @return true if the table updates in real time
* @see #setUpdateTableInRealTime
*/
public boolean getUpdateTableInRealTime() {
return updateTableInRealTime;
}
/** {@collect.stats}
* Sets the default renderer to be used when no <code>headerRenderer</code>
* is defined by a <code>TableColumn</code>.
* @param defaultRenderer the default renderer
* @since 1.3
*/
public void setDefaultRenderer(TableCellRenderer defaultRenderer) {
this.defaultRenderer = defaultRenderer;
}
/** {@collect.stats}
* Returns the default renderer used when no <code>headerRenderer</code>
* is defined by a <code>TableColumn</code>.
* @return the default renderer
* @since 1.3
*/
public TableCellRenderer getDefaultRenderer() {
return defaultRenderer;
}
/** {@collect.stats}
* Returns the index of the column that <code>point</code> lies in, or -1 if it
* lies out of bounds.
*
* @return the index of the column that <code>point</code> lies in, or -1 if it
* lies out of bounds
*/
public int columnAtPoint(Point point) {
int x = point.x;
if (!getComponentOrientation().isLeftToRight()) {
x = getWidthInRightToLeft() - x - 1;
}
return getColumnModel().getColumnIndexAtX(x);
}
/** {@collect.stats}
* Returns the rectangle containing the header tile at <code>column</code>.
* When the <code>column</code> parameter is out of bounds this method uses the
* same conventions as the <code>JTable</code> method <code>getCellRect</code>.
*
* @return the rectangle containing the header tile at <code>column</code>
* @see JTable#getCellRect
*/
public Rectangle getHeaderRect(int column) {
Rectangle r = new Rectangle();
TableColumnModel cm = getColumnModel();
r.height = getHeight();
if (column < 0) {
// x = width = 0;
if( !getComponentOrientation().isLeftToRight() ) {
r.x = getWidthInRightToLeft();
}
}
else if (column >= cm.getColumnCount()) {
if( getComponentOrientation().isLeftToRight() ) {
r.x = getWidth();
}
}
else {
for(int i = 0; i < column; i++) {
r.x += cm.getColumn(i).getWidth();
}
if( !getComponentOrientation().isLeftToRight() ) {
r.x = getWidthInRightToLeft() - r.x - cm.getColumn(column).getWidth();
}
r.width = cm.getColumn(column).getWidth();
}
return r;
}
/** {@collect.stats}
* Allows the renderer's tips to be used if there is text set.
* @param event the location of the event identifies the proper
* renderer and, therefore, the proper tip
* @return the tool tip for this component
*/
public String getToolTipText(MouseEvent event) {
String tip = null;
Point p = event.getPoint();
int column;
// Locate the renderer under the event location
if ((column = columnAtPoint(p)) != -1) {
TableColumn aColumn = columnModel.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
renderer = defaultRenderer;
}
Component component = renderer.getTableCellRendererComponent(
getTable(), aColumn.getHeaderValue(), false, false,
-1, column);
// Now have to see if the component is a JComponent before
// getting the tip
if (component instanceof JComponent) {
// Convert the event to the renderer's coordinate system
MouseEvent newEvent;
Rectangle cellRect = getHeaderRect(column);
p.translate(-cellRect.x, -cellRect.y);
newEvent = new MouseEvent(component, event.getID(),
event.getWhen(), event.getModifiers(),
p.x, p.y, event.getXOnScreen(), event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(), MouseEvent.NOBUTTON);
tip = ((JComponent)component).getToolTipText(newEvent);
}
}
// No tip from the renderer get our own tip
if (tip == null)
tip = getToolTipText();
return tip;
}
//
// Managing TableHeaderUI
//
/** {@collect.stats}
* Returns the look and feel (L&F) object that renders this component.
*
* @return the <code>TableHeaderUI</code> object that renders this component
*/
public TableHeaderUI getUI() {
return (TableHeaderUI)ui;
}
/** {@collect.stats}
* Sets the look and feel (L&F) object that renders this component.
*
* @param ui the <code>TableHeaderUI</code> L&F object
* @see UIDefaults#getUI
*/
public void setUI(TableHeaderUI ui){
if (this.ui != ui) {
super.setUI(ui);
repaint();
}
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the look and feel
* (L&F) has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI(){
setUI((TableHeaderUI)UIManager.getUI(this));
TableCellRenderer renderer = getDefaultRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
}
/** {@collect.stats}
* Returns the suffix used to construct the name of the look and feel
* (L&F) class used to render this component.
* @return the string "TableHeaderUI"
*
* @return "TableHeaderUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
//
// Managing models
//
/** {@collect.stats}
* Sets the column model for this table to <code>newModel</code> and registers
* for listener notifications from the new column model.
*
* @param columnModel the new data source for this table
* @exception IllegalArgumentException
* if <code>newModel</code> is <code>null</code>
* @see #getColumnModel
* @beaninfo
* bound: true
* description: The object governing the way columns appear in the view.
*/
public void setColumnModel(TableColumnModel columnModel) {
if (columnModel == null) {
throw new IllegalArgumentException("Cannot set a null ColumnModel");
}
TableColumnModel old = this.columnModel;
if (columnModel != old) {
if (old != null) {
old.removeColumnModelListener(this);
}
this.columnModel = columnModel;
columnModel.addColumnModelListener(this);
firePropertyChange("columnModel", old, columnModel);
resizeAndRepaint();
}
}
/** {@collect.stats}
* Returns the <code>TableColumnModel</code> that contains all column information
* of this table header.
*
* @return the <code>columnModel</code> property
* @see #setColumnModel
*/
public TableColumnModel getColumnModel() {
return columnModel;
}
//
// Implementing TableColumnModelListener interface
//
/** {@collect.stats}
* Invoked when a column is added to the table column model.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnAdded(TableColumnModelEvent e) { resizeAndRepaint(); }
/** {@collect.stats}
* Invoked when a column is removed from the table column model.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnRemoved(TableColumnModelEvent e) { resizeAndRepaint(); }
/** {@collect.stats}
* Invoked when a column is repositioned.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnMoved(TableColumnModelEvent e) { repaint(); }
/** {@collect.stats}
* Invoked when a column is moved due to a margin change.
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnMarginChanged(ChangeEvent e) { resizeAndRepaint(); }
// --Redrawing the header is slow in cell selection mode.
// --Since header selection is ugly and it is always clear from the
// --view which columns are selected, don't redraw the header.
/** {@collect.stats}
* Invoked when the selection model of the <code>TableColumnModel</code>
* is changed. This method currently has no effect (the header is not
* redrawn).
* <p>
* Application code will not use these methods explicitly, they
* are used internally by <code>JTable</code>.
*
* @param e the event received
* @see TableColumnModelListener
*/
public void columnSelectionChanged(ListSelectionEvent e) { } // repaint(); }
//
// Package Methods
//
/** {@collect.stats}
* Returns the default column model object which is
* a <code>DefaultTableColumnModel</code>. A subclass can override this
* method to return a different column model object
*
* @return the default column model object
*/
protected TableColumnModel createDefaultColumnModel() {
return new DefaultTableColumnModel();
}
/** {@collect.stats}
* Returns a default renderer to be used when no header renderer
* is defined by a <code>TableColumn</code>.
*
* @return the default table column renderer
* @since 1.3
*/
protected TableCellRenderer createDefaultRenderer() {
return new DefaultTableCellHeaderRenderer();
}
/** {@collect.stats}
* Initializes the local variables and properties with default values.
* Used by the constructor methods.
*/
protected void initializeLocalVars() {
setOpaque(true);
table = null;
reorderingAllowed = true;
resizingAllowed = true;
draggedColumn = null;
draggedDistance = 0;
resizingColumn = null;
updateTableInRealTime = true;
// I'm registered to do tool tips so we can draw tips for the
// renderers
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(this);
setDefaultRenderer(createDefaultRenderer());
}
/** {@collect.stats}
* Sizes the header and marks it as needing display. Equivalent
* to <code>revalidate</code> followed by <code>repaint</code>.
*/
public void resizeAndRepaint() {
revalidate();
repaint();
}
/** {@collect.stats}
* Sets the header's <code>draggedColumn</code> to <code>aColumn</code>.
* <p>
* Application code will not use this method explicitly, it is used
* internally by the column dragging mechanism.
*
* @param aColumn the column being dragged, or <code>null</code> if
* no column is being dragged
*/
public void setDraggedColumn(TableColumn aColumn) {
draggedColumn = aColumn;
}
/** {@collect.stats}
* Sets the header's <code>draggedDistance</code> to <code>distance</code>.
* @param distance the distance dragged
*/
public void setDraggedDistance(int distance) {
draggedDistance = distance;
}
/** {@collect.stats}
* Sets the header's <code>resizingColumn</code> to <code>aColumn</code>.
* <p>
* Application code will not use this method explicitly, it
* is used internally by the column sizing mechanism.
*
* @param aColumn the column being resized, or <code>null</code> if
* no column is being resized
*/
public void setResizingColumn(TableColumn aColumn) {
resizingColumn = aColumn;
}
/** {@collect.stats}
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if ((ui != null) && (getUIClassID().equals(uiClassID))) {
ui.installUI(this);
}
}
private int getWidthInRightToLeft() {
if ((table != null) &&
(table.getAutoResizeMode() != JTable.AUTO_RESIZE_OFF)) {
return table.getWidth();
}
return super.getWidth();
}
/** {@collect.stats}
* Returns a string representation of this <code>JTableHeader</code>. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
* <P>
* Overriding <code>paramString</code> to provide information about the
* specific new aspects of the JFC components.
*
* @return a string representation of this <code>JTableHeader</code>
*/
protected String paramString() {
String reorderingAllowedString = (reorderingAllowed ?
"true" : "false");
String resizingAllowedString = (resizingAllowed ?
"true" : "false");
String updateTableInRealTimeString = (updateTableInRealTime ?
"true" : "false");
return super.paramString() +
",draggedDistance=" + draggedDistance +
",reorderingAllowed=" + reorderingAllowedString +
",resizingAllowed=" + resizingAllowedString +
",updateTableInRealTime=" + updateTableInRealTimeString;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JTableHeader.
* For JTableHeaders, the AccessibleContext takes the form of an
* AccessibleJTableHeader.
* A new AccessibleJTableHeader instance is created if necessary.
*
* @return an AccessibleJTableHeader that serves as the
* AccessibleContext of this JTableHeader
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTableHeader();
}
return accessibleContext;
}
//
// *** should also implement AccessibleSelection?
// *** and what's up with keyboard navigation/manipulation?
//
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTableHeader</code> class. It provides an implementation of the
* Java Accessibility API appropriate to table header user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJTableHeader extends AccessibleJComponent {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PANEL;
}
/** {@collect.stats}
* Returns the Accessible child, if one exists, contained at the local
* coordinate Point.
*
* @param p The point defining the top-left corner of the Accessible,
* given in the coordinate space of the object's parent.
* @return the Accessible, if it exists, at the specified location;
* else null
*/
public Accessible getAccessibleAt(Point p) {
int column;
// Locate the renderer under the Point
if ((column = JTableHeader.this.columnAtPoint(p)) != -1) {
TableColumn aColumn = JTableHeader.this.columnModel.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
if (defaultRenderer != null) {
renderer = defaultRenderer;
} else {
return null;
}
}
Component component = renderer.getTableCellRendererComponent(
JTableHeader.this.getTable(),
aColumn.getHeaderValue(), false, false,
-1, column);
return new AccessibleJTableHeaderEntry(column, JTableHeader.this, JTableHeader.this.table);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return JTableHeader.this.columnModel.getColumnCount();
}
/** {@collect.stats}
* Return the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
TableColumn aColumn = JTableHeader.this.columnModel.getColumn(i)
;
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
if (defaultRenderer != null) {
renderer = defaultRenderer;
} else {
return null;
}
}
Component component = renderer.getTableCellRendererComponent(
JTableHeader.this.getTable(),
aColumn.getHeaderValue(), false, false,
-1, i);
return new AccessibleJTableHeaderEntry(i, JTableHeader.this, JTableHeader.this.table);
}
}
/** {@collect.stats}
* This class provides an implementation of the Java Accessibility
* API appropropriate for JTableHeader entries.
*/
protected class AccessibleJTableHeaderEntry extends AccessibleContext
implements Accessible, AccessibleComponent {
private JTableHeader parent;
private int column;
private JTable table;
/** {@collect.stats}
* Constructs an AccessiblJTableHeaaderEntry
* @since 1.4
*/
public AccessibleJTableHeaderEntry(int c, JTableHeader p, JTable t) {
parent = p;
column = c;
table = t;
this.setAccessibleParent(parent);
}
/** {@collect.stats}
* Get the AccessibleContext associated with this object.
* In the implementation of the Java Accessibility API
* for this class, returns this object, which serves as
* its own AccessibleContext.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
private AccessibleContext getCurrentAccessibleContext() {
TableColumnModel tcm = table.getColumnModel();
if (tcm != null) {
// Fixes 4772355 - ArrayOutOfBoundsException in
// JTableHeader
if (column < 0 || column >= tcm.getColumnCount()) {
return null;
}
TableColumn aColumn = tcm.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
if (defaultRenderer != null) {
renderer = defaultRenderer;
} else {
return null;
}
}
Component c = renderer.getTableCellRendererComponent(
JTableHeader.this.getTable(),
aColumn.getHeaderValue(), false, false,
-1, column);
if (c instanceof Accessible) {
return ((Accessible) c).getAccessibleContext();
}
}
return null;
}
private Component getCurrentComponent() {
TableColumnModel tcm = table.getColumnModel();
if (tcm != null) {
// Fixes 4772355 - ArrayOutOfBoundsException in
// JTableHeader
if (column < 0 || column >= tcm.getColumnCount()) {
return null;
}
TableColumn aColumn = tcm.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
if (defaultRenderer != null) {
renderer = defaultRenderer;
} else {
return null;
}
}
return renderer.getTableCellRendererComponent(
JTableHeader.this.getTable(),
aColumn.getHeaderValue(), false, false,
-1, column);
} else {
return null;
}
}
// AccessibleContext methods
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
String name = ac.getAccessibleName();
if ((name != null) && (name != "")) {
// return the cell renderer's AccessibleName
return name;
}
}
if ((accessibleName != null) && (accessibleName != "")) {
return accessibleName;
} else {
// fall back to the client property
String name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
if (name != null) {
return name;
} else {
return table.getColumnName(column);
}
}
}
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
} else {
super.setAccessibleName(s);
}
}
//
// *** should check toolTip text for desc. (needs MouseEvent)
//
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return super.getAccessibleDescription();
}
}
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
} else {
super.setAccessibleDescription(s);
}
}
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return AccessibleRole.COLUMN_HEADER;
}
}
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
AccessibleStateSet states = ac.getAccessibleStateSet();
if (isShowing()) {
states.add(AccessibleState.SHOWING);
}
return states;
} else {
return new AccessibleStateSet(); // must be non null?
}
}
public int getAccessibleIndexInParent() {
return column;
}
public int getAccessibleChildrenCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
} else {
return 0;
}
}
public Accessible getAccessibleChild(int i) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
Accessible accessibleChild = ac.getAccessibleChild(i);
ac.setAccessibleParent(this);
return accessibleChild;
} else {
return null;
}
}
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return null;
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
} else {
super.addPropertyChangeListener(l);
}
}
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
} else {
super.removePropertyChangeListener(l);
}
}
public AccessibleAction getAccessibleAction() {
return getCurrentAccessibleContext().getAccessibleAction();
}
/** {@collect.stats}
* Get the AccessibleComponent associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleComponent interface on behalf of itself.
*
* @return this object
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
public AccessibleSelection getAccessibleSelection() {
return getCurrentAccessibleContext().getAccessibleSelection();
}
public AccessibleText getAccessibleText() {
return getCurrentAccessibleContext().getAccessibleText();
}
public AccessibleValue getAccessibleValue() {
return getCurrentAccessibleContext().getAccessibleValue();
}
// AccessibleComponent methods
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
public boolean isVisible() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isVisible();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isVisible();
} else {
return false;
}
}
}
public void setVisible(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setVisible(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setVisible(b);
}
}
}
public boolean isShowing() {
if (isVisible() && JTableHeader.this.isShowing()) {
return true;
} else {
return false;
}
}
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
public Point getLocationOnScreen() {
if (parent != null) {
Point parentLocation = parent.getLocationOnScreen();
Point componentLocation = getLocation();
componentLocation.translate(parentLocation.x, parentLocation.y);
return componentLocation;
} else {
return null;
}
}
public Point getLocation() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.getLocation();
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.getLocation();
} else {
return getBounds().getLocation();
}
}
}
public void setLocation(Point p) {
// if ((parent != null) && (parent.contains(p))) {
// ensureIndexIsVisible(indexInParent);
// }
}
public Rectangle getBounds() {
Rectangle r = table.getCellRect(-1, column, false);
r.y = 0;
return r;
// AccessibleContext ac = getCurrentAccessibleContext();
// if (ac instanceof AccessibleComponent) {
// return ((AccessibleComponent) ac).getBounds();
// } else {
// Component c = getCurrentComponent();
// if (c != null) {
// return c.getBounds();
// } else {
// Rectangle r = table.getCellRect(-1, column, false);
// r.y = 0;
// return r;
// }
// }
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
public Dimension getSize() {
return getBounds().getSize();
// AccessibleContext ac = getCurrentAccessibleContext();
// if (ac instanceof AccessibleComponent) {
// Rectangle r = ((AccessibleComponent) ac).getBounds();
// return r.getSize();
// } else {
// Component c = getCurrentComponent();
// if (c != null) {
// Rectangle r = c.getBounds();
// return r.getSize();
// } else {
// return getBounds().getSize();
// }
// }
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
} // inner class AccessibleJTableHeaderElement
} // inner class AccessibleJTableHeader
} // End of Class JTableHeader
|
Java
|
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
/** {@collect.stats}
* TableStringConverter is used to convert objects from the model into
* strings. This is useful in filtering and searching when the model returns
* objects that do not have meaningful <code>toString</code> implementations.
*
* @since 1.6
*/
public abstract class TableStringConverter {
/** {@collect.stats}
* Returns the string representation of the value at the specified
* location.
*
* @param model the <code>TableModel</code> to fetch the value from
* @param row the row the string is being requested for
* @param column the column the string is being requested for
* @return the string representation. This should never return null.
* @throws NullPointerException if <code>model</code> is null
* @throws IndexOutOfBoundsException if the arguments are outside the
* bounds of the model
*/
public abstract String toString(TableModel model, int row, int column);
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import javax.swing.*;
import javax.swing.event.*;
/** {@collect.stats}
* The <code>TableModel</code> interface specifies the methods the
* <code>JTable</code> will use to interrogate a tabular data model. <p>
*
* The <code>JTable</code> can be set up to display any data
* model which implements the
* <code>TableModel</code> interface with a couple of lines of code: <p>
* <pre>
* TableModel myData = new MyTableModel();
* JTable table = new JTable(myData);
* </pre><p>
*
* For further documentation, see <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data">Creating a Table Model</a>
* in <em>The Java Tutorial</em>.
* <p>
* @author Philip Milne
* @see JTable
*/
public interface TableModel
{
/** {@collect.stats}
* Returns the number of rows in the model. A
* <code>JTable</code> uses this method to determine how many rows it
* should display. This method should be quick, as it
* is called frequently during rendering.
*
* @return the number of rows in the model
* @see #getColumnCount
*/
public int getRowCount();
/** {@collect.stats}
* Returns the number of columns in the model. A
* <code>JTable</code> uses this method to determine how many columns it
* should create and display by default.
*
* @return the number of columns in the model
* @see #getRowCount
*/
public int getColumnCount();
/** {@collect.stats}
* Returns the name of the column at <code>columnIndex</code>. This is used
* to initialize the table's column header name. Note: this name does
* not need to be unique; two columns in a table can have the same name.
*
* @param columnIndex the index of the column
* @return the name of the column
*/
public String getColumnName(int columnIndex);
/** {@collect.stats}
* Returns the most specific superclass for all the cell values
* in the column. This is used by the <code>JTable</code> to set up a
* default renderer and editor for the column.
*
* @param columnIndex the index of the column
* @return the common ancestor class of the object values in the model.
*/
public Class<?> getColumnClass(int columnIndex);
/** {@collect.stats}
* Returns true if the cell at <code>rowIndex</code> and
* <code>columnIndex</code>
* is editable. Otherwise, <code>setValueAt</code> on the cell will not
* change the value of that cell.
*
* @param rowIndex the row whose value to be queried
* @param columnIndex the column whose value to be queried
* @return true if the cell is editable
* @see #setValueAt
*/
public boolean isCellEditable(int rowIndex, int columnIndex);
/** {@collect.stats}
* Returns the value for the cell at <code>columnIndex</code> and
* <code>rowIndex</code>.
*
* @param rowIndex the row whose value is to be queried
* @param columnIndex the column whose value is to be queried
* @return the value Object at the specified cell
*/
public Object getValueAt(int rowIndex, int columnIndex);
/** {@collect.stats}
* Sets the value in the cell at <code>columnIndex</code> and
* <code>rowIndex</code> to <code>aValue</code>.
*
* @param aValue the new value
* @param rowIndex the row whose value is to be changed
* @param columnIndex the column whose value is to be changed
* @see #getValueAt
* @see #isCellEditable
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex);
/** {@collect.stats}
* Adds a listener to the list that is notified each time a change
* to the data model occurs.
*
* @param l the TableModelListener
*/
public void addTableModelListener(TableModelListener l);
/** {@collect.stats}
* Removes a listener from the list that is notified each time a
* change to the data model occurs.
*
* @param l the TableModelListener
*/
public void removeTableModelListener(TableModelListener l);
}
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import java.util.Enumeration;
import javax.swing.event.ChangeEvent;
import javax.swing.event.*;
import javax.swing.*;
/** {@collect.stats}
* Defines the requirements for a table column model object suitable for
* use with <code>JTable</code>.
*
* @author Alan Chung
* @author Philip Milne
* @see DefaultTableColumnModel
*/
public interface TableColumnModel
{
//
// Modifying the model
//
/** {@collect.stats}
* Appends <code>aColumn</code> to the end of the
* <code>tableColumns</code> array.
* This method posts a <code>columnAdded</code>
* event to its listeners.
*
* @param aColumn the <code>TableColumn</code> to be added
* @see #removeColumn
*/
public void addColumn(TableColumn aColumn);
/** {@collect.stats}
* Deletes the <code>TableColumn</code> <code>column</code> from the
* <code>tableColumns</code> array. This method will do nothing if
* <code>column</code> is not in the table's column list.
* This method posts a <code>columnRemoved</code>
* event to its listeners.
*
* @param column the <code>TableColumn</code> to be removed
* @see #addColumn
*/
public void removeColumn(TableColumn column);
/** {@collect.stats}
* Moves the column and its header at <code>columnIndex</code> to
* <code>newIndex</code>. The old column at <code>columnIndex</code>
* will now be found at <code>newIndex</code>. The column that used
* to be at <code>newIndex</code> is shifted left or right
* to make room. This will not move any columns if
* <code>columnIndex</code> equals <code>newIndex</code>. This method
* posts a <code>columnMoved</code> event to its listeners.
*
* @param columnIndex the index of column to be moved
* @param newIndex index of the column's new location
* @exception IllegalArgumentException if <code>columnIndex</code> or
* <code>newIndex</code>
* are not in the valid range
*/
public void moveColumn(int columnIndex, int newIndex);
/** {@collect.stats}
* Sets the <code>TableColumn</code>'s column margin to
* <code>newMargin</code>. This method posts
* a <code>columnMarginChanged</code> event to its listeners.
*
* @param newMargin the width, in pixels, of the new column margins
* @see #getColumnMargin
*/
public void setColumnMargin(int newMargin);
//
// Querying the model
//
/** {@collect.stats}
* Returns the number of columns in the model.
* @return the number of columns in the model
*/
public int getColumnCount();
/** {@collect.stats}
* Returns an <code>Enumeration</code> of all the columns in the model.
* @return an <code>Enumeration</code> of all the columns in the model
*/
public Enumeration<TableColumn> getColumns();
/** {@collect.stats}
* Returns the index of the first column in the table
* whose identifier is equal to <code>identifier</code>,
* when compared using <code>equals</code>.
*
* @param columnIdentifier the identifier object
* @return the index of the first table column
* whose identifier is equal to <code>identifier</code>
* @exception IllegalArgumentException if <code>identifier</code>
* is <code>null</code>, or no
* <code>TableColumn</code> has this
* <code>identifier</code>
* @see #getColumn
*/
public int getColumnIndex(Object columnIdentifier);
/** {@collect.stats}
* Returns the <code>TableColumn</code> object for the column at
* <code>columnIndex</code>.
*
* @param columnIndex the index of the desired column
* @return the <code>TableColumn</code> object for
* the column at <code>columnIndex</code>
*/
public TableColumn getColumn(int columnIndex);
/** {@collect.stats}
* Returns the width between the cells in each column.
* @return the margin, in pixels, between the cells
*/
public int getColumnMargin();
/** {@collect.stats}
* Returns the index of the column that lies on the
* horizontal point, <code>xPosition</code>;
* or -1 if it lies outside the any of the column's bounds.
*
* In keeping with Swing's separable model architecture, a
* TableColumnModel does not know how the table columns actually appear on
* screen. The visual presentation of the columns is the responsibility
* of the view/controller object using this model (typically JTable). The
* view/controller need not display the columns sequentially from left to
* right. For example, columns could be displayed from right to left to
* accomodate a locale preference or some columns might be hidden at the
* request of the user. Because the model does not know how the columns
* are laid out on screen, the given <code>xPosition</code> should not be
* considered to be a coordinate in 2D graphics space. Instead, it should
* be considered to be a width from the start of the first column in the
* model. If the column index for a given X coordinate in 2D space is
* required, <code>JTable.columnAtPoint</code> can be used instead.
*
* @return the index of the column; or -1 if no column is found
* @see javax.swing.JTable#columnAtPoint
*/
public int getColumnIndexAtX(int xPosition);
/** {@collect.stats}
* Returns the total width of all the columns.
* @return the total computed width of all columns
*/
public int getTotalColumnWidth();
//
// Selection
//
/** {@collect.stats}
* Sets whether the columns in this model may be selected.
* @param flag true if columns may be selected; otherwise false
* @see #getColumnSelectionAllowed
*/
public void setColumnSelectionAllowed(boolean flag);
/** {@collect.stats}
* Returns true if columns may be selected.
* @return true if columns may be selected
* @see #setColumnSelectionAllowed
*/
public boolean getColumnSelectionAllowed();
/** {@collect.stats}
* Returns an array of indicies of all selected columns.
* @return an array of integers containing the indicies of all
* selected columns; or an empty array if nothing is selected
*/
public int[] getSelectedColumns();
/** {@collect.stats}
* Returns the number of selected columns.
*
* @return the number of selected columns; or 0 if no columns are selected
*/
public int getSelectedColumnCount();
/** {@collect.stats}
* Sets the selection model.
*
* @param newModel a <code>ListSelectionModel</code> object
* @see #getSelectionModel
*/
public void setSelectionModel(ListSelectionModel newModel);
/** {@collect.stats}
* Returns the current selection model.
*
* @return a <code>ListSelectionModel</code> object
* @see #setSelectionModel
*/
public ListSelectionModel getSelectionModel();
//
// Listener
//
/** {@collect.stats}
* Adds a listener for table column model events.
*
* @param x a <code>TableColumnModelListener</code> object
*/
public void addColumnModelListener(TableColumnModelListener x);
/** {@collect.stats}
* Removes a listener for table column model events.
*
* @param x a <code>TableColumnModelListener</code> object
*/
public void removeColumnModelListener(TableColumnModelListener x);
}
|
Java
|
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.util.Vector;
import java.util.Enumeration;
import java.util.EventListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.Serializable;
import sun.swing.SwingUtilities2;
/** {@collect.stats}
* The standard column-handler for a <code>JTable</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
* @see JTable
*/
public class DefaultTableColumnModel implements TableColumnModel,
PropertyChangeListener, ListSelectionListener, Serializable
{
//
// Instance Variables
//
/** {@collect.stats} Array of TableColumn objects in this model */
protected Vector<TableColumn> tableColumns;
/** {@collect.stats} Model for keeping track of column selections */
protected ListSelectionModel selectionModel;
/** {@collect.stats} Width margin between each column */
protected int columnMargin;
/** {@collect.stats} List of TableColumnModelListener */
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats} Change event (only one needed) */
transient protected ChangeEvent changeEvent = null;
/** {@collect.stats} Column selection allowed in this column model */
protected boolean columnSelectionAllowed;
/** {@collect.stats} A local cache of the combined width of all columns */
protected int totalColumnWidth;
//
// Constructors
//
/** {@collect.stats}
* Creates a default table column model.
*/
public DefaultTableColumnModel() {
super();
// Initialize local ivars to default
tableColumns = new Vector<TableColumn>();
setSelectionModel(createSelectionModel());
setColumnMargin(1);
invalidateWidthCache();
setColumnSelectionAllowed(false);
}
//
// Modifying the model
//
/** {@collect.stats}
* Appends <code>aColumn</code> to the end of the
* <code>tableColumns</code> array.
* This method also posts the <code>columnAdded</code>
* event to its listeners.
*
* @param aColumn the <code>TableColumn</code> to be added
* @exception IllegalArgumentException if <code>aColumn</code> is
* <code>null</code>
* @see #removeColumn
*/
public void addColumn(TableColumn aColumn) {
if (aColumn == null) {
throw new IllegalArgumentException("Object is null");
}
tableColumns.addElement(aColumn);
aColumn.addPropertyChangeListener(this);
invalidateWidthCache();
// Post columnAdded event notification
fireColumnAdded(new TableColumnModelEvent(this, 0,
getColumnCount() - 1));
}
/** {@collect.stats}
* Deletes the <code>column</code> from the
* <code>tableColumns</code> array. This method will do nothing if
* <code>column</code> is not in the table's columns list.
* <code>tile</code> is called
* to resize both the header and table views.
* This method also posts a <code>columnRemoved</code>
* event to its listeners.
*
* @param column the <code>TableColumn</code> to be removed
* @see #addColumn
*/
public void removeColumn(TableColumn column) {
int columnIndex = tableColumns.indexOf(column);
if (columnIndex != -1) {
// Adjust for the selection
if (selectionModel != null) {
selectionModel.removeIndexInterval(columnIndex,columnIndex);
}
column.removePropertyChangeListener(this);
tableColumns.removeElementAt(columnIndex);
invalidateWidthCache();
// Post columnAdded event notification. (JTable and JTableHeader
// listens so they can adjust size and redraw)
fireColumnRemoved(new TableColumnModelEvent(this,
columnIndex, 0));
}
}
/** {@collect.stats}
* Moves the column and heading at <code>columnIndex</code> to
* <code>newIndex</code>. The old column at <code>columnIndex</code>
* will now be found at <code>newIndex</code>. The column
* that used to be at <code>newIndex</code> is shifted
* left or right to make room. This will not move any columns if
* <code>columnIndex</code> equals <code>newIndex</code>. This method
* also posts a <code>columnMoved</code> event to its listeners.
*
* @param columnIndex the index of column to be moved
* @param newIndex new index to move the column
* @exception IllegalArgumentException if <code>column</code> or
* <code>newIndex</code>
* are not in the valid range
*/
public void moveColumn(int columnIndex, int newIndex) {
if ((columnIndex < 0) || (columnIndex >= getColumnCount()) ||
(newIndex < 0) || (newIndex >= getColumnCount()))
throw new IllegalArgumentException("moveColumn() - Index out of range");
TableColumn aColumn;
// If the column has not yet moved far enough to change positions
// post the event anyway, the "draggedDistance" property of the
// tableHeader will say how far the column has been dragged.
// Here we are really trying to get the best out of an
// API that could do with some rethinking. We preserve backward
// compatibility by slightly bending the meaning of these methods.
if (columnIndex == newIndex) {
fireColumnMoved(new TableColumnModelEvent(this, columnIndex, newIndex));
return;
}
aColumn = (TableColumn)tableColumns.elementAt(columnIndex);
tableColumns.removeElementAt(columnIndex);
boolean selected = selectionModel.isSelectedIndex(columnIndex);
selectionModel.removeIndexInterval(columnIndex,columnIndex);
tableColumns.insertElementAt(aColumn, newIndex);
selectionModel.insertIndexInterval(newIndex, 1, true);
if (selected) {
selectionModel.addSelectionInterval(newIndex, newIndex);
}
else {
selectionModel.removeSelectionInterval(newIndex, newIndex);
}
fireColumnMoved(new TableColumnModelEvent(this, columnIndex,
newIndex));
}
/** {@collect.stats}
* Sets the column margin to <code>newMargin</code>. This method
* also posts a <code>columnMarginChanged</code> event to its
* listeners.
*
* @param newMargin the new margin width, in pixels
* @see #getColumnMargin
* @see #getTotalColumnWidth
*/
public void setColumnMargin(int newMargin) {
if (newMargin != columnMargin) {
columnMargin = newMargin;
// Post columnMarginChanged event notification.
fireColumnMarginChanged();
}
}
//
// Querying the model
//
/** {@collect.stats}
* Returns the number of columns in the <code>tableColumns</code> array.
*
* @return the number of columns in the <code>tableColumns</code> array
* @see #getColumns
*/
public int getColumnCount() {
return tableColumns.size();
}
/** {@collect.stats}
* Returns an <code>Enumeration</code> of all the columns in the model.
* @return an <code>Enumeration</code> of the columns in the model
*/
public Enumeration<TableColumn> getColumns() {
return tableColumns.elements();
}
/** {@collect.stats}
* Returns the index of the first column in the <code>tableColumns</code>
* array whose identifier is equal to <code>identifier</code>,
* when compared using <code>equals</code>.
*
* @param identifier the identifier object
* @return the index of the first column in the
* <code>tableColumns</code> array whose identifier
* is equal to <code>identifier</code>
* @exception IllegalArgumentException if <code>identifier</code>
* is <code>null</code>, or if no
* <code>TableColumn</code> has this
* <code>identifier</code>
* @see #getColumn
*/
public int getColumnIndex(Object identifier) {
if (identifier == null) {
throw new IllegalArgumentException("Identifier is null");
}
Enumeration enumeration = getColumns();
TableColumn aColumn;
int index = 0;
while (enumeration.hasMoreElements()) {
aColumn = (TableColumn)enumeration.nextElement();
// Compare them this way in case the column's identifier is null.
if (identifier.equals(aColumn.getIdentifier()))
return index;
index++;
}
throw new IllegalArgumentException("Identifier not found");
}
/** {@collect.stats}
* Returns the <code>TableColumn</code> object for the column
* at <code>columnIndex</code>.
*
* @param columnIndex the index of the column desired
* @return the <code>TableColumn</code> object for the column
* at <code>columnIndex</code>
*/
public TableColumn getColumn(int columnIndex) {
return (TableColumn)tableColumns.elementAt(columnIndex);
}
/** {@collect.stats}
* Returns the width margin for <code>TableColumn</code>.
* The default <code>columnMargin</code> is 1.
*
* @return the maximum width for the <code>TableColumn</code>
* @see #setColumnMargin
*/
public int getColumnMargin() {
return columnMargin;
}
/** {@collect.stats}
* Returns the index of the column that lies at position <code>x</code>,
* or -1 if no column covers this point.
*
* In keeping with Swing's separable model architecture, a
* TableColumnModel does not know how the table columns actually appear on
* screen. The visual presentation of the columns is the responsibility
* of the view/controller object using this model (typically JTable). The
* view/controller need not display the columns sequentially from left to
* right. For example, columns could be displayed from right to left to
* accomodate a locale preference or some columns might be hidden at the
* request of the user. Because the model does not know how the columns
* are laid out on screen, the given <code>xPosition</code> should not be
* considered to be a coordinate in 2D graphics space. Instead, it should
* be considered to be a width from the start of the first column in the
* model. If the column index for a given X coordinate in 2D space is
* required, <code>JTable.columnAtPoint</code> can be used instead.
*
* @param x the horizontal location of interest
* @return the index of the column or -1 if no column is found
* @see javax.swing.JTable#columnAtPoint
*/
public int getColumnIndexAtX(int x) {
if (x < 0) {
return -1;
}
int cc = getColumnCount();
for(int column = 0; column < cc; column++) {
x = x - getColumn(column).getWidth();
if (x < 0) {
return column;
}
}
return -1;
}
/** {@collect.stats}
* Returns the total combined width of all columns.
* @return the <code>totalColumnWidth</code> property
*/
public int getTotalColumnWidth() {
if (totalColumnWidth == -1) {
recalcWidthCache();
}
return totalColumnWidth;
}
//
// Selection model
//
/** {@collect.stats}
* Sets the selection model for this <code>TableColumnModel</code>
* to <code>newModel</code>
* and registers for listener notifications from the new selection
* model. If <code>newModel</code> is <code>null</code>,
* an exception is thrown.
*
* @param newModel the new selection model
* @exception IllegalArgumentException if <code>newModel</code>
* is <code>null</code>
* @see #getSelectionModel
*/
public void setSelectionModel(ListSelectionModel newModel) {
if (newModel == null) {
throw new IllegalArgumentException("Cannot set a null SelectionModel");
}
ListSelectionModel oldModel = selectionModel;
if (newModel != oldModel) {
if (oldModel != null) {
oldModel.removeListSelectionListener(this);
}
selectionModel= newModel;
newModel.addListSelectionListener(this);
}
}
/** {@collect.stats}
* Returns the <code>ListSelectionModel</code> that is used to
* maintain column selection state.
*
* @return the object that provides column selection state. Or
* <code>null</code> if row selection is not allowed.
* @see #setSelectionModel
*/
public ListSelectionModel getSelectionModel() {
return selectionModel;
}
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Sets whether column selection is allowed. The default is false.
* @param flag true if column selection will be allowed, false otherwise
*/
public void setColumnSelectionAllowed(boolean flag) {
columnSelectionAllowed = flag;
}
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Returns true if column selection is allowed, otherwise false.
* The default is false.
* @return the <code>columnSelectionAllowed</code> property
*/
public boolean getColumnSelectionAllowed() {
return columnSelectionAllowed;
}
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Returns an array of selected columns. If <code>selectionModel</code>
* is <code>null</code>, returns an empty array.
* @return an array of selected columns or an empty array if nothing
* is selected or the <code>selectionModel</code> is
* <code>null</code>
*/
public int[] getSelectedColumns() {
if (selectionModel != null) {
int iMin = selectionModel.getMinSelectionIndex();
int iMax = selectionModel.getMaxSelectionIndex();
if ((iMin == -1) || (iMax == -1)) {
return new int[0];
}
int[] rvTmp = new int[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (selectionModel.isSelectedIndex(i)) {
rvTmp[n++] = i;
}
}
int[] rv = new int[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
return new int[0];
}
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Returns the number of columns selected.
* @return the number of columns selected
*/
public int getSelectedColumnCount() {
if (selectionModel != null) {
int iMin = selectionModel.getMinSelectionIndex();
int iMax = selectionModel.getMaxSelectionIndex();
int count = 0;
for(int i = iMin; i <= iMax; i++) {
if (selectionModel.isSelectedIndex(i)) {
count++;
}
}
return count;
}
return 0;
}
//
// Listener Support Methods
//
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Adds a listener for table column model events.
* @param x a <code>TableColumnModelListener</code> object
*/
public void addColumnModelListener(TableColumnModelListener x) {
listenerList.add(TableColumnModelListener.class, x);
}
// implements javax.swing.table.TableColumnModel
/** {@collect.stats}
* Removes a listener for table column model events.
* @param x a <code>TableColumnModelListener</code> object
*/
public void removeColumnModelListener(TableColumnModelListener x) {
listenerList.remove(TableColumnModelListener.class, x);
}
/** {@collect.stats}
* Returns an array of all the column model listeners
* registered on this model.
*
* @return all of this default table column model's <code>ColumnModelListener</code>s
* or an empty
* array if no column model listeners are currently registered
*
* @see #addColumnModelListener
* @see #removeColumnModelListener
*
* @since 1.4
*/
public TableColumnModelListener[] getColumnModelListeners() {
return (TableColumnModelListener[])listenerList.getListeners(
TableColumnModelListener.class);
}
//
// Event firing methods
//
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @param e the event received
* @see EventListenerList
*/
protected void fireColumnAdded(TableColumnModelEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableColumnModelListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ChangeEvent(this);
((TableColumnModelListener)listeners[i+1]).
columnAdded(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @param e the event received
* @see EventListenerList
*/
protected void fireColumnRemoved(TableColumnModelEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableColumnModelListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ChangeEvent(this);
((TableColumnModelListener)listeners[i+1]).
columnRemoved(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @param e the event received
* @see EventListenerList
*/
protected void fireColumnMoved(TableColumnModelEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableColumnModelListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ChangeEvent(this);
((TableColumnModelListener)listeners[i+1]).
columnMoved(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @param e the event received
* @see EventListenerList
*/
protected void fireColumnSelectionChanged(ListSelectionEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableColumnModelListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ChangeEvent(this);
((TableColumnModelListener)listeners[i+1]).
columnSelectionChanged(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @see EventListenerList
*/
protected void fireColumnMarginChanged() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableColumnModelListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((TableColumnModelListener)listeners[i+1]).
columnMarginChanged(changeEvent);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
*
* You can specify the <code>listenerType</code> argument
* with a class literal,
* such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>DefaultTableColumnModel</code> <code>m</code>
* for its column model listeners with the following code:
*
* <pre>ColumnModelListener[] cmls = (ColumnModelListener[])(m.getListeners(ColumnModelListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getColumnModelListeners
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
//
// Implementing the PropertyChangeListener interface
//
// PENDING(alan)
// implements java.beans.PropertyChangeListener
/** {@collect.stats}
* Property Change Listener change method. Used to track changes
* to the column width or preferred column width.
*
* @param evt <code>PropertyChangeEvent</code>
*/
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if (name == "width" || name == "preferredWidth") {
invalidateWidthCache();
// This is a misnomer, we're using this method
// simply to cause a relayout.
fireColumnMarginChanged();
}
}
//
// Implementing ListSelectionListener interface
//
// implements javax.swing.event.ListSelectionListener
/** {@collect.stats}
* A <code>ListSelectionListener</code> that forwards
* <code>ListSelectionEvents</code> when there is a column
* selection change.
*
* @param e the change event
*/
public void valueChanged(ListSelectionEvent e) {
fireColumnSelectionChanged(e);
}
//
// Protected Methods
//
/** {@collect.stats}
* Creates a new default list selection model.
*/
protected ListSelectionModel createSelectionModel() {
return new DefaultListSelectionModel();
}
/** {@collect.stats}
* Recalculates the total combined width of all columns. Updates the
* <code>totalColumnWidth</code> property.
*/
protected void recalcWidthCache() {
Enumeration enumeration = getColumns();
totalColumnWidth = 0;
while (enumeration.hasMoreElements()) {
totalColumnWidth += ((TableColumn)enumeration.nextElement()).getWidth();
}
}
private void invalidateWidthCache() {
totalColumnWidth = -1;
}
} // End of class DefaultTableColumnModel
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import java.io.Serializable;
import java.util.Vector;
import java.util.Enumeration;
import javax.swing.event.TableModelEvent;
/** {@collect.stats}
* This is an implementation of <code>TableModel</code> that
* uses a <code>Vector</code> of <code>Vectors</code> to store the
* cell value objects.
* <p>
* <strong>Warning:</strong> <code>DefaultTableModel</code> returns a
* column class of <code>Object</code>. When
* <code>DefaultTableModel</code> is used with a
* <code>TableRowSorter</code> this will result in extensive use of
* <code>toString</code>, which for non-<code>String</code> data types
* is expensive. If you use <code>DefaultTableModel</code> with a
* <code>TableRowSorter</code> you are strongly encouraged to override
* <code>getColumnClass</code> to return the appropriate type.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Philip Milne
*
* @see TableModel
* @see #getDataVector
*/
public class DefaultTableModel extends AbstractTableModel implements Serializable {
//
// Instance Variables
//
/** {@collect.stats}
* The <code>Vector</code> of <code>Vectors</code> of
* <code>Object</code> values.
*/
protected Vector dataVector;
/** {@collect.stats} The <code>Vector</code> of column identifiers. */
protected Vector columnIdentifiers;
//
// Constructors
//
/** {@collect.stats}
* Constructs a default <code>DefaultTableModel</code>
* which is a table of zero columns and zero rows.
*/
public DefaultTableModel() {
this(0, 0);
}
private static Vector newVector(int size) {
Vector v = new Vector(size);
v.setSize(size);
return v;
}
/** {@collect.stats}
* Constructs a <code>DefaultTableModel</code> with
* <code>rowCount</code> and <code>columnCount</code> of
* <code>null</code> object values.
*
* @param rowCount the number of rows the table holds
* @param columnCount the number of columns the table holds
*
* @see #setValueAt
*/
public DefaultTableModel(int rowCount, int columnCount) {
this(newVector(columnCount), rowCount);
}
/** {@collect.stats}
* Constructs a <code>DefaultTableModel</code> with as many columns
* as there are elements in <code>columnNames</code>
* and <code>rowCount</code> of <code>null</code>
* object values. Each column's name will be taken from
* the <code>columnNames</code> vector.
*
* @param columnNames <code>vector</code> containing the names
* of the new columns; if this is
* <code>null</code> then the model has no columns
* @param rowCount the number of rows the table holds
* @see #setDataVector
* @see #setValueAt
*/
public DefaultTableModel(Vector columnNames, int rowCount) {
setDataVector(newVector(rowCount), columnNames);
}
/** {@collect.stats}
* Constructs a <code>DefaultTableModel</code> with as many
* columns as there are elements in <code>columnNames</code>
* and <code>rowCount</code> of <code>null</code>
* object values. Each column's name will be taken from
* the <code>columnNames</code> array.
*
* @param columnNames <code>array</code> containing the names
* of the new columns; if this is
* <code>null</code> then the model has no columns
* @param rowCount the number of rows the table holds
* @see #setDataVector
* @see #setValueAt
*/
public DefaultTableModel(Object[] columnNames, int rowCount) {
this(convertToVector(columnNames), rowCount);
}
/** {@collect.stats}
* Constructs a <code>DefaultTableModel</code> and initializes the table
* by passing <code>data</code> and <code>columnNames</code>
* to the <code>setDataVector</code> method.
*
* @param data the data of the table, a <code>Vector</code>
* of <code>Vector</code>s of <code>Object</code>
* values
* @param columnNames <code>vector</code> containing the names
* of the new columns
* @see #getDataVector
* @see #setDataVector
*/
public DefaultTableModel(Vector data, Vector columnNames) {
setDataVector(data, columnNames);
}
/** {@collect.stats}
* Constructs a <code>DefaultTableModel</code> and initializes the table
* by passing <code>data</code> and <code>columnNames</code>
* to the <code>setDataVector</code>
* method. The first index in the <code>Object[][]</code> array is
* the row index and the second is the column index.
*
* @param data the data of the table
* @param columnNames the names of the columns
* @see #getDataVector
* @see #setDataVector
*/
public DefaultTableModel(Object[][] data, Object[] columnNames) {
setDataVector(data, columnNames);
}
/** {@collect.stats}
* Returns the <code>Vector</code> of <code>Vectors</code>
* that contains the table's
* data values. The vectors contained in the outer vector are
* each a single row of values. In other words, to get to the cell
* at row 1, column 5: <p>
*
* <code>((Vector)getDataVector().elementAt(1)).elementAt(5);</code><p>
*
* @return the vector of vectors containing the tables data values
*
* @see #newDataAvailable
* @see #newRowsAdded
* @see #setDataVector
*/
public Vector getDataVector() {
return dataVector;
}
private static Vector nonNullVector(Vector v) {
return (v != null) ? v : new Vector();
}
/** {@collect.stats}
* Replaces the current <code>dataVector</code> instance variable
* with the new <code>Vector</code> of rows, <code>dataVector</code>.
* Each row is represented in <code>dataVector</code> as a
* <code>Vector</code> of <code>Object</code> values.
* <code>columnIdentifiers</code> are the names of the new
* columns. The first name in <code>columnIdentifiers</code> is
* mapped to column 0 in <code>dataVector</code>. Each row in
* <code>dataVector</code> is adjusted to match the number of
* columns in <code>columnIdentifiers</code>
* either by truncating the <code>Vector</code> if it is too long,
* or adding <code>null</code> values if it is too short.
* <p>Note that passing in a <code>null</code> value for
* <code>dataVector</code> results in unspecified behavior,
* an possibly an exception.
*
* @param dataVector the new data vector
* @param columnIdentifiers the names of the columns
* @see #getDataVector
*/
public void setDataVector(Vector dataVector, Vector columnIdentifiers) {
this.dataVector = nonNullVector(dataVector);
this.columnIdentifiers = nonNullVector(columnIdentifiers);
justifyRows(0, getRowCount());
fireTableStructureChanged();
}
/** {@collect.stats}
* Replaces the value in the <code>dataVector</code> instance
* variable with the values in the array <code>dataVector</code>.
* The first index in the <code>Object[][]</code>
* array is the row index and the second is the column index.
* <code>columnIdentifiers</code> are the names of the new columns.
*
* @param dataVector the new data vector
* @param columnIdentifiers the names of the columns
* @see #setDataVector(Vector, Vector)
*/
public void setDataVector(Object[][] dataVector, Object[] columnIdentifiers) {
setDataVector(convertToVector(dataVector), convertToVector(columnIdentifiers));
}
/** {@collect.stats}
* Equivalent to <code>fireTableChanged</code>.
*
* @param event the change event
*
*/
public void newDataAvailable(TableModelEvent event) {
fireTableChanged(event);
}
//
// Manipulating rows
//
private void justifyRows(int from, int to) {
// Sometimes the DefaultTableModel is subclassed
// instead of the AbstractTableModel by mistake.
// Set the number of rows for the case when getRowCount
// is overridden.
dataVector.setSize(getRowCount());
for (int i = from; i < to; i++) {
if (dataVector.elementAt(i) == null) {
dataVector.setElementAt(new Vector(), i);
}
((Vector)dataVector.elementAt(i)).setSize(getColumnCount());
}
}
/** {@collect.stats}
* Ensures that the new rows have the correct number of columns.
* This is accomplished by using the <code>setSize</code> method in
* <code>Vector</code> which truncates vectors
* which are too long, and appends <code>null</code>s if they
* are too short.
* This method also sends out a <code>tableChanged</code>
* notification message to all the listeners.
*
* @param e this <code>TableModelEvent</code> describes
* where the rows were added.
* If <code>null</code> it assumes
* all the rows were newly added
* @see #getDataVector
*/
public void newRowsAdded(TableModelEvent e) {
justifyRows(e.getFirstRow(), e.getLastRow() + 1);
fireTableChanged(e);
}
/** {@collect.stats}
* Equivalent to <code>fireTableChanged</code>.
*
* @param event the change event
*
*/
public void rowsRemoved(TableModelEvent event) {
fireTableChanged(event);
}
/** {@collect.stats}
* Obsolete as of Java 2 platform v1.3. Please use <code>setRowCount</code> instead.
*/
/*
* Sets the number of rows in the model. If the new size is greater
* than the current size, new rows are added to the end of the model
* If the new size is less than the current size, all
* rows at index <code>rowCount</code> and greater are discarded. <p>
*
* @param rowCount the new number of rows
* @see #setRowCount
*/
public void setNumRows(int rowCount) {
int old = getRowCount();
if (old == rowCount) {
return;
}
dataVector.setSize(rowCount);
if (rowCount <= old) {
fireTableRowsDeleted(rowCount, old-1);
}
else {
justifyRows(old, rowCount);
fireTableRowsInserted(old, rowCount-1);
}
}
/** {@collect.stats}
* Sets the number of rows in the model. If the new size is greater
* than the current size, new rows are added to the end of the model
* If the new size is less than the current size, all
* rows at index <code>rowCount</code> and greater are discarded. <p>
*
* @see #setColumnCount
* @since 1.3
*/
public void setRowCount(int rowCount) {
setNumRows(rowCount);
}
/** {@collect.stats}
* Adds a row to the end of the model. The new row will contain
* <code>null</code> values unless <code>rowData</code> is specified.
* Notification of the row being added will be generated.
*
* @param rowData optional data of the row being added
*/
public void addRow(Vector rowData) {
insertRow(getRowCount(), rowData);
}
/** {@collect.stats}
* Adds a row to the end of the model. The new row will contain
* <code>null</code> values unless <code>rowData</code> is specified.
* Notification of the row being added will be generated.
*
* @param rowData optional data of the row being added
*/
public void addRow(Object[] rowData) {
addRow(convertToVector(rowData));
}
/** {@collect.stats}
* Inserts a row at <code>row</code> in the model. The new row
* will contain <code>null</code> values unless <code>rowData</code>
* is specified. Notification of the row being added will be generated.
*
* @param row the row index of the row to be inserted
* @param rowData optional data of the row being added
* @exception ArrayIndexOutOfBoundsException if the row was invalid
*/
public void insertRow(int row, Vector rowData) {
dataVector.insertElementAt(rowData, row);
justifyRows(row, row+1);
fireTableRowsInserted(row, row);
}
/** {@collect.stats}
* Inserts a row at <code>row</code> in the model. The new row
* will contain <code>null</code> values unless <code>rowData</code>
* is specified. Notification of the row being added will be generated.
*
* @param row the row index of the row to be inserted
* @param rowData optional data of the row being added
* @exception ArrayIndexOutOfBoundsException if the row was invalid
*/
public void insertRow(int row, Object[] rowData) {
insertRow(row, convertToVector(rowData));
}
private static int gcd(int i, int j) {
return (j == 0) ? i : gcd(j, i%j);
}
private static void rotate(Vector v, int a, int b, int shift) {
int size = b - a;
int r = size - shift;
int g = gcd(size, r);
for(int i = 0; i < g; i++) {
int to = i;
Object tmp = v.elementAt(a + to);
for(int from = (to + r) % size; from != i; from = (to + r) % size) {
v.setElementAt(v.elementAt(a + from), a + to);
to = from;
}
v.setElementAt(tmp, a + to);
}
}
/** {@collect.stats}
* Moves one or more rows from the inclusive range <code>start</code> to
* <code>end</code> to the <code>to</code> position in the model.
* After the move, the row that was at index <code>start</code>
* will be at index <code>to</code>.
* This method will send a <code>tableChanged</code> notification
* message to all the listeners. <p>
*
* <pre>
* Examples of moves:
* <p>
* 1. moveRow(1,3,5);
* a|B|C|D|e|f|g|h|i|j|k - before
* a|e|f|g|h|B|C|D|i|j|k - after
* <p>
* 2. moveRow(6,7,1);
* a|b|c|d|e|f|G|H|i|j|k - before
* a|G|H|b|c|d|e|f|i|j|k - after
* <p>
* </pre>
*
* @param start the starting row index to be moved
* @param end the ending row index to be moved
* @param to the destination of the rows to be moved
* @exception ArrayIndexOutOfBoundsException if any of the elements
* would be moved out of the table's range
*
*/
public void moveRow(int start, int end, int to) {
int shift = to - start;
int first, last;
if (shift < 0) {
first = to;
last = end;
}
else {
first = start;
last = to + end - start;
}
rotate(dataVector, first, last + 1, shift);
fireTableRowsUpdated(first, last);
}
/** {@collect.stats}
* Removes the row at <code>row</code> from the model. Notification
* of the row being removed will be sent to all the listeners.
*
* @param row the row index of the row to be removed
* @exception ArrayIndexOutOfBoundsException if the row was invalid
*/
public void removeRow(int row) {
dataVector.removeElementAt(row);
fireTableRowsDeleted(row, row);
}
//
// Manipulating columns
//
/** {@collect.stats}
* Replaces the column identifiers in the model. If the number of
* <code>newIdentifier</code>s is greater than the current number
* of columns, new columns are added to the end of each row in the model.
* If the number of <code>newIdentifier</code>s is less than the current
* number of columns, all the extra columns at the end of a row are
* discarded. <p>
*
* @param columnIdentifiers vector of column identifiers. If
* <code>null</code>, set the model
* to zero columns
* @see #setNumRows
*/
public void setColumnIdentifiers(Vector columnIdentifiers) {
setDataVector(dataVector, columnIdentifiers);
}
/** {@collect.stats}
* Replaces the column identifiers in the model. If the number of
* <code>newIdentifier</code>s is greater than the current number
* of columns, new columns are added to the end of each row in the model.
* If the number of <code>newIdentifier</code>s is less than the current
* number of columns, all the extra columns at the end of a row are
* discarded. <p>
*
* @param newIdentifiers array of column identifiers.
* If <code>null</code>, set
* the model to zero columns
* @see #setNumRows
*/
public void setColumnIdentifiers(Object[] newIdentifiers) {
setColumnIdentifiers(convertToVector(newIdentifiers));
}
/** {@collect.stats}
* Sets the number of columns in the model. If the new size is greater
* than the current size, new columns are added to the end of the model
* with <code>null</code> cell values.
* If the new size is less than the current size, all columns at index
* <code>columnCount</code> and greater are discarded.
*
* @param columnCount the new number of columns in the model
*
* @see #setColumnCount
* @since 1.3
*/
public void setColumnCount(int columnCount) {
columnIdentifiers.setSize(columnCount);
justifyRows(0, getRowCount());
fireTableStructureChanged();
}
/** {@collect.stats}
* Adds a column to the model. The new column will have the
* identifier <code>columnName</code>, which may be null. This method
* will send a
* <code>tableChanged</code> notification message to all the listeners.
* This method is a cover for <code>addColumn(Object, Vector)</code> which
* uses <code>null</code> as the data vector.
*
* @param columnName the identifier of the column being added
*/
public void addColumn(Object columnName) {
addColumn(columnName, (Vector)null);
}
/** {@collect.stats}
* Adds a column to the model. The new column will have the
* identifier <code>columnName</code>, which may be null.
* <code>columnData</code> is the
* optional vector of data for the column. If it is <code>null</code>
* the column is filled with <code>null</code> values. Otherwise,
* the new data will be added to model starting with the first
* element going to row 0, etc. This method will send a
* <code>tableChanged</code> notification message to all the listeners.
*
* @param columnName the identifier of the column being added
* @param columnData optional data of the column being added
*/
public void addColumn(Object columnName, Vector columnData) {
columnIdentifiers.addElement(columnName);
if (columnData != null) {
int columnSize = columnData.size();
if (columnSize > getRowCount()) {
dataVector.setSize(columnSize);
}
justifyRows(0, getRowCount());
int newColumn = getColumnCount() - 1;
for(int i = 0; i < columnSize; i++) {
Vector row = (Vector)dataVector.elementAt(i);
row.setElementAt(columnData.elementAt(i), newColumn);
}
}
else {
justifyRows(0, getRowCount());
}
fireTableStructureChanged();
}
/** {@collect.stats}
* Adds a column to the model. The new column will have the
* identifier <code>columnName</code>. <code>columnData</code> is the
* optional array of data for the column. If it is <code>null</code>
* the column is filled with <code>null</code> values. Otherwise,
* the new data will be added to model starting with the first
* element going to row 0, etc. This method will send a
* <code>tableChanged</code> notification message to all the listeners.
*
* @see #addColumn(Object, Vector)
*/
public void addColumn(Object columnName, Object[] columnData) {
addColumn(columnName, convertToVector(columnData));
}
//
// Implementing the TableModel interface
//
/** {@collect.stats}
* Returns the number of rows in this data table.
* @return the number of rows in the model
*/
public int getRowCount() {
return dataVector.size();
}
/** {@collect.stats}
* Returns the number of columns in this data table.
* @return the number of columns in the model
*/
public int getColumnCount() {
return columnIdentifiers.size();
}
/** {@collect.stats}
* Returns the column name.
*
* @return a name for this column using the string value of the
* appropriate member in <code>columnIdentifiers</code>.
* If <code>columnIdentifiers</code> does not have an entry
* for this index, returns the default
* name provided by the superclass.
*/
public String getColumnName(int column) {
Object id = null;
// This test is to cover the case when
// getColumnCount has been subclassed by mistake ...
if (column < columnIdentifiers.size() && (column >= 0)) {
id = columnIdentifiers.elementAt(column);
}
return (id == null) ? super.getColumnName(column)
: id.toString();
}
/** {@collect.stats}
* Returns true regardless of parameter values.
*
* @param row the row whose value is to be queried
* @param column the column whose value is to be queried
* @return true
* @see #setValueAt
*/
public boolean isCellEditable(int row, int column) {
return true;
}
/** {@collect.stats}
* Returns an attribute value for the cell at <code>row</code>
* and <code>column</code>.
*
* @param row the row whose value is to be queried
* @param column the column whose value is to be queried
* @return the value Object at the specified cell
* @exception ArrayIndexOutOfBoundsException if an invalid row or
* column was given
*/
public Object getValueAt(int row, int column) {
Vector rowVector = (Vector)dataVector.elementAt(row);
return rowVector.elementAt(column);
}
/** {@collect.stats}
* Sets the object value for the cell at <code>column</code> and
* <code>row</code>. <code>aValue</code> is the new value. This method
* will generate a <code>tableChanged</code> notification.
*
* @param aValue the new value; this can be null
* @param row the row whose value is to be changed
* @param column the column whose value is to be changed
* @exception ArrayIndexOutOfBoundsException if an invalid row or
* column was given
*/
public void setValueAt(Object aValue, int row, int column) {
Vector rowVector = (Vector)dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
}
//
// Protected Methods
//
/** {@collect.stats}
* Returns a vector that contains the same objects as the array.
* @param anArray the array to be converted
* @return the new vector; if <code>anArray</code> is <code>null</code>,
* returns <code>null</code>
*/
protected static Vector convertToVector(Object[] anArray) {
if (anArray == null) {
return null;
}
Vector v = new Vector(anArray.length);
for (int i=0; i < anArray.length; i++) {
v.addElement(anArray[i]);
}
return v;
}
/** {@collect.stats}
* Returns a vector of vectors that contains the same objects as the array.
* @param anArray the double array to be converted
* @return the new vector of vectors; if <code>anArray</code> is
* <code>null</code>, returns <code>null</code>
*/
protected static Vector convertToVector(Object[][] anArray) {
if (anArray == null) {
return null;
}
Vector v = new Vector(anArray.length);
for (int i=0; i < anArray.length; i++) {
v.addElement(convertToVector(anArray[i]));
}
return v;
}
} // End of class DefaultTableModel
|
Java
|
/*
* Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.Component;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.Serializable;
import sun.swing.DefaultLookup;
/** {@collect.stats}
* The standard class for rendering (displaying) individual cells
* in a <code>JTable</code>.
* <p>
*
* <strong><a name="override">Implementation Note:</a></strong>
* This class inherits from <code>JLabel</code>, a standard component class.
* However <code>JTable</code> employs a unique mechanism for rendering
* its cells and therefore requires some slightly modified behavior
* from its cell renderer.
* The table class defines a single cell renderer and uses it as a
* as a rubber-stamp for rendering all cells in the table;
* it renders the first cell,
* changes the contents of that cell renderer,
* shifts the origin to the new location, re-draws it, and so on.
* The standard <code>JLabel</code> component was not
* designed to be used this way and we want to avoid
* triggering a <code>revalidate</code> each time the
* cell is drawn. This would greatly decrease performance because the
* <code>revalidate</code> message would be
* passed up the hierarchy of the container to determine whether any other
* components would be affected.
* As the renderer is only parented for the lifetime of a painting operation
* we similarly want to avoid the overhead associated with walking the
* hierarchy for painting operations.
* So this class
* overrides the <code>validate</code>, <code>invalidate</code>,
* <code>revalidate</code>, <code>repaint</code>, and
* <code>firePropertyChange</code> methods to be
* no-ops and override the <code>isOpaque</code> method solely to improve
* performance. If you write your own renderer,
* please keep this performance consideration in mind.
* <p>
*
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Philip Milne
* @see JTable
*/
public class DefaultTableCellRenderer extends JLabel
implements TableCellRenderer, Serializable
{
/** {@collect.stats}
* An empty <code>Border</code>. This field might not be used. To change the
* <code>Border</code> used by this renderer override the
* <code>getTableCellRendererComponent</code> method and set the border
* of the returned component directly.
*/
private static final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
private static final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
protected static Border noFocusBorder = DEFAULT_NO_FOCUS_BORDER;
// We need a place to store the color the JLabel should be returned
// to after its foreground and background colors have been set
// to the selection background color.
// These ivars will be made protected when their names are finalized.
private Color unselectedForeground;
private Color unselectedBackground;
/** {@collect.stats}
* Creates a default table cell renderer.
*/
public DefaultTableCellRenderer() {
super();
setOpaque(true);
setBorder(getNoFocusBorder());
setName("Table.cellRenderer");
}
private Border getNoFocusBorder() {
Border border = DefaultLookup.getBorder(this, ui, "Table.cellNoFocusBorder");
if (System.getSecurityManager() != null) {
if (border != null) return border;
return SAFE_NO_FOCUS_BORDER;
} else if (border != null) {
if (noFocusBorder == null || noFocusBorder == DEFAULT_NO_FOCUS_BORDER) {
return border;
}
}
return noFocusBorder;
}
/** {@collect.stats}
* Overrides <code>JComponent.setForeground</code> to assign
* the unselected-foreground color to the specified color.
*
* @param c set the foreground color to this value
*/
public void setForeground(Color c) {
super.setForeground(c);
unselectedForeground = c;
}
/** {@collect.stats}
* Overrides <code>JComponent.setBackground</code> to assign
* the unselected-background color to the specified color.
*
* @param c set the background color to this value
*/
public void setBackground(Color c) {
super.setBackground(c);
unselectedBackground = c;
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the look and feel
* [L&F] has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
super.updateUI();
setForeground(null);
setBackground(null);
}
// implements javax.swing.table.TableCellRenderer
/** {@collect.stats}
*
* Returns the default table cell renderer.
* <p>
* During a printing operation, this method will be called with
* <code>isSelected</code> and <code>hasFocus</code> values of
* <code>false</code> to prevent selection and focus from appearing
* in the printed output. To do other customization based on whether
* or not the table is being printed, check the return value from
* {@link javax.swing.JComponent#isPaintingForPrint()}.
*
* @param table the <code>JTable</code>
* @param value the value to assign to the cell at
* <code>[row, column]</code>
* @param isSelected true if cell is selected
* @param hasFocus true if cell has focus
* @param row the row of the cell to render
* @param column the column of the cell to render
* @return the default table cell renderer
* @see javax.swing.JComponent#isPaintingForPrint()
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Color fg = null;
Color bg = null;
JTable.DropLocation dropLocation = table.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsertRow()
&& !dropLocation.isInsertColumn()
&& dropLocation.getRow() == row
&& dropLocation.getColumn() == column) {
fg = DefaultLookup.getColor(this, ui, "Table.dropCellForeground");
bg = DefaultLookup.getColor(this, ui, "Table.dropCellBackground");
isSelected = true;
}
if (isSelected) {
super.setForeground(fg == null ? table.getSelectionForeground()
: fg);
super.setBackground(bg == null ? table.getSelectionBackground()
: bg);
} else {
Color background = unselectedBackground != null
? unselectedBackground
: table.getBackground();
if (background == null || background instanceof javax.swing.plaf.UIResource) {
Color alternateColor = DefaultLookup.getColor(this, ui, "Table.alternateRowColor");
if (alternateColor != null && row % 2 != 0) {
background = alternateColor;
}
}
super.setForeground(unselectedForeground != null
? unselectedForeground
: table.getForeground());
super.setBackground(background);
}
setFont(table.getFont());
if (hasFocus) {
Border border = null;
if (isSelected) {
border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
}
setBorder(border);
if (!isSelected && table.isCellEditable(row, column)) {
Color col;
col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
if (col != null) {
super.setForeground(col);
}
col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
if (col != null) {
super.setBackground(col);
}
}
} else {
setBorder(getNoFocusBorder());
}
setValue(value);
return this;
}
/*
* The following methods are overridden as a performance measure to
* to prune code-paths are often called in the case of renders
* but which we know are unnecessary. Great care should be taken
* when writing your own renderer to weigh the benefits and
* drawbacks of overriding methods like these.
*/
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public boolean isOpaque() {
Color back = getBackground();
Component p = getParent();
if (p != null) {
p = p.getParent();
}
// p should now be the JTable.
boolean colorMatch = (back != null) && (p != null) &&
back.equals(p.getBackground()) &&
p.isOpaque();
return !colorMatch && super.isOpaque();
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
public void invalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void validate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void revalidate() {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void repaint(long tm, int x, int y, int width, int height) {}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void repaint(Rectangle r) { }
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*
* @since 1.5
*/
public void repaint() {
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
// Strings get interned...
if (propertyName=="text"
|| propertyName == "labelFor"
|| propertyName == "displayedMnemonic"
|| ((propertyName == "font" || propertyName == "foreground")
&& oldValue != newValue
&& getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) != null)) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
}
/** {@collect.stats}
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { }
/** {@collect.stats}
* Sets the <code>String</code> object for the cell being rendered to
* <code>value</code>.
*
* @param value the string value for this cell; if value is
* <code>null</code> it sets the text value to an empty string
* @see JLabel#setText
*
*/
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
}
/** {@collect.stats}
* A subclass of <code>DefaultTableCellRenderer</code> that
* implements <code>UIResource</code>.
* <code>DefaultTableCellRenderer</code> doesn't implement
* <code>UIResource</code>
* directly so that applications can safely override the
* <code>cellRenderer</code> property with
* <code>DefaultTableCellRenderer</code> subclasses.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public static class UIResource extends DefaultTableCellRenderer
implements javax.swing.plaf.UIResource
{
}
}
|
Java
|
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.table;
import java.awt.Component;
import javax.swing.*;
/** {@collect.stats}
* This interface defines the method required by any object that
* would like to be a renderer for cells in a <code>JTable</code>.
*
* @author Alan Chung
*/
public interface TableCellRenderer {
/** {@collect.stats}
* Returns the component used for drawing the cell. This method is
* used to configure the renderer appropriately before drawing.
* <p>
* The <code>TableCellRenderer</code> is also responsible for rendering the
* the cell representing the table's current DnD drop location if
* it has one. If this renderer cares about rendering
* the DnD drop location, it should query the table directly to
* see if the given row and column represent the drop location:
* <pre>
* JTable.DropLocation dropLocation = table.getDropLocation();
* if (dropLocation != null
* && !dropLocation.isInsertRow()
* && !dropLocation.isInsertColumn()
* && dropLocation.getRow() == row
* && dropLocation.getColumn() == column) {
*
* // this cell represents the current drop location
* // so render it specially, perhaps with a different color
* }
* </pre>
* <p>
* During a printing operation, this method will be called with
* <code>isSelected</code> and <code>hasFocus</code> values of
* <code>false</code> to prevent selection and focus from appearing
* in the printed output. To do other customization based on whether
* or not the table is being printed, check the return value from
* {@link javax.swing.JComponent#isPaintingForPrint()}.
*
* @param table the <code>JTable</code> that is asking the
* renderer to draw; can be <code>null</code>
* @param value the value of the cell to be rendered. It is
* up to the specific renderer to interpret
* and draw the value. For example, if
* <code>value</code>
* is the string "true", it could be rendered as a
* string or it could be rendered as a check
* box that is checked. <code>null</code> is a
* valid value
* @param isSelected true if the cell is to be rendered with the
* selection highlighted; otherwise false
* @param hasFocus if true, render cell appropriately. For
* example, put a special border on the cell, if
* the cell can be edited, render in the color used
* to indicate editing
* @param row the row index of the cell being drawn. When
* drawing the header, the value of
* <code>row</code> is -1
* @param column the column index of the cell being drawn
* @see javax.swing.JComponent#isPaintingForPrint()
*/
Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column);
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* An implementation of a radio button -- an item that can be selected or
* deselected, and which displays its state to the user.
* Used with a {@link ButtonGroup} object to create a group of buttons
* in which only one button at a time can be selected. (Create a ButtonGroup
* object and use its <code>add</code> method to include the JRadioButton objects
* in the group.)
* <blockquote>
* <strong>Note:</strong>
* The ButtonGroup object is a logical grouping -- not a physical grouping.
* To create a button panel, you should still create a {@link JPanel} or similar
* container-object and add a {@link javax.swing.border.Border} to it to set it off from surrounding
* components.
* </blockquote>
* <p>
* Buttons can be configured, and to some degree controlled, by
* <code><a href="Action.html">Action</a></code>s. Using an
* <code>Action</code> with a button has many benefits beyond directly
* configuring a button. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details, and you can find more information in <a
* href="http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html">How
* to Use Actions</a>, a section in <em>The Java Tutorial</em>.
* <p>
* See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/button.html">How to Use Buttons, Check Boxes, and Radio Buttons</a>
* in <em>The Java Tutorial</em>
* for further documentation.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A component which can display it's state as selected or deselected.
*
* @see ButtonGroup
* @see JCheckBox
* @author Jeff Dinkins
*/
public class JRadioButton extends JToggleButton implements Accessible {
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "RadioButtonUI";
/** {@collect.stats}
* Creates an initially unselected radio button
* with no set text.
*/
public JRadioButton () {
this(null, null, false);
}
/** {@collect.stats}
* Creates an initially unselected radio button
* with the specified image but no text.
*
* @param icon the image that the button should display
*/
public JRadioButton(Icon icon) {
this(null, icon, false);
}
/** {@collect.stats}
* Creates a radiobutton where properties are taken from the
* Action supplied.
*
* @since 1.3
*/
public JRadioButton(Action a) {
this();
setAction(a);
}
/** {@collect.stats}
* Creates a radio button with the specified image
* and selection state, but no text.
*
* @param icon the image that the button should display
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JRadioButton(Icon icon, boolean selected) {
this(null, icon, selected);
}
/** {@collect.stats}
* Creates an unselected radio button with the specified text.
*
* @param text the string displayed on the radio button
*/
public JRadioButton (String text) {
this(text, null, false);
}
/** {@collect.stats}
* Creates a radio button with the specified text
* and selection state.
*
* @param text the string displayed on the radio button
* @param selected if true, the button is initially selected;
* otherwise, the button is initially unselected
*/
public JRadioButton (String text, boolean selected) {
this(text, null, selected);
}
/** {@collect.stats}
* Creates a radio button that has the specified text and image,
* and that is initially unselected.
*
* @param text the string displayed on the radio button
* @param icon the image that the button should display
*/
public JRadioButton(String text, Icon icon) {
this(text, icon, false);
}
/** {@collect.stats}
* Creates a radio button that has the specified text, image,
* and selection state.
*
* @param text the string displayed on the radio button
* @param icon the image that the button should display
*/
public JRadioButton (String text, Icon icon, boolean selected) {
super(text, icon, selected);
setBorderPainted(false);
setHorizontalAlignment(LEADING);
}
/** {@collect.stats}
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ButtonUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the L&F class
* that renders this component.
*
* @return String "RadioButtonUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
* @beaninfo
* expert: true
* description: A string that specifies the name of the L&F class.
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* The icon for radio buttons comes from the look and feel,
* not the Action.
*/
void setIconFromAction(Action a) {
}
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this JRadioButton. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JRadioButton.
*/
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JRadioButton.
* For JRadioButtons, the AccessibleContext takes the form of an
* AccessibleJRadioButton.
* A new AccessibleJRadioButton instance is created if necessary.
*
* @return an AccessibleJRadioButton that serves as the
* AccessibleContext of this JRadioButton
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this Button
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJRadioButton();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JRadioButton</code> class. It provides an implementation of the
* Java Accessibility API appropriate to radio button
* user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJRadioButton extends AccessibleJToggleButton {
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.RADIO_BUTTON;
}
} // inner class AccessibleJRadioButton
}
|
Java
|
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.plaf.ComponentUI;
import javax.swing.border.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;
import java.util.Locale;
import java.util.Vector;
import java.util.MissingResourceException;
import java.awt.Font;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Dimension;
import java.lang.reflect.Method;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
import sun.reflect.misc.MethodUtil;
import sun.reflect.misc.ReflectUtil;
import sun.util.CoreResourceBundleControl;
/** {@collect.stats}
* A table of defaults for Swing components. Applications can set/get
* default values via the <code>UIManager</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see UIManager
* @author Hans Muller
*/
public class UIDefaults extends Hashtable<Object,Object>
{
private static final Object PENDING = new String("Pending");
private SwingPropertyChangeSupport changeSupport;
private Vector resourceBundles;
private Locale defaultLocale = Locale.getDefault();
/** {@collect.stats}
* Maps from a Locale to a cached Map of the ResourceBundle. This is done
* so as to avoid an exception being thrown when a value is asked for.
* Access to this should be done while holding a lock on the
* UIDefaults, eg synchronized(this).
*/
private Map resourceCache;
/** {@collect.stats}
* Creates an empty defaults table.
*/
public UIDefaults() {
this(700, .75f);
}
/** {@collect.stats}
* Creates an empty defaults table with the specified initial capacity and
* load factor.
*
* @param initialCapacity the initial capacity of the defaults table
* @param loadFactor the load factor of the defaults table
* @see java.util.Hashtable
* @since 1.6
*/
public UIDefaults(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
resourceCache = new HashMap();
}
/** {@collect.stats}
* Creates a defaults table initialized with the specified
* key/value pairs. For example:
* <pre>
Object[] uiDefaults = {
"Font", new Font("Dialog", Font.BOLD, 12),
"Color", Color.red,
"five", new Integer(5)
}
UIDefaults myDefaults = new UIDefaults(uiDefaults);
* </pre>
* @param keyValueList an array of objects containing the key/value
* pairs
*/
public UIDefaults(Object[] keyValueList) {
super(keyValueList.length / 2);
for(int i = 0; i < keyValueList.length; i += 2) {
super.put(keyValueList[i], keyValueList[i + 1]);
}
}
/** {@collect.stats}
* Returns the value for key. If the value is a
* <code>UIDefaults.LazyValue</code> then the real
* value is computed with <code>LazyValue.createValue()</code>,
* the table entry is replaced, and the real value is returned.
* If the value is an <code>UIDefaults.ActiveValue</code>
* the table entry is not replaced - the value is computed
* with <code>ActiveValue.createValue()</code> for each
* <code>get()</code> call.
*
* If the key is not found in the table then it is searched for in the list
* of resource bundles maintained by this object. The resource bundles are
* searched most recently added first using the locale returned by
* <code>getDefaultLocale</code>. <code>LazyValues</code> and
* <code>ActiveValues</code> are not supported in the resource bundles.
*
* @param key the desired key
* @return the value for <code>key</code>
* @see LazyValue
* @see ActiveValue
* @see java.util.Hashtable#get
* @see #getDefaultLocale
* @see #addResourceBundle
* @since 1.4
*/
public Object get(Object key) {
Object value = getFromHashtable( key );
return (value != null) ? value : getFromResourceBundle(key, null);
}
/** {@collect.stats}
* Looks up up the given key in our Hashtable and resolves LazyValues
* or ActiveValues.
*/
private Object getFromHashtable(Object key) {
/* Quickly handle the common case, without grabbing
* a lock.
*/
Object value = super.get(key);
if ((value != PENDING) &&
!(value instanceof ActiveValue) &&
!(value instanceof LazyValue)) {
return value;
}
/* If the LazyValue for key is being constructed by another
* thread then wait and then return the new value, otherwise drop
* the lock and construct the ActiveValue or the LazyValue.
* We use the special value PENDING to mark LazyValues that
* are being constructed.
*/
synchronized(this) {
value = super.get(key);
if (value == PENDING) {
do {
try {
this.wait();
}
catch (InterruptedException e) {
}
value = super.get(key);
}
while(value == PENDING);
return value;
}
else if (value instanceof LazyValue) {
super.put(key, PENDING);
}
else if (!(value instanceof ActiveValue)) {
return value;
}
}
/* At this point we know that the value of key was
* a LazyValue or an ActiveValue.
*/
if (value instanceof LazyValue) {
try {
/* If an exception is thrown we'll just put the LazyValue
* back in the table.
*/
value = ((LazyValue)value).createValue(this);
}
finally {
synchronized(this) {
if (value == null) {
super.remove(key);
}
else {
super.put(key, value);
}
this.notifyAll();
}
}
}
else {
value = ((ActiveValue)value).createValue(this);
}
return value;
}
/** {@collect.stats}
* Returns the value for key associated with the given locale.
* If the value is a <code>UIDefaults.LazyValue</code> then the real
* value is computed with <code>LazyValue.createValue()</code>,
* the table entry is replaced, and the real value is returned.
* If the value is an <code>UIDefaults.ActiveValue</code>
* the table entry is not replaced - the value is computed
* with <code>ActiveValue.createValue()</code> for each
* <code>get()</code> call.
*
* If the key is not found in the table then it is searched for in the list
* of resource bundles maintained by this object. The resource bundles are
* searched most recently added first using the given locale.
* <code>LazyValues</code> and <code>ActiveValues</code> are not supported
* in the resource bundles.
*
* @param key the desired key
* @param l the desired <code>locale</code>
* @return the value for <code>key</code>
* @see LazyValue
* @see ActiveValue
* @see java.util.Hashtable#get
* @see #addResourceBundle
* @since 1.4
*/
public Object get(Object key, Locale l) {
Object value = getFromHashtable( key );
return (value != null) ? value : getFromResourceBundle(key, l);
}
/** {@collect.stats}
* Looks up given key in our resource bundles.
*/
private Object getFromResourceBundle(Object key, Locale l) {
if( resourceBundles == null ||
resourceBundles.isEmpty() ||
!(key instanceof String) ) {
return null;
}
// A null locale means use the default locale.
if( l == null ) {
if( defaultLocale == null )
return null;
else
l = (Locale)defaultLocale;
}
synchronized(this) {
return getResourceCache(l).get((String)key);
}
}
/** {@collect.stats}
* Returns a Map of the known resources for the given locale.
*/
private Map getResourceCache(Locale l) {
Map values = (Map)resourceCache.get(l);
if (values == null) {
values = new HashMap();
for (int i=resourceBundles.size()-1; i >= 0; i--) {
String bundleName = (String)resourceBundles.get(i);
try {
Control c = CoreResourceBundleControl.getRBControlInstance(bundleName);
ResourceBundle b;
if (c != null) {
b = ResourceBundle.getBundle(bundleName, l, c);
} else {
b = ResourceBundle.getBundle(bundleName, l);
}
Enumeration keys = b.getKeys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if (values.get(key) == null) {
Object value = b.getObject(key);
values.put(key, value);
}
}
} catch( MissingResourceException mre ) {
// Keep looking
}
}
resourceCache.put(l, values);
}
return values;
}
/** {@collect.stats}
* Sets the value of <code>key</code> to <code>value</code> for all locales.
* If <code>key</code> is a string and the new value isn't
* equal to the old one, fire a <code>PropertyChangeEvent</code>.
* If value is <code>null</code>, the key is removed from the table.
*
* @param key the unique <code>Object</code> who's value will be used
* to retrieve the data value associated with it
* @param value the new <code>Object</code> to store as data under
* that key
* @return the previous <code>Object</code> value, or <code>null</code>
* @see #putDefaults
* @see java.util.Hashtable#put
*/
public Object put(Object key, Object value) {
Object oldValue = (value == null) ? super.remove(key) : super.put(key, value);
if (key instanceof String) {
firePropertyChange((String)key, oldValue, value);
}
return oldValue;
}
/** {@collect.stats}
* Puts all of the key/value pairs in the database and
* unconditionally generates one <code>PropertyChangeEvent</code>.
* The events oldValue and newValue will be <code>null</code> and its
* <code>propertyName</code> will be "UIDefaults". The key/value pairs are
* added for all locales.
*
* @param keyValueList an array of key/value pairs
* @see #put
* @see java.util.Hashtable#put
*/
public void putDefaults(Object[] keyValueList) {
for(int i = 0, max = keyValueList.length; i < max; i += 2) {
Object value = keyValueList[i + 1];
if (value == null) {
super.remove(keyValueList[i]);
}
else {
super.put(keyValueList[i], value);
}
}
firePropertyChange("UIDefaults", null, null);
}
/** {@collect.stats}
* If the value of <code>key</code> is a <code>Font</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is a <code>Font</code>,
* return the <code>Font</code> object; otherwise return
* <code>null</code>
*/
public Font getFont(Object key) {
Object value = get(key);
return (value instanceof Font) ? (Font)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is a <code>Font</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is a <code>Font</code>,
* return the <code>Font</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Font getFont(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Font) ? (Font)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is a <code>Color</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is a <code>Color</code>,
* return the <code>Color</code> object; otherwise return
* <code>null</code>
*/
public Color getColor(Object key) {
Object value = get(key);
return (value instanceof Color) ? (Color)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is a <code>Color</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is a <code>Color</code>,
* return the <code>Color</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Color getColor(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Color) ? (Color)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is an <code>Icon</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is an <code>Icon</code>,
* return the <code>Icon</code> object; otherwise return
* <code>null</code>
*/
public Icon getIcon(Object key) {
Object value = get(key);
return (value instanceof Icon) ? (Icon)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is an <code>Icon</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is an <code>Icon</code>,
* return the <code>Icon</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Icon getIcon(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Icon) ? (Icon)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is a <code>Border</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is a <code>Border</code>,
* return the <code>Border</code> object; otherwise return
* <code>null</code>
*/
public Border getBorder(Object key) {
Object value = get(key);
return (value instanceof Border) ? (Border)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is a <code>Border</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is a <code>Border</code>,
* return the <code>Border</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Border getBorder(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Border) ? (Border)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is a <code>String</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is a <code>String</code>,
* return the <code>String</code> object; otherwise return
* <code>null</code>
*/
public String getString(Object key) {
Object value = get(key);
return (value instanceof String) ? (String)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is a <code>String</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired <code>Locale</code>
* @return if the value for <code>key</code> for the given
* <code>Locale</code> is a <code>String</code>,
* return the <code>String</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public String getString(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof String) ? (String)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is an <code>Integer</code> return its
* integer value, otherwise return 0.
* @param key the desired key
* @return if the value for <code>key</code> is an <code>Integer</code>,
* return its value, otherwise return 0
*/
public int getInt(Object key) {
Object value = get(key);
return (value instanceof Integer) ? ((Integer)value).intValue() : 0;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is an <code>Integer</code> return its integer value, otherwise return 0.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is an <code>Integer</code>,
* return its value, otherwise return 0
* @since 1.4
*/
public int getInt(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Integer) ? ((Integer)value).intValue() : 0;
}
/** {@collect.stats}
* If the value of <code>key</code> is boolean, return the
* boolean value, otherwise return false.
*
* @param key an <code>Object</code> specifying the key for the desired boolean value
* @return if the value of <code>key</code> is boolean, return the
* boolean value, otherwise return false.
* @since 1.4
*/
public boolean getBoolean(Object key) {
Object value = get(key);
return (value instanceof Boolean) ? ((Boolean)value).booleanValue() : false;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is boolean, return the boolean value, otherwise return false.
*
* @param key an <code>Object</code> specifying the key for the desired boolean value
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is boolean, return the
* boolean value, otherwise return false.
* @since 1.4
*/
public boolean getBoolean(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Boolean) ? ((Boolean)value).booleanValue() : false;
}
/** {@collect.stats}
* If the value of <code>key</code> is an <code>Insets</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is an <code>Insets</code>,
* return the <code>Insets</code> object; otherwise return
* <code>null</code>
*/
public Insets getInsets(Object key) {
Object value = get(key);
return (value instanceof Insets) ? (Insets)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is an <code>Insets</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is an <code>Insets</code>,
* return the <code>Insets</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Insets getInsets(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Insets) ? (Insets)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> is a <code>Dimension</code> return it,
* otherwise return <code>null</code>.
* @param key the desired key
* @return if the value for <code>key</code> is a <code>Dimension</code>,
* return the <code>Dimension</code> object; otherwise return
* <code>null</code>
*/
public Dimension getDimension(Object key) {
Object value = get(key);
return (value instanceof Dimension) ? (Dimension)value : null;
}
/** {@collect.stats}
* If the value of <code>key</code> for the given <code>Locale</code>
* is a <code>Dimension</code> return it, otherwise return <code>null</code>.
* @param key the desired key
* @param l the desired locale
* @return if the value for <code>key</code> and <code>Locale</code>
* is a <code>Dimension</code>,
* return the <code>Dimension</code> object; otherwise return
* <code>null</code>
* @since 1.4
*/
public Dimension getDimension(Object key, Locale l) {
Object value = get(key,l);
return (value instanceof Dimension) ? (Dimension)value : null;
}
/** {@collect.stats}
* The value of <code>get(uidClassID)</code> must be the
* <code>String</code> name of a
* class that implements the corresponding <code>ComponentUI</code>
* class. If the class hasn't been loaded before, this method looks
* up the class with <code>uiClassLoader.loadClass()</code> if a non
* <code>null</code>
* class loader is provided, <code>classForName()</code> otherwise.
* <p>
* If a mapping for <code>uiClassID</code> exists or if the specified
* class can't be found, return <code>null</code>.
* <p>
* This method is used by <code>getUI</code>, it's usually
* not necessary to call it directly.
*
* @param uiClassID a string containing the class ID
* @param uiClassLoader the object which will load the class
* @return the value of <code>Class.forName(get(uidClassID))</code>
* @see #getUI
*/
public Class<? extends ComponentUI>
getUIClass(String uiClassID, ClassLoader uiClassLoader)
{
try {
String className = (String)get(uiClassID);
if (className != null) {
Class cls = (Class)get(className);
if (cls == null) {
if (uiClassLoader == null) {
cls = SwingUtilities.loadSystemClass(className);
}
else {
cls = uiClassLoader.loadClass(className);
}
if (cls != null) {
// Save lookup for future use, as forName is slow.
put(className, cls);
}
}
return cls;
}
}
catch (ClassNotFoundException e) {
return null;
}
catch (ClassCastException e) {
return null;
}
return null;
}
/** {@collect.stats}
* Returns the L&F class that renders this component.
*
* @param uiClassID a string containing the class ID
* @return the Class object returned by
* <code>getUIClass(uiClassID, null)</code>
*/
public Class<? extends ComponentUI> getUIClass(String uiClassID) {
return getUIClass(uiClassID, null);
}
/** {@collect.stats}
* If <code>getUI()</code> fails for any reason,
* it calls this method before returning <code>null</code>.
* Subclasses may choose to do more or less here.
*
* @param msg message string to print
* @see #getUI
*/
protected void getUIError(String msg) {
System.err.println("UIDefaults.getUI() failed: " + msg);
try {
throw new Error();
}
catch (Throwable e) {
e.printStackTrace();
}
}
/** {@collect.stats}
* Creates an <code>ComponentUI</code> implementation for the
* specified component. In other words create the look
* and feel specific delegate object for <code>target</code>.
* This is done in two steps:
* <ul>
* <li> Look up the name of the <code>ComponentUI</code> implementation
* class under the value returned by <code>target.getUIClassID()</code>.
* <li> Use the implementation classes static <code>createUI()</code>
* method to construct a look and feel delegate.
* </ul>
* @param target the <code>JComponent</code> which needs a UI
* @return the <code>ComponentUI</code> object
*/
public ComponentUI getUI(JComponent target) {
Object cl = get("ClassLoader");
ClassLoader uiClassLoader =
(cl != null) ? (ClassLoader)cl : target.getClass().getClassLoader();
Class uiClass = getUIClass(target.getUIClassID(), uiClassLoader);
Object uiObject = null;
if (uiClass == null) {
getUIError("no ComponentUI class for: " + target);
}
else {
try {
Method m = (Method)get(uiClass);
if (m == null) {
Class acClass = javax.swing.JComponent.class;
m = uiClass.getMethod("createUI", new Class[]{acClass});
put(uiClass, m);
}
uiObject = MethodUtil.invoke(m, null, new Object[]{target});
}
catch (NoSuchMethodException e) {
getUIError("static createUI() method not found in " + uiClass);
}
catch (Exception e) {
getUIError("createUI() failed for " + target + " " + e);
}
}
return (ComponentUI)uiObject;
}
/** {@collect.stats}
* Adds a <code>PropertyChangeListener</code> to the listener list.
* The listener is registered for all properties.
* <p>
* A <code>PropertyChangeEvent</code> will get fired whenever a default
* is changed.
*
* @param listener the <code>PropertyChangeListener</code> to be added
* @see java.beans.PropertyChangeSupport
*/
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/** {@collect.stats}
* Removes a <code>PropertyChangeListener</code> from the listener list.
* This removes a <code>PropertyChangeListener</code> that was registered
* for all properties.
*
* @param listener the <code>PropertyChangeListener</code> to be removed
* @see java.beans.PropertyChangeSupport
*/
public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
/** {@collect.stats}
* Returns an array of all the <code>PropertyChangeListener</code>s added
* to this UIDefaults with addPropertyChangeListener().
*
* @return all of the <code>PropertyChangeListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners();
}
/** {@collect.stats}
* Support for reporting bound property changes. If oldValue and
* newValue are not equal and the <code>PropertyChangeEvent</code>x
* listener list isn't empty, then fire a
* <code>PropertyChange</code> event to each listener.
*
* @param propertyName the programmatic name of the property
* that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @see java.beans.PropertyChangeSupport
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (changeSupport != null) {
changeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
/** {@collect.stats}
* Adds a resource bundle to the list of resource bundles that are
* searched for localized values. Resource bundles are searched in the
* reverse order they were added. In other words, the most recently added
* bundle is searched first.
*
* @param bundleName the base name of the resource bundle to be added
* @see java.util.ResourceBundle
* @see #removeResourceBundle
* @since 1.4
*/
public synchronized void addResourceBundle( String bundleName ) {
if( bundleName == null ) {
return;
}
if( resourceBundles == null ) {
resourceBundles = new Vector(5);
}
if (!resourceBundles.contains(bundleName)) {
resourceBundles.add( bundleName );
resourceCache.clear();
}
}
/** {@collect.stats}
* Removes a resource bundle from the list of resource bundles that are
* searched for localized defaults.
*
* @param bundleName the base name of the resource bundle to be removed
* @see java.util.ResourceBundle
* @see #addResourceBundle
* @since 1.4
*/
public synchronized void removeResourceBundle( String bundleName ) {
if( resourceBundles != null ) {
resourceBundles.remove( bundleName );
}
resourceCache.clear();
}
/** {@collect.stats}
* Sets the default locale. The default locale is used in retrieving
* localized values via <code>get</code> methods that do not take a
* locale argument. As of release 1.4, Swing UI objects should retrieve
* localized values using the locale of their component rather than the
* default locale. The default locale exists to provide compatibility with
* pre 1.4 behaviour.
*
* @param l the new default locale
* @see #getDefaultLocale
* @see #get(Object)
* @see #get(Object,Locale)
* @since 1.4
*/
public void setDefaultLocale( Locale l ) {
defaultLocale = l;
}
/** {@collect.stats}
* Returns the default locale. The default locale is used in retrieving
* localized values via <code>get</code> methods that do not take a
* locale argument. As of release 1.4, Swing UI objects should retrieve
* localized values using the locale of their component rather than the
* default locale. The default locale exists to provide compatibility with
* pre 1.4 behaviour.
*
* @return the default locale
* @see #setDefaultLocale
* @see #get(Object)
* @see #get(Object,Locale)
* @since 1.4
*/
public Locale getDefaultLocale() {
return defaultLocale;
}
/** {@collect.stats}
* This class enables one to store an entry in the defaults
* table that isn't constructed until the first time it's
* looked up with one of the <code>getXXX(key)</code> methods.
* Lazy values are useful for defaults that are expensive
* to construct or are seldom retrieved. The first time
* a <code>LazyValue</code> is retrieved its "real value" is computed
* by calling <code>LazyValue.createValue()</code> and the real
* value is used to replace the <code>LazyValue</code> in the
* <code>UIDefaults</code>
* table. Subsequent lookups for the same key return
* the real value. Here's an example of a <code>LazyValue</code>
* that constructs a <code>Border</code>:
* <pre>
* Object borderLazyValue = new UIDefaults.LazyValue() {
* public Object createValue(UIDefaults table) {
* return new BorderFactory.createLoweredBevelBorder();
* }
* };
*
* uiDefaultsTable.put("MyBorder", borderLazyValue);
* </pre>
*
* @see UIDefaults#get
*/
public interface LazyValue {
/** {@collect.stats}
* Creates the actual value retrieved from the <code>UIDefaults</code>
* table. When an object that implements this interface is
* retrieved from the table, this method is used to create
* the real value, which is then stored in the table and
* returned to the calling method.
*
* @param table a <code>UIDefaults</code> table
* @return the created <code>Object</code>
*/
Object createValue(UIDefaults table);
}
/** {@collect.stats}
* This class enables one to store an entry in the defaults
* table that's constructed each time it's looked up with one of
* the <code>getXXX(key)</code> methods. Here's an example of
* an <code>ActiveValue</code> that constructs a
* <code>DefaultListCellRenderer</code>:
* <pre>
* Object cellRendererActiveValue = new UIDefaults.ActiveValue() {
* public Object createValue(UIDefaults table) {
* return new DefaultListCellRenderer();
* }
* };
*
* uiDefaultsTable.put("MyRenderer", cellRendererActiveValue);
* </pre>
*
* @see UIDefaults#get
*/
public interface ActiveValue {
/** {@collect.stats}
* Creates the value retrieved from the <code>UIDefaults</code> table.
* The object is created each time it is accessed.
*
* @param table a <code>UIDefaults</code> table
* @return the created <code>Object</code>
*/
Object createValue(UIDefaults table);
}
/** {@collect.stats}
* This class provides an implementation of <code>LazyValue</code>
* which can be
* used to delay loading of the Class for the instance to be created.
* It also avoids creation of an anonymous inner class for the
* <code>LazyValue</code>
* subclass. Both of these improve performance at the time that a
* a Look and Feel is loaded, at the cost of a slight performance
* reduction the first time <code>createValue</code> is called
* (since Reflection APIs are used).
* @since 1.3
*/
public static class ProxyLazyValue implements LazyValue {
private AccessControlContext acc;
private String className;
private String methodName;
private Object[] args;
/** {@collect.stats}
* Creates a <code>LazyValue</code> which will construct an instance
* when asked.
*
* @param c a <code>String</code> specifying the classname
* of the instance to be created on demand
*/
public ProxyLazyValue(String c) {
this(c, (String)null);
}
/** {@collect.stats}
* Creates a <code>LazyValue</code> which will construct an instance
* when asked.
*
* @param c a <code>String</code> specifying the classname of
* the class
* containing a static method to be called for
* instance creation
* @param m a <code>String</code> specifying the static
* method to be called on class c
*/
public ProxyLazyValue(String c, String m) {
this(c, m, null);
}
/** {@collect.stats}
* Creates a <code>LazyValue</code> which will construct an instance
* when asked.
*
* @param c a <code>String</code> specifying the classname
* of the instance to be created on demand
* @param o an array of <code>Objects</code> to be passed as
* paramaters to the constructor in class c
*/
public ProxyLazyValue(String c, Object[] o) {
this(c, null, o);
}
/** {@collect.stats}
* Creates a <code>LazyValue</code> which will construct an instance
* when asked.
*
* @param c a <code>String</code> specifying the classname
* of the class
* containing a static method to be called for
* instance creation.
* @param m a <code>String</code> specifying the static method
* to be called on class c
* @param o an array of <code>Objects</code> to be passed as
* paramaters to the static method in class c
*/
public ProxyLazyValue(String c, String m, Object[] o) {
acc = AccessController.getContext();
className = c;
methodName = m;
if (o != null) {
args = (Object[])o.clone();
}
}
/** {@collect.stats}
* Creates the value retrieved from the <code>UIDefaults</code> table.
* The object is created each time it is accessed.
*
* @param table a <code>UIDefaults</code> table
* @return the created <code>Object</code>
*/
public Object createValue(final UIDefaults table) {
// In order to pick up the security policy in effect at the
// time of creation we use a doPrivileged with the
// AccessControlContext that was in place when this was created.
if (acc == null && System.getSecurityManager() != null) {
throw new SecurityException("null AccessControlContext");
}
return AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
Class c;
Object cl;
// See if we should use a separate ClassLoader
if (table == null || !((cl = table.get("ClassLoader"))
instanceof ClassLoader)) {
cl = Thread.currentThread().
getContextClassLoader();
if (cl == null) {
// Fallback to the system class loader.
cl = ClassLoader.getSystemClassLoader();
}
}
ReflectUtil.checkPackageAccess(className);
c = Class.forName(className, true, (ClassLoader)cl);
checkAccess(c.getModifiers());
if (methodName != null) {
Class[] types = getClassArray(args);
Method m = c.getMethod(methodName, types);
return MethodUtil.invoke(m, c, args);
} else {
Class[] types = getClassArray(args);
Constructor constructor = c.getConstructor(types);
checkAccess(constructor.getModifiers());
return constructor.newInstance(args);
}
} catch(Exception e) {
// Ideally we would throw an exception, unfortunately
// often times there are errors as an initial look and
// feel is loaded before one can be switched. Perhaps a
// flag should be added for debugging, so that if true
// the exception would be thrown.
}
return null;
}
}, acc);
}
private void checkAccess(int modifiers) {
if(System.getSecurityManager() != null &&
!Modifier.isPublic(modifiers)) {
throw new SecurityException("Resource is not accessible");
}
}
/*
* Coerce the array of class types provided into one which
* looks the way the Reflection APIs expect. This is done
* by substituting primitive types for their Object counterparts,
* and superclasses for subclasses used to add the
* <code>UIResource</code> tag.
*/
private Class[] getClassArray(Object[] args) {
Class[] types = null;
if (args!=null) {
types = new Class[args.length];
for (int i = 0; i< args.length; i++) {
/* PENDING(ges): At present only the primitive types
used are handled correctly; this should eventually
handle all primitive types */
if (args[i] instanceof java.lang.Integer) {
types[i]=Integer.TYPE;
} else if (args[i] instanceof java.lang.Boolean) {
types[i]=Boolean.TYPE;
} else if (args[i] instanceof javax.swing.plaf.ColorUIResource) {
/* PENDING(ges) Currently the Reflection APIs do not
search superclasses of parameters supplied for
constructor/method lookup. Since we only have
one case where this is needed, we substitute
directly instead of adding a massive amount
of mechanism for this. Eventually this will
probably need to handle the general case as well.
*/
types[i]=java.awt.Color.class;
} else {
types[i]=args[i].getClass();
}
}
}
return types;
}
private String printArgs(Object[] array) {
String s = "{";
if (array !=null) {
for (int i = 0 ; i < array.length-1; i++) {
s = s.concat(array[i] + ",");
}
s = s.concat(array[array.length-1] + "}");
} else {
s = s.concat("}");
}
return s;
}
}
/** {@collect.stats}
* <code>LazyInputMap</code> will create a <code>InputMap</code>
* in its <code>createValue</code>
* method. The bindings are passed in in the constructor.
* The bindings are an array with
* the even number entries being string <code>KeyStrokes</code>
* (eg "alt SPACE") and
* the odd number entries being the value to use in the
* <code>InputMap</code> (and the key in the <code>ActionMap</code>).
* @since 1.3
*/
public static class LazyInputMap implements LazyValue {
/** {@collect.stats} Key bindings are registered under. */
private Object[] bindings;
public LazyInputMap(Object[] bindings) {
this.bindings = bindings;
}
/** {@collect.stats}
* Creates an <code>InputMap</code> with the bindings that are
* passed in.
*
* @param table a <code>UIDefaults</code> table
* @return the <code>InputMap</code>
*/
public Object createValue(UIDefaults table) {
if (bindings != null) {
InputMap km = LookAndFeel.makeInputMap(bindings);
return km;
}
return null;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
/** {@collect.stats}
* Defines the requirements for an object responsible for
* "rendering" (displaying) a value.
*
* @author Arnaud Weber
*/
public interface Renderer {
/** {@collect.stats}
* Specifies the value to display and whether or not the
* value should be portrayed as "currently selected".
*
* @param aValue an Object object
* @param isSelected a boolean
*/
void setValue(Object aValue,boolean isSelected);
/** {@collect.stats}
* Returns the component used to render the value.
*
* @return the Component responsible for displaying the value
*/
Component getComponent();
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* A private interface to access clip bounds in wrapped Graphics objects.
*
* @author Thomas Ball
*/
import java.awt.*;
interface GraphicsWrapper {
Graphics subGraphics();
boolean isClipIntersecting(Rectangle r);
int getClipX();
int getClipY();
int getClipWidth();
int getClipHeight();
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
import java.awt.event.*;
import java.lang.Boolean;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.EventObject;
import javax.swing.tree.*;
import java.io.Serializable;
/** {@collect.stats}
* The default editor for table and tree cells.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Alan Chung
* @author Philip Milne
*/
public class DefaultCellEditor extends AbstractCellEditor
implements TableCellEditor, TreeCellEditor {
//
// Instance Variables
//
/** {@collect.stats} The Swing component being edited. */
protected JComponent editorComponent;
/** {@collect.stats}
* The delegate class which handles all methods sent from the
* <code>CellEditor</code>.
*/
protected EditorDelegate delegate;
/** {@collect.stats}
* An integer specifying the number of clicks needed to start editing.
* Even if <code>clickCountToStart</code> is defined as zero, it
* will not initiate until a click occurs.
*/
protected int clickCountToStart = 1;
//
// Constructors
//
/** {@collect.stats}
* Constructs a <code>DefaultCellEditor</code> that uses a text field.
*
* @param textField a <code>JTextField</code> object
*/
public DefaultCellEditor(final JTextField textField) {
editorComponent = textField;
this.clickCountToStart = 2;
delegate = new EditorDelegate() {
public void setValue(Object value) {
textField.setText((value != null) ? value.toString() : "");
}
public Object getCellEditorValue() {
return textField.getText();
}
};
textField.addActionListener(delegate);
}
/** {@collect.stats}
* Constructs a <code>DefaultCellEditor</code> object that uses a check box.
*
* @param checkBox a <code>JCheckBox</code> object
*/
public DefaultCellEditor(final JCheckBox checkBox) {
editorComponent = checkBox;
delegate = new EditorDelegate() {
public void setValue(Object value) {
boolean selected = false;
if (value instanceof Boolean) {
selected = ((Boolean)value).booleanValue();
}
else if (value instanceof String) {
selected = value.equals("true");
}
checkBox.setSelected(selected);
}
public Object getCellEditorValue() {
return Boolean.valueOf(checkBox.isSelected());
}
};
checkBox.addActionListener(delegate);
checkBox.setRequestFocusEnabled(false);
}
/** {@collect.stats}
* Constructs a <code>DefaultCellEditor</code> object that uses a
* combo box.
*
* @param comboBox a <code>JComboBox</code> object
*/
public DefaultCellEditor(final JComboBox comboBox) {
editorComponent = comboBox;
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
delegate = new EditorDelegate() {
public void setValue(Object value) {
comboBox.setSelectedItem(value);
}
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}
public boolean shouldSelectCell(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
MouseEvent e = (MouseEvent)anEvent;
return e.getID() != MouseEvent.MOUSE_DRAGGED;
}
return true;
}
public boolean stopCellEditing() {
if (comboBox.isEditable()) {
// Commit edited value.
comboBox.actionPerformed(new ActionEvent(
DefaultCellEditor.this, 0, ""));
}
return super.stopCellEditing();
}
};
comboBox.addActionListener(delegate);
}
/** {@collect.stats}
* Returns a reference to the editor component.
*
* @return the editor <code>Component</code>
*/
public Component getComponent() {
return editorComponent;
}
//
// Modifying
//
/** {@collect.stats}
* Specifies the number of clicks needed to start editing.
*
* @param count an int specifying the number of clicks needed to start editing
* @see #getClickCountToStart
*/
public void setClickCountToStart(int count) {
clickCountToStart = count;
}
/** {@collect.stats}
* Returns the number of clicks needed to start editing.
* @return the number of clicks needed to start editing
*/
public int getClickCountToStart() {
return clickCountToStart;
}
//
// Override the implementations of the superclass, forwarding all methods
// from the CellEditor interface to our delegate.
//
/** {@collect.stats}
* Forwards the message from the <code>CellEditor</code> to
* the <code>delegate</code>.
* @see EditorDelegate#getCellEditorValue
*/
public Object getCellEditorValue() {
return delegate.getCellEditorValue();
}
/** {@collect.stats}
* Forwards the message from the <code>CellEditor</code> to
* the <code>delegate</code>.
* @see EditorDelegate#isCellEditable(EventObject)
*/
public boolean isCellEditable(EventObject anEvent) {
return delegate.isCellEditable(anEvent);
}
/** {@collect.stats}
* Forwards the message from the <code>CellEditor</code> to
* the <code>delegate</code>.
* @see EditorDelegate#shouldSelectCell(EventObject)
*/
public boolean shouldSelectCell(EventObject anEvent) {
return delegate.shouldSelectCell(anEvent);
}
/** {@collect.stats}
* Forwards the message from the <code>CellEditor</code> to
* the <code>delegate</code>.
* @see EditorDelegate#stopCellEditing
*/
public boolean stopCellEditing() {
return delegate.stopCellEditing();
}
/** {@collect.stats}
* Forwards the message from the <code>CellEditor</code> to
* the <code>delegate</code>.
* @see EditorDelegate#cancelCellEditing
*/
public void cancelCellEditing() {
delegate.cancelCellEditing();
}
//
// Implementing the TreeCellEditor Interface
//
/** {@collect.stats} Implements the <code>TreeCellEditor</code> interface. */
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected,
boolean expanded,
boolean leaf, int row) {
String stringValue = tree.convertValueToText(value, isSelected,
expanded, leaf, row, false);
delegate.setValue(stringValue);
return editorComponent;
}
//
// Implementing the CellEditor Interface
//
/** {@collect.stats} Implements the <code>TableCellEditor</code> interface. */
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column) {
delegate.setValue(value);
if (editorComponent instanceof JCheckBox) {
//in order to avoid a "flashing" effect when clicking a checkbox
//in a table, it is important for the editor to have as a border
//the same border that the renderer has, and have as the background
//the same color as the renderer has. This is primarily only
//needed for JCheckBox since this editor doesn't fill all the
//visual space of the table cell, unlike a text field.
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component c = renderer.getTableCellRendererComponent(table, value,
isSelected, true, row, column);
if (c != null) {
editorComponent.setOpaque(true);
editorComponent.setBackground(c.getBackground());
if (c instanceof JComponent) {
editorComponent.setBorder(((JComponent)c).getBorder());
}
} else {
editorComponent.setOpaque(false);
}
}
return editorComponent;
}
//
// Protected EditorDelegate class
//
/** {@collect.stats}
* The protected <code>EditorDelegate</code> class.
*/
protected class EditorDelegate implements ActionListener, ItemListener, Serializable {
/** {@collect.stats} The value of this cell. */
protected Object value;
/** {@collect.stats}
* Returns the value of this cell.
* @return the value of this cell
*/
public Object getCellEditorValue() {
return value;
}
/** {@collect.stats}
* Sets the value of this cell.
* @param value the new value of this cell
*/
public void setValue(Object value) {
this.value = value;
}
/** {@collect.stats}
* Returns true if <code>anEvent</code> is <b>not</b> a
* <code>MouseEvent</code>. Otherwise, it returns true
* if the necessary number of clicks have occurred, and
* returns false otherwise.
*
* @param anEvent the event
* @return true if cell is ready for editing, false otherwise
* @see #setClickCountToStart
* @see #shouldSelectCell
*/
public boolean isCellEditable(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
}
return true;
}
/** {@collect.stats}
* Returns true to indicate that the editing cell may
* be selected.
*
* @param anEvent the event
* @return true
* @see #isCellEditable
*/
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
/** {@collect.stats}
* Returns true to indicate that editing has begun.
*
* @param anEvent the event
*/
public boolean startCellEditing(EventObject anEvent) {
return true;
}
/** {@collect.stats}
* Stops editing and
* returns true to indicate that editing has stopped.
* This method calls <code>fireEditingStopped</code>.
*
* @return true
*/
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
/** {@collect.stats}
* Cancels editing. This method calls <code>fireEditingCanceled</code>.
*/
public void cancelCellEditing() {
fireEditingCanceled();
}
/** {@collect.stats}
* When an action is performed, editing is ended.
* @param e the action event
* @see #stopCellEditing
*/
public void actionPerformed(ActionEvent e) {
DefaultCellEditor.this.stopCellEditing();
}
/** {@collect.stats}
* When an item's state changes, editing is ended.
* @param e the action event
* @see #stopCellEditing
*/
public void itemStateChanged(ItemEvent e) {
DefaultCellEditor.this.stopCellEditing();
}
}
} // End of class JCellEditor
|
Java
|
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
import java.io.Serializable;
import java.util.EventListener;
/** {@collect.stats}
* The abstract definition for the data model that provides
* a <code>List</code> with its contents.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Hans Muller
*/
public abstract class AbstractListModel implements ListModel, Serializable
{
protected EventListenerList listenerList = new EventListenerList();
/** {@collect.stats}
* Adds a listener to the list that's notified each time a change
* to the data model occurs.
*
* @param l the <code>ListDataListener</code> to be added
*/
public void addListDataListener(ListDataListener l) {
listenerList.add(ListDataListener.class, l);
}
/** {@collect.stats}
* Removes a listener from the list that's notified each time a
* change to the data model occurs.
*
* @param l the <code>ListDataListener</code> to be removed
*/
public void removeListDataListener(ListDataListener l) {
listenerList.remove(ListDataListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the list data listeners
* registered on this <code>AbstractListModel</code>.
*
* @return all of this model's <code>ListDataListener</code>s,
* or an empty array if no list data listeners
* are currently registered
*
* @see #addListDataListener
* @see #removeListDataListener
*
* @since 1.4
*/
public ListDataListener[] getListDataListeners() {
return (ListDataListener[])listenerList.getListeners(
ListDataListener.class);
}
/** {@collect.stats}
* <code>AbstractListModel</code> subclasses must call this method
* <b>after</b>
* one or more elements of the list change. The changed elements
* are specified by the closed interval index0, index1 -- the endpoints
* are included. Note that
* index0 need not be less than or equal to index1.
*
* @param source the <code>ListModel</code> that changed, typically "this"
* @param index0 one end of the new interval
* @param index1 the other end of the new interval
* @see EventListenerList
* @see DefaultListModel
*/
protected void fireContentsChanged(Object source, int index0, int index1)
{
Object[] listeners = listenerList.getListenerList();
ListDataEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListDataListener.class) {
if (e == null) {
e = new ListDataEvent(source, ListDataEvent.CONTENTS_CHANGED, index0, index1);
}
((ListDataListener)listeners[i+1]).contentsChanged(e);
}
}
}
/** {@collect.stats}
* <code>AbstractListModel</code> subclasses must call this method
* <b>after</b>
* one or more elements are added to the model. The new elements
* are specified by a closed interval index0, index1 -- the enpoints
* are included. Note that
* index0 need not be less than or equal to index1.
*
* @param source the <code>ListModel</code> that changed, typically "this"
* @param index0 one end of the new interval
* @param index1 the other end of the new interval
* @see EventListenerList
* @see DefaultListModel
*/
protected void fireIntervalAdded(Object source, int index0, int index1)
{
Object[] listeners = listenerList.getListenerList();
ListDataEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListDataListener.class) {
if (e == null) {
e = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1);
}
((ListDataListener)listeners[i+1]).intervalAdded(e);
}
}
}
/** {@collect.stats}
* <code>AbstractListModel</code> subclasses must call this method
* <b>after</b> one or more elements are removed from the model.
* <code>index0</code> and <code>index1</code> are the end points
* of the interval that's been removed. Note that <code>index0</code>
* need not be less than or equal to <code>index1</code>.
*
* @param source the <code>ListModel</code> that changed, typically "this"
* @param index0 one end of the removed interval,
* including <code>index0</code>
* @param index1 the other end of the removed interval,
* including <code>index1</code>
* @see EventListenerList
* @see DefaultListModel
*/
protected void fireIntervalRemoved(Object source, int index0, int index1)
{
Object[] listeners = listenerList.getListenerList();
ListDataEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListDataListener.class) {
if (e == null) {
e = new ListDataEvent(source, ListDataEvent.INTERVAL_REMOVED, index0, index1);
}
((ListDataListener)listeners[i+1]).intervalRemoved(e);
}
}
}
/** {@collect.stats}
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s
* are registered using the <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as <code><em>Foo</em>Listener.class</code>.
* For example, you can query a list model
* <code>m</code>
* for its list data listeners
* with the following code:
*
* <pre>ListDataListener[] ldls = (ListDataListener[])(m.getListeners(ListDataListener.class));</pre>
*
* If no such listeners exist,
* this method returns an empty array.
*
* @param listenerType the type of listeners requested;
* this parameter should specify an interface
* that descends from <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s
* on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code> doesn't
* specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getListDataListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.tree.*;
import javax.swing.text.Position;
import javax.accessibility.*;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
import static sun.swing.SwingUtilities2.Section.*;
/** {@collect.stats}
* <a name="jtree_description">
* A control that displays a set of hierarchical data as an outline.
* You can find task-oriented documentation and examples of using trees in
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* A specific node in a tree can be identified either by a
* <code>TreePath</code> (an object
* that encapsulates a node and all of its ancestors), or by its
* display row, where each row in the display area displays one node.
* An <i>expanded</i> node is a non-leaf node (as identified by
* <code>TreeModel.isLeaf(node)</code> returning false) that will displays
* its children when all its ancestors are <i>expanded</i>.
* A <i>collapsed</i>
* node is one which hides them. A <i>hidden</i> node is one which is
* under a collapsed ancestor. All of a <i>viewable</i> nodes parents
* are expanded, but may or may not be displayed. A <i>displayed</i> node
* is both viewable and in the display area, where it can be seen.
* <p>
* The following <code>JTree</code> methods use "visible" to mean "displayed":
* <ul>
* <li><code>isRootVisible()</code>
* <li><code>setRootVisible()</code>
* <li><code>scrollPathToVisible()</code>
* <li><code>scrollRowToVisible()</code>
* <li><code>getVisibleRowCount()</code>
* <li><code>setVisibleRowCount()</code>
* </ul>
* <p>
* The next group of <code>JTree</code> methods use "visible" to mean
* "viewable" (under an expanded parent):
* <ul>
* <li><code>isVisible()</code>
* <li><code>makeVisible()</code>
* </ul>
* <p>
* If you are interested in knowing when the selection changes implement
* the <code>TreeSelectionListener</code> interface and add the instance
* using the method <code>addTreeSelectionListener</code>.
* <code>valueChanged</code> will be invoked when the
* selection changes, that is if the user clicks twice on the same
* node <code>valueChanged</code> will only be invoked once.
* <p>
* If you are interested in detecting either double-click events or when
* a user clicks on a node, regardless of whether or not it was selected,
* we recommend you do the following:
* <pre>
* final JTree tree = ...;
*
* MouseListener ml = new MouseAdapter() {
* public void <b>mousePressed</b>(MouseEvent e) {
* int selRow = tree.getRowForLocation(e.getX(), e.getY());
* TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
* if(selRow != -1) {
* if(e.getClickCount() == 1) {
* mySingleClick(selRow, selPath);
* }
* else if(e.getClickCount() == 2) {
* myDoubleClick(selRow, selPath);
* }
* }
* }
* };
* tree.addMouseListener(ml);
* </pre>
* NOTE: This example obtains both the path and row, but you only need to
* get the one you're interested in.
* <p>
* To use <code>JTree</code> to display compound nodes
* (for example, nodes containing both
* a graphic icon and text), subclass {@link TreeCellRenderer} and use
* {@link #setCellRenderer} to tell the tree to use it. To edit such nodes,
* subclass {@link TreeCellEditor} and use {@link #setCellEditor}.
* <p>
* Like all <code>JComponent</code> classes, you can use {@link InputMap} and
* {@link ActionMap}
* to associate an {@link Action} object with a {@link KeyStroke}
* and execute the action under specified conditions.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A component that displays a set of hierarchical data as an outline.
*
* @author Rob Davis
* @author Ray Ryan
* @author Scott Violet
*/
public class JTree extends JComponent implements Scrollable, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TreeUI";
/** {@collect.stats}
* The model that defines the tree displayed by this object.
*/
transient protected TreeModel treeModel;
/** {@collect.stats}
* Models the set of selected nodes in this tree.
*/
transient protected TreeSelectionModel selectionModel;
/** {@collect.stats}
* True if the root node is displayed, false if its children are
* the highest visible nodes.
*/
protected boolean rootVisible;
/** {@collect.stats}
* The cell used to draw nodes. If <code>null</code>, the UI uses a default
* <code>cellRenderer</code>.
*/
transient protected TreeCellRenderer cellRenderer;
/** {@collect.stats}
* Height to use for each display row. If this is <= 0 the renderer
* determines the height for each row.
*/
protected int rowHeight;
private boolean rowHeightSet = false;
/** {@collect.stats}
* Maps from <code>TreePath</code> to <code>Boolean</code>
* indicating whether or not the
* particular path is expanded. This ONLY indicates whether a
* given path is expanded, and NOT if it is visible or not. That
* information must be determined by visiting all the parent
* paths and seeing if they are visible.
*/
transient private Hashtable expandedState;
/** {@collect.stats}
* True if handles are displayed at the topmost level of the tree.
* <p>
* A handle is a small icon that displays adjacent to the node which
* allows the user to click once to expand or collapse the node. A
* common interface shows a plus sign (+) for a node which can be
* expanded and a minus sign (-) for a node which can be collapsed.
* Handles are always shown for nodes below the topmost level.
* <p>
* If the <code>rootVisible</code> setting specifies that the root
* node is to be displayed, then that is the only node at the topmost
* level. If the root node is not displayed, then all of its
* children are at the topmost level of the tree. Handles are
* always displayed for nodes other than the topmost.
* <p>
* If the root node isn't visible, it is generally a good to make
* this value true. Otherwise, the tree looks exactly like a list,
* and users may not know that the "list entries" are actually
* tree nodes.
*
* @see #rootVisible
*/
protected boolean showsRootHandles;
private boolean showsRootHandlesSet = false;
/** {@collect.stats}
* Creates a new event and passed it off the
* <code>selectionListeners</code>.
*/
protected transient TreeSelectionRedirector selectionRedirector;
/** {@collect.stats}
* Editor for the entries. Default is <code>null</code>
* (tree is not editable).
*/
transient protected TreeCellEditor cellEditor;
/** {@collect.stats}
* Is the tree editable? Default is false.
*/
protected boolean editable;
/** {@collect.stats}
* Is this tree a large model? This is a code-optimization setting.
* A large model can be used when the cell height is the same for all
* nodes. The UI will then cache very little information and instead
* continually message the model. Without a large model the UI caches
* most of the information, resulting in fewer method calls to the model.
* <p>
* This value is only a suggestion to the UI. Not all UIs will
* take advantage of it. Default value is false.
*/
protected boolean largeModel;
/** {@collect.stats}
* Number of rows to make visible at one time. This value is used for
* the <code>Scrollable</code> interface. It determines the preferred
* size of the display area.
*/
protected int visibleRowCount;
/** {@collect.stats}
* If true, when editing is to be stopped by way of selection changing,
* data in tree changing or other means <code>stopCellEditing</code>
* is invoked, and changes are saved. If false,
* <code>cancelCellEditing</code> is invoked, and changes
* are discarded. Default is false.
*/
protected boolean invokesStopCellEditing;
/** {@collect.stats}
* If true, when a node is expanded, as many of the descendants are
* scrolled to be visible.
*/
protected boolean scrollsOnExpand;
private boolean scrollsOnExpandSet = false;
/** {@collect.stats}
* Number of mouse clicks before a node is expanded.
*/
protected int toggleClickCount;
/** {@collect.stats}
* Updates the <code>expandedState</code>.
*/
transient protected TreeModelListener treeModelListener;
/** {@collect.stats}
* Used when <code>setExpandedState</code> is invoked,
* will be a <code>Stack</code> of <code>Stack</code>s.
*/
transient private Stack expandedStack;
/** {@collect.stats}
* Lead selection path, may not be <code>null</code>.
*/
private TreePath leadPath;
/** {@collect.stats}
* Anchor path.
*/
private TreePath anchorPath;
/** {@collect.stats}
* True if paths in the selection should be expanded.
*/
private boolean expandsSelectedPaths;
/** {@collect.stats}
* This is set to true for the life of the <code>setUI</code> call.
*/
private boolean settingUI;
/** {@collect.stats} If true, mouse presses on selections initiate a drag operation. */
private boolean dragEnabled;
/** {@collect.stats}
* The drop mode for this component.
*/
private DropMode dropMode = DropMode.USE_SELECTION;
/** {@collect.stats}
* The drop location.
*/
private transient DropLocation dropLocation;
/** {@collect.stats}
* A subclass of <code>TransferHandler.DropLocation</code> representing
* a drop location for a <code>JTree</code>.
*
* @see #getDropLocation
* @since 1.6
*/
public static final class DropLocation extends TransferHandler.DropLocation {
private final TreePath path;
private final int index;
private DropLocation(Point p, TreePath path, int index) {
super(p);
this.path = path;
this.index = index;
}
/** {@collect.stats}
* Returns the index where the dropped data should be inserted
* with respect to the path returned by <code>getPath()</code>.
* <p>
* For drop modes <code>DropMode.USE_SELECTION</code> and
* <code>DropMode.ON</code>, this index is unimportant (and it will
* always be <code>-1</code>) as the only interesting data is the
* path over which the drop operation occurred.
* <p>
* For drop mode <code>DropMode.INSERT</code>, this index
* indicates the index at which the data should be inserted into
* the parent path represented by <code>getPath()</code>.
* <code>-1</code> indicates that the drop occurred over the
* parent itself, and in most cases should be treated as inserting
* into either the beginning or the end of the parent's list of
* children.
* <p>
* For <code>DropMode.ON_OR_INSERT</code>, this value will be
* an insert index, as described above, or <code>-1</code> if
* the drop occurred over the path itself.
*
* @return the child index
* @see #getPath
*/
public int getChildIndex() {
return index;
}
/** {@collect.stats}
* Returns the path where dropped data should be placed in the
* tree.
* <p>
* Interpretation of this value depends on the drop mode set on the
* component. If the drop mode is <code>DropMode.USE_SELECTION</code>
* or <code>DropMode.ON</code>, the return value is the path in the
* tree over which the data has been (or will be) dropped.
* <code>null</code> indicates that the drop is over empty space,
* not associated with a particular path.
* <p>
* If the drop mode is <code>DropMode.INSERT</code>, the return value
* refers to the path that should become the parent of the new data,
* in which case <code>getChildIndex()</code> indicates where the
* new item should be inserted into this parent path. A
* <code>null</code> path indicates that no parent path has been
* determined, which can happen for multiple reasons:
* <ul>
* <li>The tree has no model
* <li>There is no root in the tree
* <li>The root is collapsed
* <li>The root is a leaf node
* </ul>
* It is up to the developer to decide if and how they wish to handle
* the <code>null</code> case.
* <p>
* If the drop mode is <code>DropMode.ON_OR_INSERT</code>,
* <code>getChildIndex</code> can be used to determine whether the
* drop is on top of the path itself (<code>-1</code>) or the index
* at which it should be inserted into the path (values other than
* <code>-1</code>).
*
* @return the drop path
* @see #getChildIndex
*/
public TreePath getPath() {
return path;
}
/** {@collect.stats}
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName()
+ "[dropPoint=" + getDropPoint() + ","
+ "path=" + path + ","
+ "childIndex=" + index + "]";
}
}
/** {@collect.stats}
* The row to expand during DnD.
*/
private int expandRow = -1;
private class TreeTimer extends Timer {
public TreeTimer() {
super(2000, null);
setRepeats(false);
}
public void fireActionPerformed(ActionEvent ae) {
JTree.this.expandRow(expandRow);
}
}
/** {@collect.stats}
* A timer to expand nodes during drop.
*/
private TreeTimer dropTimer;
/** {@collect.stats}
* When <code>addTreeExpansionListener</code> is invoked,
* and <code>settingUI</code> is true, this ivar gets set to the passed in
* <code>Listener</code>. This listener is then notified first in
* <code>fireTreeCollapsed</code> and <code>fireTreeExpanded</code>.
* <p>This is an ugly workaround for a way to have the UI listener
* get notified before other listeners.
*/
private transient TreeExpansionListener uiTreeExpansionListener;
/** {@collect.stats}
* Max number of stacks to keep around.
*/
private static int TEMP_STACK_SIZE = 11;
//
// Bound property names
//
/** {@collect.stats} Bound property name for <code>cellRenderer</code>. */
public final static String CELL_RENDERER_PROPERTY = "cellRenderer";
/** {@collect.stats} Bound property name for <code>treeModel</code>. */
public final static String TREE_MODEL_PROPERTY = "model";
/** {@collect.stats} Bound property name for <code>rootVisible</code>. */
public final static String ROOT_VISIBLE_PROPERTY = "rootVisible";
/** {@collect.stats} Bound property name for <code>showsRootHandles</code>. */
public final static String SHOWS_ROOT_HANDLES_PROPERTY = "showsRootHandles";
/** {@collect.stats} Bound property name for <code>rowHeight</code>. */
public final static String ROW_HEIGHT_PROPERTY = "rowHeight";
/** {@collect.stats} Bound property name for <code>cellEditor</code>. */
public final static String CELL_EDITOR_PROPERTY = "cellEditor";
/** {@collect.stats} Bound property name for <code>editable</code>. */
public final static String EDITABLE_PROPERTY = "editable";
/** {@collect.stats} Bound property name for <code>largeModel</code>. */
public final static String LARGE_MODEL_PROPERTY = "largeModel";
/** {@collect.stats} Bound property name for selectionModel. */
public final static String SELECTION_MODEL_PROPERTY = "selectionModel";
/** {@collect.stats} Bound property name for <code>visibleRowCount</code>. */
public final static String VISIBLE_ROW_COUNT_PROPERTY = "visibleRowCount";
/** {@collect.stats} Bound property name for <code>messagesStopCellEditing</code>. */
public final static String INVOKES_STOP_CELL_EDITING_PROPERTY = "invokesStopCellEditing";
/** {@collect.stats} Bound property name for <code>scrollsOnExpand</code>. */
public final static String SCROLLS_ON_EXPAND_PROPERTY = "scrollsOnExpand";
/** {@collect.stats} Bound property name for <code>toggleClickCount</code>. */
public final static String TOGGLE_CLICK_COUNT_PROPERTY = "toggleClickCount";
/** {@collect.stats} Bound property name for <code>leadSelectionPath</code>.
* @since 1.3 */
public final static String LEAD_SELECTION_PATH_PROPERTY = "leadSelectionPath";
/** {@collect.stats} Bound property name for anchor selection path.
* @since 1.3 */
public final static String ANCHOR_SELECTION_PATH_PROPERTY = "anchorSelectionPath";
/** {@collect.stats} Bound property name for expands selected paths property
* @since 1.3 */
public final static String EXPANDS_SELECTED_PATHS_PROPERTY = "expandsSelectedPaths";
/** {@collect.stats}
* Creates and returns a sample <code>TreeModel</code>.
* Used primarily for beanbuilders to show something interesting.
*
* @return the default <code>TreeModel</code>
*/
protected static TreeModel getDefaultTreeModel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("JTree");
DefaultMutableTreeNode parent;
parent = new DefaultMutableTreeNode("colors");
root.add(parent);
parent.add(new DefaultMutableTreeNode("blue"));
parent.add(new DefaultMutableTreeNode("violet"));
parent.add(new DefaultMutableTreeNode("red"));
parent.add(new DefaultMutableTreeNode("yellow"));
parent = new DefaultMutableTreeNode("sports");
root.add(parent);
parent.add(new DefaultMutableTreeNode("basketball"));
parent.add(new DefaultMutableTreeNode("soccer"));
parent.add(new DefaultMutableTreeNode("football"));
parent.add(new DefaultMutableTreeNode("hockey"));
parent = new DefaultMutableTreeNode("food");
root.add(parent);
parent.add(new DefaultMutableTreeNode("hot dogs"));
parent.add(new DefaultMutableTreeNode("pizza"));
parent.add(new DefaultMutableTreeNode("ravioli"));
parent.add(new DefaultMutableTreeNode("bananas"));
return new DefaultTreeModel(root);
}
/** {@collect.stats}
* Returns a <code>TreeModel</code> wrapping the specified object.
* If the object is:<ul>
* <li>an array of <code>Object</code>s,
* <li>a <code>Hashtable</code>, or
* <li>a <code>Vector</code>
* </ul>then a new root node is created with each of the incoming
* objects as children. Otherwise, a new root is created with the
* specified object as its value.
*
* @param value the <code>Object</code> used as the foundation for
* the <code>TreeModel</code>
* @return a <code>TreeModel</code> wrapping the specified object
*/
protected static TreeModel createTreeModel(Object value) {
DefaultMutableTreeNode root;
if((value instanceof Object[]) || (value instanceof Hashtable) ||
(value instanceof Vector)) {
root = new DefaultMutableTreeNode("root");
DynamicUtilTreeNode.createChildren(root, value);
}
else {
root = new DynamicUtilTreeNode("root", value);
}
return new DefaultTreeModel(root, false);
}
/** {@collect.stats}
* Returns a <code>JTree</code> with a sample model.
* The default model used by the tree defines a leaf node as any node
* without children.
*
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree() {
this(getDefaultTreeModel());
}
/** {@collect.stats}
* Returns a <code>JTree</code> with each element of the
* specified array as the
* child of a new root node which is not displayed.
* By default, the tree defines a leaf node as any node without
* children.
*
* @param value an array of <code>Object</code>s
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Object[] value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/** {@collect.stats}
* Returns a <code>JTree</code> with each element of the specified
* <code>Vector</code> as the
* child of a new root node which is not displayed. By default, the
* tree defines a leaf node as any node without children.
*
* @param value a <code>Vector</code>
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Vector<?> value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/** {@collect.stats}
* Returns a <code>JTree</code> created from a <code>Hashtable</code>
* which does not display with root.
* Each value-half of the key/value pairs in the <code>HashTable</code>
* becomes a child of the new root node. By default, the tree defines
* a leaf node as any node without children.
*
* @param value a <code>Hashtable</code>
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Hashtable<?,?> value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/** {@collect.stats}
* Returns a <code>JTree</code> with the specified
* <code>TreeNode</code> as its root,
* which displays the root node.
* By default, the tree defines a leaf node as any node without children.
*
* @param root a <code>TreeNode</code> object
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(TreeNode root) {
this(root, false);
}
/** {@collect.stats}
* Returns a <code>JTree</code> with the specified <code>TreeNode</code>
* as its root, which
* displays the root node and which decides whether a node is a
* leaf node in the specified manner.
*
* @param root a <code>TreeNode</code> object
* @param asksAllowsChildren if false, any node without children is a
* leaf node; if true, only nodes that do not allow
* children are leaf nodes
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(TreeNode root, boolean asksAllowsChildren) {
this(new DefaultTreeModel(root, asksAllowsChildren));
}
/** {@collect.stats}
* Returns an instance of <code>JTree</code> which displays the root node
* -- the tree is created using the specified data model.
*
* @param newModel the <code>TreeModel</code> to use as the data model
*/
public JTree(TreeModel newModel) {
super();
expandedStack = new Stack();
toggleClickCount = 2;
expandedState = new Hashtable();
setLayout(null);
rowHeight = 16;
visibleRowCount = 20;
rootVisible = true;
selectionModel = new DefaultTreeSelectionModel();
cellRenderer = null;
scrollsOnExpand = true;
setOpaque(true);
expandsSelectedPaths = true;
updateUI();
setModel(newModel);
}
/** {@collect.stats}
* Returns the L&F object that renders this component.
*
* @return the <code>TreeUI</code> object that renders this component
*/
public TreeUI getUI() {
return (TreeUI)ui;
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>TreeUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(TreeUI ui) {
if ((TreeUI)this.ui != ui) {
settingUI = true;
uiTreeExpansionListener = null;
try {
super.setUI(ui);
}
finally {
settingUI = false;
}
}
}
/** {@collect.stats}
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((TreeUI)UIManager.getUI(this));
SwingUtilities.updateRendererOrEditorUI(getCellRenderer());
SwingUtilities.updateRendererOrEditorUI(getCellEditor());
}
/** {@collect.stats}
* Returns the name of the L&F class that renders this component.
*
* @return the string "TreeUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the current <code>TreeCellRenderer</code>
* that is rendering each cell.
*
* @return the <code>TreeCellRenderer</code> that is rendering each cell
*/
public TreeCellRenderer getCellRenderer() {
return cellRenderer;
}
/** {@collect.stats}
* Sets the <code>TreeCellRenderer</code> that will be used to
* draw each cell.
*
* @param x the <code>TreeCellRenderer</code> that is to render each cell
* @beaninfo
* bound: true
* description: The TreeCellRenderer that will be used to draw
* each cell.
*/
public void setCellRenderer(TreeCellRenderer x) {
TreeCellRenderer oldValue = cellRenderer;
cellRenderer = x;
firePropertyChange(CELL_RENDERER_PROPERTY, oldValue, cellRenderer);
invalidate();
}
/** {@collect.stats}
* Determines whether the tree is editable. Fires a property
* change event if the new setting is different from the existing
* setting.
*
* @param flag a boolean value, true if the tree is editable
* @beaninfo
* bound: true
* description: Whether the tree is editable.
*/
public void setEditable(boolean flag) {
boolean oldValue = this.editable;
this.editable = flag;
firePropertyChange(EDITABLE_PROPERTY, oldValue, flag);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
(oldValue ? AccessibleState.EDITABLE : null),
(flag ? AccessibleState.EDITABLE : null));
}
}
/** {@collect.stats}
* Returns true if the tree is editable.
*
* @return true if the tree is editable
*/
public boolean isEditable() {
return editable;
}
/** {@collect.stats}
* Sets the cell editor. A <code>null</code> value implies that the
* tree cannot be edited. If this represents a change in the
* <code>cellEditor</code>, the <code>propertyChange</code>
* method is invoked on all listeners.
*
* @param cellEditor the <code>TreeCellEditor</code> to use
* @beaninfo
* bound: true
* description: The cell editor. A null value implies the tree
* cannot be edited.
*/
public void setCellEditor(TreeCellEditor cellEditor) {
TreeCellEditor oldEditor = this.cellEditor;
this.cellEditor = cellEditor;
firePropertyChange(CELL_EDITOR_PROPERTY, oldEditor, cellEditor);
invalidate();
}
/** {@collect.stats}
* Returns the editor used to edit entries in the tree.
*
* @return the <code>TreeCellEditor</code> in use,
* or <code>null</code> if the tree cannot be edited
*/
public TreeCellEditor getCellEditor() {
return cellEditor;
}
/** {@collect.stats}
* Returns the <code>TreeModel</code> that is providing the data.
*
* @return the <code>TreeModel</code> that is providing the data
*/
public TreeModel getModel() {
return treeModel;
}
/** {@collect.stats}
* Sets the <code>TreeModel</code> that will provide the data.
*
* @param newModel the <code>TreeModel</code> that is to provide the data
* @beaninfo
* bound: true
* description: The TreeModel that will provide the data.
*/
public void setModel(TreeModel newModel) {
clearSelection();
TreeModel oldModel = treeModel;
if(treeModel != null && treeModelListener != null)
treeModel.removeTreeModelListener(treeModelListener);
if (accessibleContext != null) {
if (treeModel != null) {
treeModel.removeTreeModelListener((TreeModelListener)accessibleContext);
}
if (newModel != null) {
newModel.addTreeModelListener((TreeModelListener)accessibleContext);
}
}
treeModel = newModel;
clearToggledPaths();
if(treeModel != null) {
if(treeModelListener == null)
treeModelListener = createTreeModelListener();
if(treeModelListener != null)
treeModel.addTreeModelListener(treeModelListener);
// Mark the root as expanded, if it isn't a leaf.
if(treeModel.getRoot() != null &&
!treeModel.isLeaf(treeModel.getRoot())) {
expandedState.put(new TreePath(treeModel.getRoot()),
Boolean.TRUE);
}
}
firePropertyChange(TREE_MODEL_PROPERTY, oldModel, treeModel);
invalidate();
}
/** {@collect.stats}
* Returns true if the root node of the tree is displayed.
*
* @return true if the root node of the tree is displayed
* @see #rootVisible
*/
public boolean isRootVisible() {
return rootVisible;
}
/** {@collect.stats}
* Determines whether or not the root node from
* the <code>TreeModel</code> is visible.
*
* @param rootVisible true if the root node of the tree is to be displayed
* @see #rootVisible
* @beaninfo
* bound: true
* description: Whether or not the root node
* from the TreeModel is visible.
*/
public void setRootVisible(boolean rootVisible) {
boolean oldValue = this.rootVisible;
this.rootVisible = rootVisible;
firePropertyChange(ROOT_VISIBLE_PROPERTY, oldValue, this.rootVisible);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
/** {@collect.stats}
* Sets the value of the <code>showsRootHandles</code> property,
* which specifies whether the node handles should be displayed.
* The default value of this property depends on the constructor
* used to create the <code>JTree</code>.
* Some look and feels might not support handles;
* they will ignore this property.
*
* @param newValue <code>true</code> if root handles should be displayed;
* otherwise, <code>false</code>
* @see #showsRootHandles
* @see #getShowsRootHandles
* @beaninfo
* bound: true
* description: Whether the node handles are to be
* displayed.
*/
public void setShowsRootHandles(boolean newValue) {
boolean oldValue = showsRootHandles;
TreeModel model = getModel();
showsRootHandles = newValue;
showsRootHandlesSet = true;
firePropertyChange(SHOWS_ROOT_HANDLES_PROPERTY, oldValue,
showsRootHandles);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
invalidate();
}
/** {@collect.stats}
* Returns the value of the <code>showsRootHandles</code> property.
*
* @return the value of the <code>showsRootHandles</code> property
* @see #showsRootHandles
*/
public boolean getShowsRootHandles()
{
return showsRootHandles;
}
/** {@collect.stats}
* Sets the height of each cell, in pixels. If the specified value
* is less than or equal to zero the current cell renderer is
* queried for each row's height.
*
* @param rowHeight the height of each cell, in pixels
* @beaninfo
* bound: true
* description: The height of each cell.
*/
public void setRowHeight(int rowHeight)
{
int oldValue = this.rowHeight;
this.rowHeight = rowHeight;
rowHeightSet = true;
firePropertyChange(ROW_HEIGHT_PROPERTY, oldValue, this.rowHeight);
invalidate();
}
/** {@collect.stats}
* Returns the height of each row. If the returned value is less than
* or equal to 0 the height for each row is determined by the
* renderer.
*
*/
public int getRowHeight()
{
return rowHeight;
}
/** {@collect.stats}
* Returns true if the height of each display row is a fixed size.
*
* @return true if the height of each row is a fixed size
*/
public boolean isFixedRowHeight()
{
return (rowHeight > 0);
}
/** {@collect.stats}
* Specifies whether the UI should use a large model.
* (Not all UIs will implement this.) Fires a property change
* for the LARGE_MODEL_PROPERTY.
*
* @param newValue true to suggest a large model to the UI
* @see #largeModel
* @beaninfo
* bound: true
* description: Whether the UI should use a
* large model.
*/
public void setLargeModel(boolean newValue) {
boolean oldValue = largeModel;
largeModel = newValue;
firePropertyChange(LARGE_MODEL_PROPERTY, oldValue, newValue);
}
/** {@collect.stats}
* Returns true if the tree is configured for a large model.
*
* @return true if a large model is suggested
* @see #largeModel
*/
public boolean isLargeModel() {
return largeModel;
}
/** {@collect.stats}
* Determines what happens when editing is interrupted by selecting
* another node in the tree, a change in the tree's data, or by some
* other means. Setting this property to <code>true</code> causes the
* changes to be automatically saved when editing is interrupted.
* <p>
* Fires a property change for the INVOKES_STOP_CELL_EDITING_PROPERTY.
*
* @param newValue true means that <code>stopCellEditing</code> is invoked
* when editing is interrupted, and data is saved; false means that
* <code>cancelCellEditing</code> is invoked, and changes are lost
* @beaninfo
* bound: true
* description: Determines what happens when editing is interrupted,
* selecting another node in the tree, a change in the
* tree's data, or some other means.
*/
public void setInvokesStopCellEditing(boolean newValue) {
boolean oldValue = invokesStopCellEditing;
invokesStopCellEditing = newValue;
firePropertyChange(INVOKES_STOP_CELL_EDITING_PROPERTY, oldValue,
newValue);
}
/** {@collect.stats}
* Returns the indicator that tells what happens when editing is
* interrupted.
*
* @return the indicator that tells what happens when editing is
* interrupted
* @see #setInvokesStopCellEditing
*/
public boolean getInvokesStopCellEditing() {
return invokesStopCellEditing;
}
/** {@collect.stats}
* Sets the <code>scrollsOnExpand</code> property,
* which determines whether the
* tree might scroll to show previously hidden children.
* If this property is <code>true</code> (the default),
* when a node expands
* the tree can use scrolling to make
* the maximum possible number of the node's descendants visible.
* In some look and feels, trees might not need to scroll when expanded;
* those look and feels will ignore this property.
*
* @param newValue <code>false</code> to disable scrolling on expansion;
* <code>true</code> to enable it
* @see #getScrollsOnExpand
*
* @beaninfo
* bound: true
* description: Indicates if a node descendant should be scrolled when expanded.
*/
public void setScrollsOnExpand(boolean newValue) {
boolean oldValue = scrollsOnExpand;
scrollsOnExpand = newValue;
scrollsOnExpandSet = true;
firePropertyChange(SCROLLS_ON_EXPAND_PROPERTY, oldValue,
newValue);
}
/** {@collect.stats}
* Returns the value of the <code>scrollsOnExpand</code> property.
*
* @return the value of the <code>scrollsOnExpand</code> property
*/
public boolean getScrollsOnExpand() {
return scrollsOnExpand;
}
/** {@collect.stats}
* Sets the number of mouse clicks before a node will expand or close.
* The default is two.
*
* @since 1.3
* @beaninfo
* bound: true
* description: Number of clicks before a node will expand/collapse.
*/
public void setToggleClickCount(int clickCount) {
int oldCount = toggleClickCount;
toggleClickCount = clickCount;
firePropertyChange(TOGGLE_CLICK_COUNT_PROPERTY, oldCount,
clickCount);
}
/** {@collect.stats}
* Returns the number of mouse clicks needed to expand or close a node.
*
* @return number of mouse clicks before node is expanded
* @since 1.3
*/
public int getToggleClickCount() {
return toggleClickCount;
}
/** {@collect.stats}
* Configures the <code>expandsSelectedPaths</code> property. If
* true, any time the selection is changed, either via the
* <code>TreeSelectionModel</code>, or the cover methods provided by
* <code>JTree</code>, the <code>TreePath</code>s parents will be
* expanded to make them visible (visible meaning the parent path is
* expanded, not necessarily in the visible rectangle of the
* <code>JTree</code>). If false, when the selection
* changes the nodes parent is not made visible (all its parents expanded).
* This is useful if you wish to have your selection model maintain paths
* that are not always visible (all parents expanded).
*
* @param newValue the new value for <code>expandsSelectedPaths</code>
*
* @since 1.3
* @beaninfo
* bound: true
* description: Indicates whether changes to the selection should make
* the parent of the path visible.
*/
public void setExpandsSelectedPaths(boolean newValue) {
boolean oldValue = expandsSelectedPaths;
expandsSelectedPaths = newValue;
firePropertyChange(EXPANDS_SELECTED_PATHS_PROPERTY, oldValue,
newValue);
}
/** {@collect.stats}
* Returns the <code>expandsSelectedPaths</code> property.
* @return true if selection changes result in the parent path being
* expanded
* @since 1.3
* @see #setExpandsSelectedPaths
*/
public boolean getExpandsSelectedPaths() {
return expandsSelectedPaths;
}
/** {@collect.stats}
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* tree's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the tree's
* {@code TreeUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* an item and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* tree's {@code TransferHandler}.
*
* @param b whether or not to enable automatic drag handling
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/** {@collect.stats}
* Returns whether or not automatic drag handling is enabled.
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
/** {@collect.stats}
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of one of the other modes is recommended, however, for an
* improved user experience. <code>DropMode.ON</code>, for instance,
* offers similar behavior of showing items as selected, but does so without
* affecting the actual selection in the tree.
* <p>
* <code>JTree</code> supports the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.ON</code></li>
* <li><code>DropMode.INSERT</code></li>
* <li><code>DropMode.ON_OR_INSERT</code></li>
* </ul>
* <p>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see TransferHandler
* @since 1.6
*/
public final void setDropMode(DropMode dropMode) {
if (dropMode != null) {
switch (dropMode) {
case USE_SELECTION:
case ON:
case INSERT:
case ON_OR_INSERT:
this.dropMode = dropMode;
return;
}
}
throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for tree");
}
/** {@collect.stats}
* Returns the drop mode for this component.
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
public final DropMode getDropMode() {
return dropMode;
}
/** {@collect.stats}
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
DropLocation dropLocationForPoint(Point p) {
DropLocation location = null;
int row = getClosestRowForLocation(p.x, p.y);
Rectangle bounds = getRowBounds(row);
TreeModel model = getModel();
Object root = (model == null) ? null : model.getRoot();
TreePath rootPath = (root == null) ? null : new TreePath(root);
TreePath child = null;
TreePath parent = null;
boolean outside = row == -1
|| p.y < bounds.y
|| p.y >= bounds.y + bounds.height;
switch(dropMode) {
case USE_SELECTION:
case ON:
if (outside) {
location = new DropLocation(p, null, -1);
} else {
location = new DropLocation(p, getPathForRow(row), -1);
}
break;
case INSERT:
case ON_OR_INSERT:
if (row == -1) {
if (root != null && !model.isLeaf(root) && isExpanded(rootPath)) {
location = new DropLocation(p, rootPath, 0);
} else {
location = new DropLocation(p, null, -1);
}
break;
}
boolean checkOn = dropMode == DropMode.ON_OR_INSERT
|| !model.isLeaf(getPathForRow(row).getLastPathComponent());
Section section = SwingUtilities2.liesInVertical(bounds, p, checkOn);
if(section == LEADING) {
child = getPathForRow(row);
parent = child.getParentPath();
} else if (section == TRAILING) {
int index = row + 1;
if (index >= getRowCount()) {
if (model.isLeaf(root) || !isExpanded(rootPath)) {
location = new DropLocation(p, null, -1);
} else {
parent = rootPath;
index = model.getChildCount(root);
location = new DropLocation(p, parent, index);
}
break;
}
child = getPathForRow(index);
parent = child.getParentPath();
} else {
assert checkOn;
location = new DropLocation(p, getPathForRow(row), -1);
break;
}
if (parent != null) {
location = new DropLocation(p, parent,
model.getIndexOfChild(parent.getLastPathComponent(),
child.getLastPathComponent()));
} else if (checkOn || !model.isLeaf(root)) {
location = new DropLocation(p, rootPath, -1);
} else {
location = new DropLocation(p, null, -1);
}
break;
default:
assert false : "Unexpected drop mode";
}
if (outside || row != expandRow) {
cancelDropTimer();
}
if (!outside && row != expandRow) {
if (isCollapsed(row)) {
expandRow = row;
startDropTimer();
}
}
return location;
}
/** {@collect.stats}
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
Object retVal = null;
DropLocation treeLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (treeLocation == null) {
if (!forDrop && state != null) {
setSelectionPaths(((TreePath[][])state)[0]);
setAnchorSelectionPath(((TreePath[][])state)[1][0]);
setLeadSelectionPath(((TreePath[][])state)[1][1]);
}
} else {
if (dropLocation == null) {
TreePath[] paths = getSelectionPaths();
if (paths == null) {
paths = new TreePath[0];
}
retVal = new TreePath[][] {paths,
{getAnchorSelectionPath(), getLeadSelectionPath()}};
} else {
retVal = state;
}
setSelectionPath(treeLocation.getPath());
}
}
DropLocation old = dropLocation;
dropLocation = treeLocation;
firePropertyChange("dropLocation", old, dropLocation);
return retVal;
}
/** {@collect.stats}
* Called to indicate to this component that DnD is done.
* Allows for us to cancel the expand timer.
*/
void dndDone() {
cancelDropTimer();
dropTimer = null;
}
/** {@collect.stats}
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public final DropLocation getDropLocation() {
return dropLocation;
}
private void startDropTimer() {
if (dropTimer == null) {
dropTimer = new TreeTimer();
}
dropTimer.start();
}
private void cancelDropTimer() {
if (dropTimer != null && dropTimer.isRunning()) {
expandRow = -1;
dropTimer.stop();
}
}
/** {@collect.stats}
* Returns <code>isEditable</code>. This is invoked from the UI before
* editing begins to insure that the given path can be edited. This
* is provided as an entry point for subclassers to add filtered
* editing without having to resort to creating a new editor.
*
* @return true if every parent node and the node itself is editable
* @see #isEditable
*/
public boolean isPathEditable(TreePath path) {
return isEditable();
}
/** {@collect.stats}
* Overrides <code>JComponent</code>'s <code>getToolTipText</code>
* method in order to allow
* renderer's tips to be used if it has text set.
* <p>
* NOTE: For <code>JTree</code> to properly display tooltips of its
* renderers, <code>JTree</code> must be a registered component with the
* <code>ToolTipManager</code>. This can be done by invoking
* <code>ToolTipManager.sharedInstance().registerComponent(tree)</code>.
* This is not done automatically!
*
* @param event the <code>MouseEvent</code> that initiated the
* <code>ToolTip</code> display
* @return a string containing the tooltip or <code>null</code>
* if <code>event</code> is null
*/
public String getToolTipText(MouseEvent event) {
String tip = null;
if(event != null) {
Point p = event.getPoint();
int selRow = getRowForLocation(p.x, p.y);
TreeCellRenderer r = getCellRenderer();
if(selRow != -1 && r != null) {
TreePath path = getPathForRow(selRow);
Object lastPath = path.getLastPathComponent();
Component rComponent = r.getTreeCellRendererComponent
(this, lastPath, isRowSelected(selRow),
isExpanded(selRow), getModel().isLeaf(lastPath), selRow,
true);
if(rComponent instanceof JComponent) {
MouseEvent newEvent;
Rectangle pathBounds = getPathBounds(path);
p.translate(-pathBounds.x, -pathBounds.y);
newEvent = new MouseEvent(rComponent, event.getID(),
event.getWhen(),
event.getModifiers(),
p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
tip = ((JComponent)rComponent).getToolTipText(newEvent);
}
}
}
// No tip from the renderer get our own tip
if (tip == null) {
tip = getToolTipText();
}
return tip;
}
/** {@collect.stats}
* Called by the renderers to convert the specified value to
* text. This implementation returns <code>value.toString</code>, ignoring
* all other arguments. To control the conversion, subclass this
* method and use any of the arguments you need.
*
* @param value the <code>Object</code> to convert to text
* @param selected true if the node is selected
* @param expanded true if the node is expanded
* @param leaf true if the node is a leaf node
* @param row an integer specifying the node's display row, where 0 is
* the first row in the display
* @param hasFocus true if the node has the focus
* @return the <code>String</code> representation of the node's value
*/
public String convertValueToText(Object value, boolean selected,
boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if(value != null) {
String sValue = value.toString();
if (sValue != null) {
return sValue;
}
}
return "";
}
//
// The following are convenience methods that get forwarded to the
// current TreeUI.
//
/** {@collect.stats}
* Returns the number of rows that are currently being displayed.
*
* @return the number of rows that are being displayed
*/
public int getRowCount() {
TreeUI tree = getUI();
if(tree != null)
return tree.getRowCount(this);
return 0;
}
/** {@collect.stats}
* Selects the node identified by the specified path. If any
* component of the path is hidden (under a collapsed node), and
* <code>getExpandsSelectedPaths</code> is true it is
* exposed (made viewable).
*
* @param path the <code>TreePath</code> specifying the node to select
*/
public void setSelectionPath(TreePath path) {
getSelectionModel().setSelectionPath(path);
}
/** {@collect.stats}
* Selects the nodes identified by the specified array of paths.
* If any component in any of the paths is hidden (under a collapsed
* node), and <code>getExpandsSelectedPaths</code> is true
* it is exposed (made viewable).
*
* @param paths an array of <code>TreePath</code> objects that specifies
* the nodes to select
*/
public void setSelectionPaths(TreePath[] paths) {
getSelectionModel().setSelectionPaths(paths);
}
/** {@collect.stats}
* Sets the path identifies as the lead. The lead may not be selected.
* The lead is not maintained by <code>JTree</code>,
* rather the UI will update it.
*
* @param newPath the new lead path
* @since 1.3
* @beaninfo
* bound: true
* description: Lead selection path
*/
public void setLeadSelectionPath(TreePath newPath) {
TreePath oldValue = leadPath;
leadPath = newPath;
firePropertyChange(LEAD_SELECTION_PATH_PROPERTY, oldValue, newPath);
}
/** {@collect.stats}
* Sets the path identified as the anchor.
* The anchor is not maintained by <code>JTree</code>, rather the UI will
* update it.
*
* @param newPath the new anchor path
* @since 1.3
* @beaninfo
* bound: true
* description: Anchor selection path
*/
public void setAnchorSelectionPath(TreePath newPath) {
TreePath oldValue = anchorPath;
anchorPath = newPath;
firePropertyChange(ANCHOR_SELECTION_PATH_PROPERTY, oldValue, newPath);
}
/** {@collect.stats}
* Selects the node at the specified row in the display.
*
* @param row the row to select, where 0 is the first row in
* the display
*/
public void setSelectionRow(int row) {
int[] rows = { row };
setSelectionRows(rows);
}
/** {@collect.stats}
* Selects the nodes corresponding to each of the specified rows
* in the display. If a particular element of <code>rows</code> is
* < 0 or >= <code>getRowCount</code>, it will be ignored.
* If none of the elements
* in <code>rows</code> are valid rows, the selection will
* be cleared. That is it will be as if <code>clearSelection</code>
* was invoked.
*
* @param rows an array of ints specifying the rows to select,
* where 0 indicates the first row in the display
*/
public void setSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++) {
paths[counter] = ui.getPathForRow(this, rows[counter]);
}
setSelectionPaths(paths);
}
}
/** {@collect.stats}
* Adds the node identified by the specified <code>TreePath</code>
* to the current selection. If any component of the path isn't
* viewable, and <code>getExpandsSelectedPaths</code> is true it is
* made viewable.
* <p>
* Note that <code>JTree</code> does not allow duplicate nodes to
* exist as children under the same parent -- each sibling must be
* a unique object.
*
* @param path the <code>TreePath</code> to add
*/
public void addSelectionPath(TreePath path) {
getSelectionModel().addSelectionPath(path);
}
/** {@collect.stats}
* Adds each path in the array of paths to the current selection. If
* any component of any of the paths isn't viewable and
* <code>getExpandsSelectedPaths</code> is true, it is
* made viewable.
* <p>
* Note that <code>JTree</code> does not allow duplicate nodes to
* exist as children under the same parent -- each sibling must be
* a unique object.
*
* @param paths an array of <code>TreePath</code> objects that specifies
* the nodes to add
*/
public void addSelectionPaths(TreePath[] paths) {
getSelectionModel().addSelectionPaths(paths);
}
/** {@collect.stats}
* Adds the path at the specified row to the current selection.
*
* @param row an integer specifying the row of the node to add,
* where 0 is the first row in the display
*/
public void addSelectionRow(int row) {
int[] rows = { row };
addSelectionRows(rows);
}
/** {@collect.stats}
* Adds the paths at each of the specified rows to the current selection.
*
* @param rows an array of ints specifying the rows to add,
* where 0 indicates the first row in the display
*/
public void addSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++)
paths[counter] = ui.getPathForRow(this, rows[counter]);
addSelectionPaths(paths);
}
}
/** {@collect.stats}
* Returns the last path component in the first node of the current
* selection.
*
* @return the last <code>Object</code> in the first selected node's
* <code>TreePath</code>,
* or <code>null</code> if nothing is selected
* @see TreePath#getLastPathComponent
*/
public Object getLastSelectedPathComponent() {
TreePath selPath = getSelectionModel().getSelectionPath();
if(selPath != null)
return selPath.getLastPathComponent();
return null;
}
/** {@collect.stats}
* Returns the path identified as the lead.
* @return path identified as the lead
*/
public TreePath getLeadSelectionPath() {
return leadPath;
}
/** {@collect.stats}
* Returns the path identified as the anchor.
* @return path identified as the anchor
* @since 1.3
*/
public TreePath getAnchorSelectionPath() {
return anchorPath;
}
/** {@collect.stats}
* Returns the path to the first selected node.
*
* @return the <code>TreePath</code> for the first selected node,
* or <code>null</code> if nothing is currently selected
*/
public TreePath getSelectionPath() {
return getSelectionModel().getSelectionPath();
}
/** {@collect.stats}
* Returns the paths of all selected values.
*
* @return an array of <code>TreePath</code> objects indicating the selected
* nodes, or <code>null</code> if nothing is currently selected
*/
public TreePath[] getSelectionPaths() {
return getSelectionModel().getSelectionPaths();
}
/** {@collect.stats}
* Returns all of the currently selected rows. This method is simply
* forwarded to the <code>TreeSelectionModel</code>.
* If nothing is selected <code>null</code> or an empty array will
* be returned, based on the <code>TreeSelectionModel</code>
* implementation.
*
* @return an array of integers that identifies all currently selected rows
* where 0 is the first row in the display
*/
public int[] getSelectionRows() {
return getSelectionModel().getSelectionRows();
}
/** {@collect.stats}
* Returns the number of nodes selected.
*
* @return the number of nodes selected
*/
public int getSelectionCount() {
return selectionModel.getSelectionCount();
}
/** {@collect.stats}
* Gets the first selected row.
*
* @return an integer designating the first selected row, where 0 is the
* first row in the display
*/
public int getMinSelectionRow() {
return getSelectionModel().getMinSelectionRow();
}
/** {@collect.stats}
* Returns the last selected row.
*
* @return an integer designating the last selected row, where 0 is the
* first row in the display
*/
public int getMaxSelectionRow() {
return getSelectionModel().getMaxSelectionRow();
}
/** {@collect.stats}
* Returns the row index corresponding to the lead path.
*
* @return an integer giving the row index of the lead path,
* where 0 is the first row in the display; or -1
* if <code>leadPath</code> is <code>null</code>
*/
public int getLeadSelectionRow() {
TreePath leadPath = getLeadSelectionPath();
if (leadPath != null) {
return getRowForPath(leadPath);
}
return -1;
}
/** {@collect.stats}
* Returns true if the item identified by the path is currently selected.
*
* @param path a <code>TreePath</code> identifying a node
* @return true if the node is selected
*/
public boolean isPathSelected(TreePath path) {
return getSelectionModel().isPathSelected(path);
}
/** {@collect.stats}
* Returns true if the node identified by row is selected.
*
* @param row an integer specifying a display row, where 0 is the first
* row in the display
* @return true if the node is selected
*/
public boolean isRowSelected(int row) {
return getSelectionModel().isRowSelected(row);
}
/** {@collect.stats}
* Returns an <code>Enumeration</code> of the descendants of the
* path <code>parent</code> that
* are currently expanded. If <code>parent</code> is not currently
* expanded, this will return <code>null</code>.
* If you expand/collapse nodes while
* iterating over the returned <code>Enumeration</code>
* this may not return all
* the expanded paths, or may return paths that are no longer expanded.
*
* @param parent the path which is to be examined
* @return an <code>Enumeration</code> of the descendents of
* <code>parent</code>, or <code>null</code> if
* <code>parent</code> is not currently expanded
*/
public Enumeration<TreePath> getExpandedDescendants(TreePath parent) {
if(!isExpanded(parent))
return null;
Enumeration toggledPaths = expandedState.keys();
Vector elements = null;
TreePath path;
Object value;
if(toggledPaths != null) {
while(toggledPaths.hasMoreElements()) {
path = (TreePath)toggledPaths.nextElement();
value = expandedState.get(path);
// Add the path if it is expanded, a descendant of parent,
// and it is visible (all parents expanded). This is rather
// expensive!
if(path != parent && value != null &&
((Boolean)value).booleanValue() &&
parent.isDescendant(path) && isVisible(path)) {
if (elements == null) {
elements = new Vector();
}
elements.addElement(path);
}
}
}
if (elements == null) {
Set<TreePath> empty = Collections.emptySet();
return Collections.enumeration(empty);
}
return elements.elements();
}
/** {@collect.stats}
* Returns true if the node identified by the path has ever been
* expanded.
* @return true if the <code>path</code> has ever been expanded
*/
public boolean hasBeenExpanded(TreePath path) {
return (path != null && expandedState.get(path) != null);
}
/** {@collect.stats}
* Returns true if the node identified by the path is currently expanded,
*
* @param path the <code>TreePath</code> specifying the node to check
* @return false if any of the nodes in the node's path are collapsed,
* true if all nodes in the path are expanded
*/
public boolean isExpanded(TreePath path) {
if(path == null)
return false;
// Is this node expanded?
Object value = expandedState.get(path);
if(value == null || !((Boolean)value).booleanValue())
return false;
// It is, make sure its parent is also expanded.
TreePath parentPath = path.getParentPath();
if(parentPath != null)
return isExpanded(parentPath);
return true;
}
/** {@collect.stats}
* Returns true if the node at the specified display row is currently
* expanded.
*
* @param row the row to check, where 0 is the first row in the
* display
* @return true if the node is currently expanded, otherwise false
*/
public boolean isExpanded(int row) {
TreeUI tree = getUI();
if(tree != null) {
TreePath path = tree.getPathForRow(this, row);
if(path != null) {
Boolean value = (Boolean)expandedState.get(path);
return (value != null && value.booleanValue());
}
}
return false;
}
/** {@collect.stats}
* Returns true if the value identified by path is currently collapsed,
* this will return false if any of the values in path are currently
* not being displayed.
*
* @param path the <code>TreePath</code> to check
* @return true if any of the nodes in the node's path are collapsed,
* false if all nodes in the path are expanded
*/
public boolean isCollapsed(TreePath path) {
return !isExpanded(path);
}
/** {@collect.stats}
* Returns true if the node at the specified display row is collapsed.
*
* @param row the row to check, where 0 is the first row in the
* display
* @return true if the node is currently collapsed, otherwise false
*/
public boolean isCollapsed(int row) {
return !isExpanded(row);
}
/** {@collect.stats}
* Ensures that the node identified by path is currently viewable.
*
* @param path the <code>TreePath</code> to make visible
*/
public void makeVisible(TreePath path) {
if(path != null) {
TreePath parentPath = path.getParentPath();
if(parentPath != null) {
expandPath(parentPath);
}
}
}
/** {@collect.stats}
* Returns true if the value identified by path is currently viewable,
* which means it is either the root or all of its parents are expanded.
* Otherwise, this method returns false.
*
* @return true if the node is viewable, otherwise false
*/
public boolean isVisible(TreePath path) {
if(path != null) {
TreePath parentPath = path.getParentPath();
if(parentPath != null)
return isExpanded(parentPath);
// Root.
return true;
}
return false;
}
/** {@collect.stats}
* Returns the <code>Rectangle</code> that the specified node will be drawn
* into. Returns <code>null</code> if any component in the path is hidden
* (under a collapsed parent).
* <p>
* Note:<br>
* This method returns a valid rectangle, even if the specified
* node is not currently displayed.
*
* @param path the <code>TreePath</code> identifying the node
* @return the <code>Rectangle</code> the node is drawn in,
* or <code>null</code>
*/
public Rectangle getPathBounds(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
return tree.getPathBounds(this, path);
return null;
}
/** {@collect.stats}
* Returns the <code>Rectangle</code> that the node at the specified row is
* drawn in.
*
* @param row the row to be drawn, where 0 is the first row in the
* display
* @return the <code>Rectangle</code> the node is drawn in
*/
public Rectangle getRowBounds(int row) {
return getPathBounds(getPathForRow(row));
}
/** {@collect.stats}
* Makes sure all the path components in path are expanded (except
* for the last path component) and scrolls so that the
* node identified by the path is displayed. Only works when this
* <code>JTree</code> is contained in a <code>JScrollPane</code>.
*
* @param path the <code>TreePath</code> identifying the node to
* bring into view
*/
public void scrollPathToVisible(TreePath path) {
if(path != null) {
makeVisible(path);
Rectangle bounds = getPathBounds(path);
if(bounds != null) {
scrollRectToVisible(bounds);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
}
}
/** {@collect.stats}
* Scrolls the item identified by row until it is displayed. The minimum
* of amount of scrolling necessary to bring the row into view
* is performed. Only works when this <code>JTree</code> is contained in a
* <code>JScrollPane</code>.
*
* @param row an integer specifying the row to scroll, where 0 is the
* first row in the display
*/
public void scrollRowToVisible(int row) {
scrollPathToVisible(getPathForRow(row));
}
/** {@collect.stats}
* Returns the path for the specified row. If <code>row</code> is
* not visible, <code>null</code> is returned.
*
* @param row an integer specifying a row
* @return the <code>TreePath</code> to the specified node,
* <code>null</code> if <code>row < 0</code>
* or <code>row > getRowCount()</code>
*/
public TreePath getPathForRow(int row) {
TreeUI tree = getUI();
if(tree != null)
return tree.getPathForRow(this, row);
return null;
}
/** {@collect.stats}
* Returns the row that displays the node identified by the specified
* path.
*
* @param path the <code>TreePath</code> identifying a node
* @return an integer specifying the display row, where 0 is the first
* row in the display, or -1 if any of the elements in path
* are hidden under a collapsed parent.
*/
public int getRowForPath(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
return tree.getRowForPath(this, path);
return -1;
}
/** {@collect.stats}
* Ensures that the node identified by the specified path is
* expanded and viewable. If the last item in the path is a
* leaf, this will have no effect.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void expandPath(TreePath path) {
// Only expand if not leaf!
TreeModel model = getModel();
if(path != null && model != null &&
!model.isLeaf(path.getLastPathComponent())) {
setExpandedState(path, true);
}
}
/** {@collect.stats}
* Ensures that the node in the specified row is expanded and
* viewable.
* <p>
* If <code>row</code> is < 0 or >= <code>getRowCount</code> this
* will have no effect.
*
* @param row an integer specifying a display row, where 0 is the
* first row in the display
*/
public void expandRow(int row) {
expandPath(getPathForRow(row));
}
/** {@collect.stats}
* Ensures that the node identified by the specified path is
* collapsed and viewable.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void collapsePath(TreePath path) {
setExpandedState(path, false);
}
/** {@collect.stats}
* Ensures that the node in the specified row is collapsed.
* <p>
* If <code>row</code> is < 0 or >= <code>getRowCount</code> this
* will have no effect.
*
* @param row an integer specifying a display row, where 0 is the
* first row in the display
*/
public void collapseRow(int row) {
collapsePath(getPathForRow(row));
}
/** {@collect.stats}
* Returns the path for the node at the specified location.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the <code>TreePath</code> for the node at that location
*/
public TreePath getPathForLocation(int x, int y) {
TreePath closestPath = getClosestPathForLocation(x, y);
if(closestPath != null) {
Rectangle pathBounds = getPathBounds(closestPath);
if(pathBounds != null &&
x >= pathBounds.x && x < (pathBounds.x + pathBounds.width) &&
y >= pathBounds.y && y < (pathBounds.y + pathBounds.height))
return closestPath;
}
return null;
}
/** {@collect.stats}
* Returns the row for the specified location.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the row corresponding to the location, or -1 if the
* location is not within the bounds of a displayed cell
* @see #getClosestRowForLocation
*/
public int getRowForLocation(int x, int y) {
return getRowForPath(getPathForLocation(x, y));
}
/** {@collect.stats}
* Returns the path to the node that is closest to x,y. If
* no nodes are currently viewable, or there is no model, returns
* <code>null</code>, otherwise it always returns a valid path. To test if
* the node is exactly at x, y, get the node's bounds and
* test x, y against that.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the <code>TreePath</code> for the node closest to that location,
* <code>null</code> if nothing is viewable or there is no model
*
* @see #getPathForLocation
* @see #getPathBounds
*/
public TreePath getClosestPathForLocation(int x, int y) {
TreeUI tree = getUI();
if(tree != null)
return tree.getClosestPathForLocation(this, x, y);
return null;
}
/** {@collect.stats}
* Returns the row to the node that is closest to x,y. If no nodes
* are viewable or there is no model, returns -1. Otherwise,
* it always returns a valid row. To test if the returned object is
* exactly at x, y, get the bounds for the node at the returned
* row and test x, y against that.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the row closest to the location, -1 if nothing is
* viewable or there is no model
*
* @see #getRowForLocation
* @see #getRowBounds
*/
public int getClosestRowForLocation(int x, int y) {
return getRowForPath(getClosestPathForLocation(x, y));
}
/** {@collect.stats}
* Returns true if the tree is being edited. The item that is being
* edited can be obtained using <code>getSelectionPath</code>.
*
* @return true if the user is currently editing a node
* @see #getSelectionPath
*/
public boolean isEditing() {
TreeUI tree = getUI();
if(tree != null)
return tree.isEditing(this);
return false;
}
/** {@collect.stats}
* Ends the current editing session.
* (The <code>DefaultTreeCellEditor</code>
* object saves any edits that are currently in progress on a cell.
* Other implementations may operate differently.)
* Has no effect if the tree isn't being edited.
* <blockquote>
* <b>Note:</b><br>
* To make edit-saves automatic whenever the user changes
* their position in the tree, use {@link #setInvokesStopCellEditing}.
* </blockquote>
*
* @return true if editing was in progress and is now stopped,
* false if editing was not in progress
*/
public boolean stopEditing() {
TreeUI tree = getUI();
if(tree != null)
return tree.stopEditing(this);
return false;
}
/** {@collect.stats}
* Cancels the current editing session. Has no effect if the
* tree isn't being edited.
*/
public void cancelEditing() {
TreeUI tree = getUI();
if(tree != null)
tree.cancelEditing(this);
}
/** {@collect.stats}
* Selects the node identified by the specified path and initiates
* editing. The edit-attempt fails if the <code>CellEditor</code>
* does not allow
* editing for the specified item.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void startEditingAtPath(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
tree.startEditingAtPath(this, path);
}
/** {@collect.stats}
* Returns the path to the element that is currently being edited.
*
* @return the <code>TreePath</code> for the node being edited
*/
public TreePath getEditingPath() {
TreeUI tree = getUI();
if(tree != null)
return tree.getEditingPath(this);
return null;
}
//
// Following are primarily convenience methods for mapping from
// row based selections to path selections. Sometimes it is
// easier to deal with these than paths (mouse downs, key downs
// usually just deal with index based selections).
// Since row based selections require a UI many of these won't work
// without one.
//
/** {@collect.stats}
* Sets the tree's selection model. When a <code>null</code> value is
* specified an empty
* <code>selectionModel</code> is used, which does not allow selections.
*
* @param selectionModel the <code>TreeSelectionModel</code> to use,
* or <code>null</code> to disable selections
* @see TreeSelectionModel
* @beaninfo
* bound: true
* description: The tree's selection model.
*/
public void setSelectionModel(TreeSelectionModel selectionModel) {
if(selectionModel == null)
selectionModel = EmptySelectionModel.sharedInstance();
TreeSelectionModel oldValue = this.selectionModel;
if (this.selectionModel != null && selectionRedirector != null) {
this.selectionModel.removeTreeSelectionListener
(selectionRedirector);
}
if (accessibleContext != null) {
this.selectionModel.removeTreeSelectionListener((TreeSelectionListener)accessibleContext);
selectionModel.addTreeSelectionListener((TreeSelectionListener)accessibleContext);
}
this.selectionModel = selectionModel;
if (selectionRedirector != null) {
this.selectionModel.addTreeSelectionListener(selectionRedirector);
}
firePropertyChange(SELECTION_MODEL_PROPERTY, oldValue,
this.selectionModel);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
}
/** {@collect.stats}
* Returns the model for selections. This should always return a
* non-<code>null</code> value. If you don't want to allow anything
* to be selected
* set the selection model to <code>null</code>, which forces an empty
* selection model to be used.
*
* @see #setSelectionModel
*/
public TreeSelectionModel getSelectionModel() {
return selectionModel;
}
/** {@collect.stats}
* Returns <code>JTreePath</code> instances representing the path
* between index0 and index1 (including index1).
* Returns <code>null</code> if there is no tree.
*
* @param index0 an integer specifying a display row, where 0 is the
* first row in the display
* @param index1 an integer specifying a second display row
* @return an array of <code>TreePath</code> objects, one for each
* node between index0 and index1, inclusive; or <code>null</code>
* if there is no tree
*/
protected TreePath[] getPathBetweenRows(int index0, int index1) {
int newMinIndex, newMaxIndex;
TreeUI tree = getUI();
newMinIndex = Math.min(index0, index1);
newMaxIndex = Math.max(index0, index1);
if(tree != null) {
TreePath[] selection = new TreePath[newMaxIndex - newMinIndex + 1];
for(int counter = newMinIndex; counter <= newMaxIndex; counter++) {
selection[counter - newMinIndex] = tree.getPathForRow(this, counter);
}
return selection;
}
return null;
}
/** {@collect.stats}
* Selects the nodes between index0 and index1, inclusive.
*
* @param index0 an integer specifying a display row, where 0 is the
* first row in the display
* @param index1 an integer specifying a second display row
*/
public void setSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
this.getSelectionModel().setSelectionPaths(paths);
}
/** {@collect.stats}
* Adds the paths between index0 and index1, inclusive, to the
* selection.
*
* @param index0 an integer specifying a display row, where 0 is the
* first row in the display
* @param index1 an integer specifying a second display row
*/
public void addSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
this.getSelectionModel().addSelectionPaths(paths);
}
/** {@collect.stats}
* Removes the nodes between index0 and index1, inclusive, from the
* selection.
*
* @param index0 an integer specifying a display row, where 0 is the
* first row in the display
* @param index1 an integer specifying a second display row
*/
public void removeSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
this.getSelectionModel().removeSelectionPaths(paths);
}
/** {@collect.stats}
* Removes the node identified by the specified path from the current
* selection.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void removeSelectionPath(TreePath path) {
this.getSelectionModel().removeSelectionPath(path);
}
/** {@collect.stats}
* Removes the nodes identified by the specified paths from the
* current selection.
*
* @param paths an array of <code>TreePath</code> objects that
* specifies the nodes to remove
*/
public void removeSelectionPaths(TreePath[] paths) {
this.getSelectionModel().removeSelectionPaths(paths);
}
/** {@collect.stats}
* Removes the row at the index <code>row</code> from the current
* selection.
*
* @param row the row to remove
*/
public void removeSelectionRow(int row) {
int[] rows = { row };
removeSelectionRows(rows);
}
/** {@collect.stats}
* Removes the rows that are selected at each of the specified
* rows.
*
* @param rows an array of ints specifying display rows, where 0 is
* the first row in the display
*/
public void removeSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++)
paths[counter] = ui.getPathForRow(this, rows[counter]);
removeSelectionPaths(paths);
}
}
/** {@collect.stats}
* Clears the selection.
*/
public void clearSelection() {
getSelectionModel().clearSelection();
}
/** {@collect.stats}
* Returns true if the selection is currently empty.
*
* @return true if the selection is currently empty
*/
public boolean isSelectionEmpty() {
return getSelectionModel().isSelectionEmpty();
}
/** {@collect.stats}
* Adds a listener for <code>TreeExpansion</code> events.
*
* @param tel a TreeExpansionListener that will be notified when
* a tree node is expanded or collapsed (a "negative
* expansion")
*/
public void addTreeExpansionListener(TreeExpansionListener tel) {
if (settingUI) {
uiTreeExpansionListener = tel;
}
listenerList.add(TreeExpansionListener.class, tel);
}
/** {@collect.stats}
* Removes a listener for <code>TreeExpansion</code> events.
*
* @param tel the <code>TreeExpansionListener</code> to remove
*/
public void removeTreeExpansionListener(TreeExpansionListener tel) {
listenerList.remove(TreeExpansionListener.class, tel);
if (uiTreeExpansionListener == tel) {
uiTreeExpansionListener = null;
}
}
/** {@collect.stats}
* Returns an array of all the <code>TreeExpansionListener</code>s added
* to this JTree with addTreeExpansionListener().
*
* @return all of the <code>TreeExpansionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeExpansionListener[] getTreeExpansionListeners() {
return (TreeExpansionListener[])listenerList.getListeners(
TreeExpansionListener.class);
}
/** {@collect.stats}
* Adds a listener for <code>TreeWillExpand</code> events.
*
* @param tel a <code>TreeWillExpandListener</code> that will be notified
* when a tree node will be expanded or collapsed (a "negative
* expansion")
*/
public void addTreeWillExpandListener(TreeWillExpandListener tel) {
listenerList.add(TreeWillExpandListener.class, tel);
}
/** {@collect.stats}
* Removes a listener for <code>TreeWillExpand</code> events.
*
* @param tel the <code>TreeWillExpandListener</code> to remove
*/
public void removeTreeWillExpandListener(TreeWillExpandListener tel) {
listenerList.remove(TreeWillExpandListener.class, tel);
}
/** {@collect.stats}
* Returns an array of all the <code>TreeWillExpandListener</code>s added
* to this JTree with addTreeWillExpandListener().
*
* @return all of the <code>TreeWillExpandListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeWillExpandListener[] getTreeWillExpandListeners() {
return (TreeWillExpandListener[])listenerList.getListeners(
TreeWillExpandListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeExpanded(TreePath path) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
if (uiTreeExpansionListener != null) {
e = new TreeExpansionEvent(this, path);
uiTreeExpansionListener.treeExpanded(e);
}
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeExpansionListener.class &&
listeners[i + 1] != uiTreeExpansionListener) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeExpansionListener)listeners[i+1]).
treeExpanded(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* collapsed
* @see EventListenerList
*/
public void fireTreeCollapsed(TreePath path) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
if (uiTreeExpansionListener != null) {
e = new TreeExpansionEvent(this, path);
uiTreeExpansionListener.treeCollapsed(e);
}
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeExpansionListener.class &&
listeners[i + 1] != uiTreeExpansionListener) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeExpansionListener)listeners[i+1]).
treeCollapsed(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeWillExpand(TreePath path) throws ExpandVetoException {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeWillExpandListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeWillExpandListener)listeners[i+1]).
treeWillExpand(e);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeWillCollapse(TreePath path) throws ExpandVetoException {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeWillExpandListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeWillExpandListener)listeners[i+1]).
treeWillCollapse(e);
}
}
}
/** {@collect.stats}
* Adds a listener for <code>TreeSelection</code> events.
*
* @param tsl the <code>TreeSelectionListener</code> that will be notified
* when a node is selected or deselected (a "negative
* selection")
*/
public void addTreeSelectionListener(TreeSelectionListener tsl) {
listenerList.add(TreeSelectionListener.class,tsl);
if(listenerList.getListenerCount(TreeSelectionListener.class) != 0
&& selectionRedirector == null) {
selectionRedirector = new TreeSelectionRedirector();
selectionModel.addTreeSelectionListener(selectionRedirector);
}
}
/** {@collect.stats}
* Removes a <code>TreeSelection</code> listener.
*
* @param tsl the <code>TreeSelectionListener</code> to remove
*/
public void removeTreeSelectionListener(TreeSelectionListener tsl) {
listenerList.remove(TreeSelectionListener.class,tsl);
if(listenerList.getListenerCount(TreeSelectionListener.class) == 0
&& selectionRedirector != null) {
selectionModel.removeTreeSelectionListener
(selectionRedirector);
selectionRedirector = null;
}
}
/** {@collect.stats}
* Returns an array of all the <code>TreeSelectionListener</code>s added
* to this JTree with addTreeSelectionListener().
*
* @return all of the <code>TreeSelectionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeSelectionListener[] getTreeSelectionListeners() {
return (TreeSelectionListener[])listenerList.getListeners(
TreeSelectionListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param e the <code>TreeSelectionEvent</code> to be fired;
* generated by the
* <code>TreeSelectionModel</code>
* when a node is selected or deselected
* @see EventListenerList
*/
protected void fireValueChanged(TreeSelectionEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
// TreeSelectionEvent e = null;
if (listeners[i]==TreeSelectionListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((TreeSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
/** {@collect.stats}
* Sent when the tree has changed enough that we need to resize
* the bounds, but not enough that we need to remove the
* expanded node set (e.g nodes were expanded or collapsed, or
* nodes were inserted into the tree). You should never have to
* invoke this, the UI will invoke this as it needs to.
*/
public void treeDidChange() {
revalidate();
repaint();
}
/** {@collect.stats}
* Sets the number of rows that are to be displayed.
* This will only work if the tree is contained in a
* <code>JScrollPane</code>,
* and will adjust the preferred size and size of that scrollpane.
*
* @param newCount the number of rows to display
* @beaninfo
* bound: true
* description: The number of rows that are to be displayed.
*/
public void setVisibleRowCount(int newCount) {
int oldCount = visibleRowCount;
visibleRowCount = newCount;
firePropertyChange(VISIBLE_ROW_COUNT_PROPERTY, oldCount,
visibleRowCount);
invalidate();
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
/** {@collect.stats}
* Returns the number of rows that are displayed in the display area.
*
* @return the number of rows displayed
*/
public int getVisibleRowCount() {
return visibleRowCount;
}
/** {@collect.stats}
* Expands the root path, assuming the current TreeModel has been set.
*/
private void expandRoot() {
TreeModel model = getModel();
if(model != null && model.getRoot() != null) {
expandPath(new TreePath(model.getRoot()));
}
}
/** {@collect.stats}
* Returns the TreePath to the next tree element that
* begins with a prefix. To handle the conversion of a
* <code>TreePath</code> into a String, <code>convertValueToText</code>
* is used.
*
* @param prefix the string to test for a match
* @param startingRow the row for starting the search
* @param bias the search direction, either
* Position.Bias.Forward or Position.Bias.Backward.
* @return the TreePath of the next tree element that
* starts with the prefix; otherwise null
* @exception IllegalArgumentException if prefix is null
* or startingRow is out of bounds
* @since 1.4
*/
public TreePath getNextMatch(String prefix, int startingRow,
Position.Bias bias) {
int max = getRowCount();
if (prefix == null) {
throw new IllegalArgumentException();
}
if (startingRow < 0 || startingRow >= max) {
throw new IllegalArgumentException();
}
prefix = prefix.toUpperCase();
// start search from the next/previous element froom the
// selected element
int increment = (bias == Position.Bias.Forward) ? 1 : -1;
int row = startingRow;
do {
TreePath path = getPathForRow(row);
String text = convertValueToText(
path.getLastPathComponent(), isRowSelected(row),
isExpanded(row), true, row, false);
if (text.toUpperCase().startsWith(prefix)) {
return path;
}
row = (row + increment + max) % max;
} while (row != startingRow);
return null;
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Vector values = new Vector();
s.defaultWriteObject();
// Save the cellRenderer, if its Serializable.
if(cellRenderer != null && cellRenderer instanceof Serializable) {
values.addElement("cellRenderer");
values.addElement(cellRenderer);
}
// Save the cellEditor, if its Serializable.
if(cellEditor != null && cellEditor instanceof Serializable) {
values.addElement("cellEditor");
values.addElement(cellEditor);
}
// Save the treeModel, if its Serializable.
if(treeModel != null && treeModel instanceof Serializable) {
values.addElement("treeModel");
values.addElement(treeModel);
}
// Save the selectionModel, if its Serializable.
if(selectionModel != null && selectionModel instanceof Serializable) {
values.addElement("selectionModel");
values.addElement(selectionModel);
}
Object expandedData = getArchivableExpandedState();
if(expandedData != null) {
values.addElement("expandedState");
values.addElement(expandedData);
}
s.writeObject(values);
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Create an instance of expanded state.
expandedState = new Hashtable();
expandedStack = new Stack();
Vector values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("cellRenderer")) {
cellRenderer = (TreeCellRenderer)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("cellEditor")) {
cellEditor = (TreeCellEditor)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("treeModel")) {
treeModel = (TreeModel)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("selectionModel")) {
selectionModel = (TreeSelectionModel)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("expandedState")) {
unarchiveExpandedState(values.elementAt(++indexCounter));
indexCounter++;
}
// Reinstall the redirector.
if(listenerList.getListenerCount(TreeSelectionListener.class) != 0) {
selectionRedirector = new TreeSelectionRedirector();
selectionModel.addTreeSelectionListener(selectionRedirector);
}
// Listener to TreeModel.
if(treeModel != null) {
treeModelListener = createTreeModelListener();
if(treeModelListener != null)
treeModel.addTreeModelListener(treeModelListener);
}
}
/** {@collect.stats}
* Returns an object that can be archived indicating what nodes are
* expanded and what aren't. The objects from the model are NOT
* written out.
*/
private Object getArchivableExpandedState() {
TreeModel model = getModel();
if(model != null) {
Enumeration paths = expandedState.keys();
if(paths != null) {
Vector state = new Vector();
while(paths.hasMoreElements()) {
TreePath path = (TreePath)paths.nextElement();
Object archivePath;
try {
archivePath = getModelIndexsForPath(path);
} catch (Error error) {
archivePath = null;
}
if(archivePath != null) {
state.addElement(archivePath);
state.addElement(expandedState.get(path));
}
}
return state;
}
}
return null;
}
/** {@collect.stats}
* Updates the expanded state of nodes in the tree based on the
* previously archived state <code>state</code>.
*/
private void unarchiveExpandedState(Object state) {
if(state instanceof Vector) {
Vector paths = (Vector)state;
for(int counter = paths.size() - 1; counter >= 0; counter--) {
Boolean eState = (Boolean)paths.elementAt(counter--);
TreePath path;
try {
path = getPathForIndexs((int[])paths.elementAt(counter));
if(path != null)
expandedState.put(path, eState);
} catch (Error error) {}
}
}
}
/** {@collect.stats}
* Returns an array of integers specifying the indexs of the
* components in the <code>path</code>. If <code>path</code> is
* the root, this will return an empty array. If <code>path</code>
* is <code>null</code>, <code>null</code> will be returned.
*/
private int[] getModelIndexsForPath(TreePath path) {
if(path != null) {
TreeModel model = getModel();
int count = path.getPathCount();
int[] indexs = new int[count - 1];
Object parent = model.getRoot();
for(int counter = 1; counter < count; counter++) {
indexs[counter - 1] = model.getIndexOfChild
(parent, path.getPathComponent(counter));
parent = path.getPathComponent(counter);
if(indexs[counter - 1] < 0)
return null;
}
return indexs;
}
return null;
}
/** {@collect.stats}
* Returns a <code>TreePath</code> created by obtaining the children
* for each of the indices in <code>indexs</code>. If <code>indexs</code>
* or the <code>TreeModel</code> is <code>null</code>, it will return
* <code>null</code>.
*/
private TreePath getPathForIndexs(int[] indexs) {
if(indexs == null)
return null;
TreeModel model = getModel();
if(model == null)
return null;
int count = indexs.length;
Object parent = model.getRoot();
TreePath parentPath = new TreePath(parent);
for(int counter = 0; counter < count; counter++) {
parent = model.getChild(parent, indexs[counter]);
if(parent == null)
return null;
parentPath = parentPath.pathByAddingChild(parent);
}
return parentPath;
}
/** {@collect.stats}
* <code>EmptySelectionModel</code> is a <code>TreeSelectionModel</code>
* that does not allow anything to be selected.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected static class EmptySelectionModel extends
DefaultTreeSelectionModel
{
/** {@collect.stats} Unique shared instance. */
protected static final EmptySelectionModel sharedInstance =
new EmptySelectionModel();
/** {@collect.stats} Returns a shared instance of an empty selection model. */
static public EmptySelectionModel sharedInstance() {
return sharedInstance;
}
/** {@collect.stats} A <code>null</code> implementation that selects nothing. */
public void setSelectionPaths(TreePath[] pPaths) {}
/** {@collect.stats} A <code>null</code> implementation that adds nothing. */
public void addSelectionPaths(TreePath[] paths) {}
/** {@collect.stats} A <code>null</code> implementation that removes nothing. */
public void removeSelectionPaths(TreePath[] paths) {}
}
/** {@collect.stats}
* Handles creating a new <code>TreeSelectionEvent</code> with the
* <code>JTree</code> as the
* source and passing it off to all the listeners.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class TreeSelectionRedirector implements Serializable,
TreeSelectionListener
{
/** {@collect.stats}
* Invoked by the <code>TreeSelectionModel</code> when the
* selection changes.
*
* @param e the <code>TreeSelectionEvent</code> generated by the
* <code>TreeSelectionModel</code>
*/
public void valueChanged(TreeSelectionEvent e) {
TreeSelectionEvent newE;
newE = (TreeSelectionEvent)e.cloneWithSource(JTree.this);
fireValueChanged(newE);
}
} // End of class JTree.TreeSelectionRedirector
//
// Scrollable interface
//
/** {@collect.stats}
* Returns the preferred display size of a <code>JTree</code>. The height is
* determined from <code>getVisibleRowCount</code> and the width
* is the current preferred width.
*
* @return a <code>Dimension</code> object containing the preferred size
*/
public Dimension getPreferredScrollableViewportSize() {
int width = getPreferredSize().width;
int visRows = getVisibleRowCount();
int height = -1;
if(isFixedRowHeight())
height = visRows * getRowHeight();
else {
TreeUI ui = getUI();
if (ui != null && visRows > 0) {
int rc = ui.getRowCount(this);
if (rc >= visRows) {
Rectangle bounds = getRowBounds(visRows - 1);
if (bounds != null) {
height = bounds.y + bounds.height;
}
}
else if (rc > 0) {
Rectangle bounds = getRowBounds(0);
if (bounds != null) {
height = bounds.height * visRows;
}
}
}
if (height == -1) {
height = 16 * visRows;
}
}
return new Dimension(width, height);
}
/** {@collect.stats}
* Returns the amount to increment when scrolling. The amount is
* the height of the first displayed row that isn't completely in view
* or, if it is totally displayed, the height of the next row in the
* scrolling direction.
*
* @param visibleRect the view area visible within the viewport
* @param orientation either <code>SwingConstants.VERTICAL</code>
* or <code>SwingConstants.HORIZONTAL</code>
* @param direction less than zero to scroll up/left,
* greater than zero for down/right
* @return the "unit" increment for scrolling in the specified direction
* @see JScrollBar#setUnitIncrement(int)
*/
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction) {
if(orientation == SwingConstants.VERTICAL) {
Rectangle rowBounds;
int firstIndex = getClosestRowForLocation
(0, visibleRect.y);
if(firstIndex != -1) {
rowBounds = getRowBounds(firstIndex);
if(rowBounds.y != visibleRect.y) {
if(direction < 0) {
// UP
return Math.max(0, (visibleRect.y - rowBounds.y));
}
return (rowBounds.y + rowBounds.height - visibleRect.y);
}
if(direction < 0) { // UP
if(firstIndex != 0) {
rowBounds = getRowBounds(firstIndex - 1);
return rowBounds.height;
}
}
else {
return rowBounds.height;
}
}
return 0;
}
return 4;
}
/** {@collect.stats}
* Returns the amount for a block increment, which is the height or
* width of <code>visibleRect</code>, based on <code>orientation</code>.
*
* @param visibleRect the view area visible within the viewport
* @param orientation either <code>SwingConstants.VERTICAL</code>
* or <code>SwingConstants.HORIZONTAL</code>
* @param direction less than zero to scroll up/left,
* greater than zero for down/right.
* @return the "block" increment for scrolling in the specified direction
* @see JScrollBar#setBlockIncrement(int)
*/
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) {
return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
visibleRect.width;
}
/** {@collect.stats}
* Returns false to indicate that the width of the viewport does not
* determine the width of the table, unless the preferred width of
* the tree is smaller than the viewports width. In other words:
* ensure that the tree is never smaller than its viewport.
*
* @return false
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
return false;
}
/** {@collect.stats}
* Returns false to indicate that the height of the viewport does not
* determine the height of the table, unless the preferred height
* of the tree is smaller than the viewports height. In other words:
* ensure that the tree is never smaller than its viewport.
*
* @return false
* @see Scrollable#getScrollableTracksViewportHeight
*/
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
return false;
}
/** {@collect.stats}
* Sets the expanded state of this <code>JTree</code>.
* If <code>state</code> is
* true, all parents of <code>path</code> and path are marked as
* expanded. If <code>state</code> is false, all parents of
* <code>path</code> are marked EXPANDED, but <code>path</code> itself
* is marked collapsed.<p>
* This will fail if a <code>TreeWillExpandListener</code> vetos it.
*/
protected void setExpandedState(TreePath path, boolean state) {
if(path != null) {
// Make sure all parents of path are expanded.
Stack stack;
TreePath parentPath = path.getParentPath();
if (expandedStack.size() == 0) {
stack = new Stack();
}
else {
stack = (Stack)expandedStack.pop();
}
try {
while(parentPath != null) {
if(isExpanded(parentPath)) {
parentPath = null;
}
else {
stack.push(parentPath);
parentPath = parentPath.getParentPath();
}
}
for(int counter = stack.size() - 1; counter >= 0; counter--) {
parentPath = (TreePath)stack.pop();
if(!isExpanded(parentPath)) {
try {
fireTreeWillExpand(parentPath);
} catch (ExpandVetoException eve) {
// Expand vetoed!
return;
}
expandedState.put(parentPath, Boolean.TRUE);
fireTreeExpanded(parentPath);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
}
finally {
if (expandedStack.size() < TEMP_STACK_SIZE) {
stack.removeAllElements();
expandedStack.push(stack);
}
}
if(!state) {
// collapse last path.
Object cValue = expandedState.get(path);
if(cValue != null && ((Boolean)cValue).booleanValue()) {
try {
fireTreeWillCollapse(path);
}
catch (ExpandVetoException eve) {
return;
}
expandedState.put(path, Boolean.FALSE);
fireTreeCollapsed(path);
if (removeDescendantSelectedPaths(path, false) &&
!isPathSelected(path)) {
// A descendant was selected, select the parent.
addSelectionPath(path);
}
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
else {
// Expand last path.
Object cValue = expandedState.get(path);
if(cValue == null || !((Boolean)cValue).booleanValue()) {
try {
fireTreeWillExpand(path);
}
catch (ExpandVetoException eve) {
return;
}
expandedState.put(path, Boolean.TRUE);
fireTreeExpanded(path);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
}
}
/** {@collect.stats}
* Returns an <code>Enumeration</code> of <code>TreePaths</code>
* that have been expanded that
* are descendants of <code>parent</code>.
*/
protected Enumeration<TreePath>
getDescendantToggledPaths(TreePath parent)
{
if(parent == null)
return null;
Vector descendants = new Vector();
Enumeration nodes = expandedState.keys();
TreePath path;
while(nodes.hasMoreElements()) {
path = (TreePath)nodes.nextElement();
if(parent.isDescendant(path))
descendants.addElement(path);
}
return descendants.elements();
}
/** {@collect.stats}
* Removes any descendants of the <code>TreePaths</code> in
* <code>toRemove</code>
* that have been expanded.
*/
protected void
removeDescendantToggledPaths(Enumeration<TreePath> toRemove)
{
if(toRemove != null) {
while(toRemove.hasMoreElements()) {
Enumeration descendants = getDescendantToggledPaths
((TreePath)toRemove.nextElement());
if(descendants != null) {
while(descendants.hasMoreElements()) {
expandedState.remove(descendants.nextElement());
}
}
}
}
}
/** {@collect.stats}
* Clears the cache of toggled tree paths. This does NOT send out
* any <code>TreeExpansionListener</code> events.
*/
protected void clearToggledPaths() {
expandedState.clear();
}
/** {@collect.stats}
* Creates and returns an instance of <code>TreeModelHandler</code>.
* The returned
* object is responsible for updating the expanded state when the
* <code>TreeModel</code> changes.
* <p>
* For more information on what expanded state means, see the
* <a href=#jtree_description>JTree description</a> above.
*/
protected TreeModelListener createTreeModelListener() {
return new TreeModelHandler();
}
/** {@collect.stats}
* Removes any paths in the selection that are descendants of
* <code>path</code>. If <code>includePath</code> is true and
* <code>path</code> is selected, it will be removed from the selection.
*
* @return true if a descendant was selected
* @since 1.3
*/
protected boolean removeDescendantSelectedPaths(TreePath path,
boolean includePath) {
TreePath[] toRemove = getDescendantSelectedPaths(path, includePath);
if (toRemove != null) {
getSelectionModel().removeSelectionPaths(toRemove);
return true;
}
return false;
}
/** {@collect.stats}
* Returns an array of paths in the selection that are descendants of
* <code>path</code>. The returned array may contain <code>null</code>s.
*/
private TreePath[] getDescendantSelectedPaths(TreePath path,
boolean includePath) {
TreeSelectionModel sm = getSelectionModel();
TreePath[] selPaths = (sm != null) ? sm.getSelectionPaths() :
null;
if(selPaths != null) {
boolean shouldRemove = false;
for(int counter = selPaths.length - 1; counter >= 0; counter--) {
if(selPaths[counter] != null &&
path.isDescendant(selPaths[counter]) &&
(!path.equals(selPaths[counter]) || includePath))
shouldRemove = true;
else
selPaths[counter] = null;
}
if(!shouldRemove) {
selPaths = null;
}
return selPaths;
}
return null;
}
/** {@collect.stats}
* Removes any paths from the selection model that are descendants of
* the nodes identified by in <code>e</code>.
*/
void removeDescendantSelectedPaths(TreeModelEvent e) {
TreePath pPath = e.getTreePath();
Object[] oldChildren = e.getChildren();
TreeSelectionModel sm = getSelectionModel();
if (sm != null && pPath != null && oldChildren != null &&
oldChildren.length > 0) {
for (int counter = oldChildren.length - 1; counter >= 0;
counter--) {
// Might be better to call getDescendantSelectedPaths
// numerous times, then push to the model.
removeDescendantSelectedPaths(pPath.pathByAddingChild
(oldChildren[counter]), true);
}
}
}
/** {@collect.stats}
* Listens to the model and updates the <code>expandedState</code>
* accordingly when nodes are removed, or changed.
*/
protected class TreeModelHandler implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) { }
public void treeNodesInserted(TreeModelEvent e) { }
public void treeStructureChanged(TreeModelEvent e) {
if(e == null)
return;
// NOTE: If I change this to NOT remove the descendants
// and update BasicTreeUIs treeStructureChanged method
// to update descendants in response to a treeStructureChanged
// event, all the children of the event won't collapse!
TreePath parent = e.getTreePath();
if(parent == null)
return;
if (parent.getPathCount() == 1) {
// New root, remove everything!
clearToggledPaths();
if(treeModel.getRoot() != null &&
!treeModel.isLeaf(treeModel.getRoot())) {
// Mark the root as expanded, if it isn't a leaf.
expandedState.put(parent, Boolean.TRUE);
}
}
else if(expandedState.get(parent) != null) {
Vector<TreePath> toRemove = new Vector<TreePath>(1);
boolean isExpanded = isExpanded(parent);
toRemove.addElement(parent);
removeDescendantToggledPaths(toRemove.elements());
if(isExpanded) {
TreeModel model = getModel();
if(model == null || model.isLeaf
(parent.getLastPathComponent()))
collapsePath(parent);
else
expandedState.put(parent, Boolean.TRUE);
}
}
removeDescendantSelectedPaths(parent, false);
}
public void treeNodesRemoved(TreeModelEvent e) {
if(e == null)
return;
TreePath parent = e.getTreePath();
Object[] children = e.getChildren();
if(children == null)
return;
TreePath rPath;
Vector<TreePath> toRemove
= new Vector<TreePath>(Math.max(1, children.length));
for(int counter = children.length - 1; counter >= 0; counter--) {
rPath = parent.pathByAddingChild(children[counter]);
if(expandedState.get(rPath) != null)
toRemove.addElement(rPath);
}
if(toRemove.size() > 0)
removeDescendantToggledPaths(toRemove.elements());
TreeModel model = getModel();
if(model == null || model.isLeaf(parent.getLastPathComponent()))
expandedState.remove(parent);
removeDescendantSelectedPaths(e);
}
}
/** {@collect.stats}
* <code>DynamicUtilTreeNode</code> can wrap
* vectors/hashtables/arrays/strings and
* create the appropriate children tree nodes as necessary. It is
* dynamic in that it will only create the children as necessary.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
public static class DynamicUtilTreeNode extends DefaultMutableTreeNode {
/** {@collect.stats}
* Does the this <code>JTree</code> have children?
* This property is currently not implemented.
*/
protected boolean hasChildren;
/** {@collect.stats} Value to create children with. */
protected Object childValue;
/** {@collect.stats} Have the children been loaded yet? */
protected boolean loadedChildren;
/** {@collect.stats}
* Adds to parent all the children in <code>children</code>.
* If <code>children</code> is an array or vector all of its
* elements are added is children, otherwise if <code>children</code>
* is a hashtable all the key/value pairs are added in the order
* <code>Enumeration</code> returns them.
*/
public static void createChildren(DefaultMutableTreeNode parent,
Object children) {
if(children instanceof Vector) {
Vector childVector = (Vector)children;
for(int counter = 0, maxCounter = childVector.size();
counter < maxCounter; counter++)
parent.add(new DynamicUtilTreeNode
(childVector.elementAt(counter),
childVector.elementAt(counter)));
}
else if(children instanceof Hashtable) {
Hashtable childHT = (Hashtable)children;
Enumeration keys = childHT.keys();
Object aKey;
while(keys.hasMoreElements()) {
aKey = keys.nextElement();
parent.add(new DynamicUtilTreeNode(aKey,
childHT.get(aKey)));
}
}
else if(children instanceof Object[]) {
Object[] childArray = (Object[])children;
for(int counter = 0, maxCounter = childArray.length;
counter < maxCounter; counter++)
parent.add(new DynamicUtilTreeNode(childArray[counter],
childArray[counter]));
}
}
/** {@collect.stats}
* Creates a node with the specified object as its value and
* with the specified children. For the node to allow children,
* the children-object must be an array of objects, a
* <code>Vector</code>, or a <code>Hashtable</code> -- even
* if empty. Otherwise, the node is not
* allowed to have children.
*
* @param value the <code>Object</code> that is the value for the
* new node
* @param children an array of <code>Object</code>s, a
* <code>Vector</code>, or a <code>Hashtable</code>
* used to create the child nodes; if any other
* object is specified, or if the value is
* <code>null</code>,
* then the node is not allowed to have children
*/
public DynamicUtilTreeNode(Object value, Object children) {
super(value);
loadedChildren = false;
childValue = children;
if(children != null) {
if(children instanceof Vector)
setAllowsChildren(true);
else if(children instanceof Hashtable)
setAllowsChildren(true);
else if(children instanceof Object[])
setAllowsChildren(true);
else
setAllowsChildren(false);
}
else
setAllowsChildren(false);
}
/** {@collect.stats}
* Returns true if this node allows children. Whether the node
* allows children depends on how it was created.
*
* @return true if this node allows children, false otherwise
* @see #JTree.DynamicUtilTreeNode
*/
public boolean isLeaf() {
return !getAllowsChildren();
}
/** {@collect.stats}
* Returns the number of child nodes.
*
* @return the number of child nodes
*/
public int getChildCount() {
if(!loadedChildren)
loadChildren();
return super.getChildCount();
}
/** {@collect.stats}
* Loads the children based on <code>childValue</code>.
* If <code>childValue</code> is a <code>Vector</code>
* or array each element is added as a child,
* if <code>childValue</code> is a <code>Hashtable</code>
* each key/value pair is added in the order that
* <code>Enumeration</code> returns the keys.
*/
protected void loadChildren() {
loadedChildren = true;
createChildren(this, childValue);
}
/** {@collect.stats}
* Subclassed to load the children, if necessary.
*/
public TreeNode getChildAt(int index) {
if(!loadedChildren)
loadChildren();
return super.getChildAt(index);
}
/** {@collect.stats}
* Subclassed to load the children, if necessary.
*/
public Enumeration children() {
if(!loadedChildren)
loadChildren();
return super.children();
}
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "rowHeight") {
if (!rowHeightSet) {
setRowHeight(((Number)value).intValue());
rowHeightSet = false;
}
} else if (propertyName == "scrollsOnExpand") {
if (!scrollsOnExpandSet) {
setScrollsOnExpand(((Boolean)value).booleanValue());
scrollsOnExpandSet = false;
}
} else if (propertyName == "showsRootHandles") {
if (!showsRootHandlesSet) {
setShowsRootHandles(((Boolean)value).booleanValue());
showsRootHandlesSet = false;
}
} else {
super.setUIProperty(propertyName, value);
}
}
/** {@collect.stats}
* Returns a string representation of this <code>JTree</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JTree</code>.
*/
protected String paramString() {
String rootVisibleString = (rootVisible ?
"true" : "false");
String showsRootHandlesString = (showsRootHandles ?
"true" : "false");
String editableString = (editable ?
"true" : "false");
String largeModelString = (largeModel ?
"true" : "false");
String invokesStopCellEditingString = (invokesStopCellEditing ?
"true" : "false");
String scrollsOnExpandString = (scrollsOnExpand ?
"true" : "false");
return super.paramString() +
",editable=" + editableString +
",invokesStopCellEditing=" + invokesStopCellEditingString +
",largeModel=" + largeModelString +
",rootVisible=" + rootVisibleString +
",rowHeight=" + rowHeight +
",scrollsOnExpand=" + scrollsOnExpandString +
",showsRootHandles=" + showsRootHandlesString +
",toggleClickCount=" + toggleClickCount +
",visibleRowCount=" + visibleRowCount;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JTree.
* For JTrees, the AccessibleContext takes the form of an
* AccessibleJTree.
* A new AccessibleJTree instance is created if necessary.
*
* @return an AccessibleJTree that serves as the
* AccessibleContext of this JTree
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTree();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTree</code> class. It provides an implementation of the
* Java Accessibility API appropriate to tree user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJTree extends AccessibleJComponent
implements AccessibleSelection, TreeSelectionListener,
TreeModelListener, TreeExpansionListener {
TreePath leadSelectionPath;
Accessible leadSelectionAccessible;
public AccessibleJTree() {
// Add a tree model listener for JTree
TreeModel model = JTree.this.getModel();
if (model != null) {
model.addTreeModelListener(this);
}
JTree.this.addTreeExpansionListener(this);
JTree.this.addTreeSelectionListener(this);
leadSelectionPath = JTree.this.getLeadSelectionPath();
leadSelectionAccessible = (leadSelectionPath != null)
? new AccessibleJTreeNode(JTree.this,
leadSelectionPath,
JTree.this)
: null;
}
/** {@collect.stats}
* Tree Selection Listener value change method. Used to fire the
* property change
*
* @param e ListSelectionEvent
*
*/
public void valueChanged(TreeSelectionEvent e) {
// Fixes 4546503 - JTree is sending incorrect active
// descendant events
TreePath oldLeadSelectionPath = e.getOldLeadSelectionPath();
leadSelectionPath = e.getNewLeadSelectionPath();
if (oldLeadSelectionPath != leadSelectionPath) {
// Set parent to null so AccessibleJTreeNode computes
// its parent.
Accessible oldLSA = leadSelectionAccessible;
leadSelectionAccessible = (leadSelectionPath != null)
? new AccessibleJTreeNode(JTree.this,
leadSelectionPath,
null) // parent
: null;
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldLSA, leadSelectionAccessible);
}
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/** {@collect.stats}
* Fire a visible data property change notification.
* A 'visible' data property is one that represents
* something about the way the component appears on the
* display, where that appearance isn't bound to any other
* property. It notifies screen readers that the visual
* appearance of the component has changed, so they can
* notify the user.
*/
public void fireVisibleDataPropertyChange() {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
// Fire the visible data changes for the model changes.
/** {@collect.stats}
* Tree Model Node change notification.
*
* @param e a Tree Model event
*/
public void treeNodesChanged(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/** {@collect.stats}
* Tree Model Node change notification.
*
* @param e a Tree node insertion event
*/
public void treeNodesInserted(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/** {@collect.stats}
* Tree Model Node change notification.
*
* @param e a Tree node(s) removal event
*/
public void treeNodesRemoved(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/** {@collect.stats}
* Tree Model structure change change notification.
*
* @param e a Tree Model event
*/
public void treeStructureChanged(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/** {@collect.stats}
* Tree Collapsed notification.
*
* @param e a TreeExpansionEvent
*/
public void treeCollapsed(TreeExpansionEvent e) {
fireVisibleDataPropertyChange();
TreePath path = e.getPath();
if (path != null) {
// Set parent to null so AccessibleJTreeNode computes
// its parent.
AccessibleJTreeNode node = new AccessibleJTreeNode(JTree.this,
path,
null);
PropertyChangeEvent pce = new PropertyChangeEvent(node,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.EXPANDED,
AccessibleState.COLLAPSED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
}
/** {@collect.stats}
* Tree Model Expansion notification.
*
* @param e a Tree node insertion event
*/
public void treeExpanded(TreeExpansionEvent e) {
fireVisibleDataPropertyChange();
TreePath path = e.getPath();
if (path != null) {
// TIGER - 4839971
// Set parent to null so AccessibleJTreeNode computes
// its parent.
AccessibleJTreeNode node = new AccessibleJTreeNode(JTree.this,
path,
null);
PropertyChangeEvent pce = new PropertyChangeEvent(node,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.COLLAPSED,
AccessibleState.EXPANDED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getCurrentComponent();
if (c instanceof Accessible) {
return (((Accessible) c).getAccessibleContext());
} else {
return null;
}
}
private Component getCurrentComponent() {
// is the object visible?
// if so, get row, selected, focus & leaf state,
// and then get the renderer component and return it
TreeModel model = JTree.this.getModel();
if (model == null) {
return null;
}
TreePath path = new TreePath(model.getRoot());
if (JTree.this.isVisible(path)) {
TreeCellRenderer r = JTree.this.getCellRenderer();
TreeUI ui = JTree.this.getUI();
if (ui != null) {
int row = ui.getRowForPath(JTree.this, path);
int lsr = JTree.this.getLeadSelectionRow();
boolean hasFocus = JTree.this.isFocusOwner()
&& (lsr == row);
boolean selected = JTree.this.isPathSelected(path);
boolean expanded = JTree.this.isExpanded(path);
return r.getTreeCellRendererComponent(JTree.this,
model.getRoot(), selected, expanded,
model.isLeaf(model.getRoot()), row, hasFocus);
}
}
return null;
}
// Overridden methods from AccessibleJComponent
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TREE;
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child, if one exists,
* contained at the local coordinate <code>Point</code>.
* Otherwise returns <code>null</code>.
*
* @param p point in local coordinates of this <code>Accessible</code>
* @return the <code>Accessible</code>, if it exists,
* at the specified location; else <code>null</code>
*/
public Accessible getAccessibleAt(Point p) {
TreePath path = getClosestPathForLocation(p.x, p.y);
if (path != null) {
// JTree.this is NOT the parent; parent will get computed later
return new AccessibleJTreeNode(JTree.this, path, null);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the number of top-level children nodes of this
* JTree. Each of these nodes may in turn have children nodes.
*
* @return the number of accessible children nodes in the tree.
*/
public int getAccessibleChildrenCount() {
TreeModel model = JTree.this.getModel();
if (model == null) {
return 0;
}
if (isRootVisible()) {
return 1; // the root node
}
// return the root's first set of children count
return model.getChildCount(model.getRoot());
}
/** {@collect.stats}
* Return the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
TreeModel model = JTree.this.getModel();
if (model == null) {
return null;
}
if (isRootVisible()) {
if (i == 0) { // return the root node Accessible
Object[] objPath = { model.getRoot() };
TreePath path = new TreePath(objPath);
return new AccessibleJTreeNode(JTree.this, path, JTree.this);
} else {
return null;
}
}
// return Accessible for one of root's child nodes
int count = model.getChildCount(model.getRoot());
if (i < 0 || i >= count) {
return null;
}
Object obj = model.getChild(model.getRoot(), i);
Object[] objPath = { model.getRoot(), obj };
TreePath path = new TreePath(objPath);
return new AccessibleJTreeNode(JTree.this, path, JTree.this);
}
/** {@collect.stats}
* Get the index of this object in its accessible parent.
*
* @return the index of this object in its parent. Since a JTree
* top-level object does not have an accessible parent.
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
// didn't ever need to override this...
return super.getAccessibleIndexInParent();
}
// AccessibleSelection methods
/** {@collect.stats}
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/** {@collect.stats}
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
if (JTree.this.isPathSelected(childPath)) {
return 1;
} else {
return 0;
}
}
/** {@collect.stats}
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be null.
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
// The JTree can have only one accessible child, the root.
if (i == 0) {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
if (JTree.this.isPathSelected(childPath)) {
return new AccessibleJTreeNode(JTree.this, childPath, JTree.this);
}
}
return null;
}
/** {@collect.stats}
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
// The JTree can have only one accessible child, the root.
if (i == 0) {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
return JTree.this.isPathSelected(childPath);
} else {
return false;
}
}
/** {@collect.stats}
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i == 0) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.addSelectionPath(path);
}
}
}
/** {@collect.stats}
* Removes the specified selected item in the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i == 0) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.removeSelectionPath(path);
}
}
}
/** {@collect.stats}
* Clears the selection in the object, so that nothing in the
* object is selected.
*/
public void clearAccessibleSelection() {
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
removeAccessibleSelection(i);
}
}
/** {@collect.stats}
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
*/
public void selectAllAccessibleSelection() {
TreeModel model = JTree.this.getModel();
if (model != null) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.addSelectionPath(path);
}
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JTree</code> child. It provides an implementation of the
* Java Accessibility API appropriate to tree nodes.
*/
protected class AccessibleJTreeNode extends AccessibleContext
implements Accessible, AccessibleComponent, AccessibleSelection,
AccessibleAction {
private JTree tree = null;
private TreeModel treeModel = null;
private Object obj = null;
private TreePath path = null;
private Accessible accessibleParent = null;
private int index = 0;
private boolean isLeaf = false;
/** {@collect.stats}
* Constructs an AccessibleJTreeNode
* @since 1.4
*/
public AccessibleJTreeNode(JTree t, TreePath p, Accessible ap) {
tree = t;
path = p;
accessibleParent = ap;
treeModel = t.getModel();
obj = p.getLastPathComponent();
if (treeModel != null) {
isLeaf = treeModel.isLeaf(obj);
}
}
private TreePath getChildTreePath(int i) {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
Object childObj = treeModel.getChild(obj, i);
Object[] objPath = path.getPath();
Object[] objChildPath = new Object[objPath.length+1];
java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
objChildPath[objChildPath.length-1] = childObj;
return new TreePath(objChildPath);
}
}
/** {@collect.stats}
* Get the AccessibleContext associated with this tree node.
* In the implementation of the Java Accessibility API for
* this class, return this object, which is its own
* AccessibleContext.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getCurrentComponent();
if (c instanceof Accessible) {
return (((Accessible) c).getAccessibleContext());
} else {
return null;
}
}
private Component getCurrentComponent() {
// is the object visible?
// if so, get row, selected, focus & leaf state,
// and then get the renderer component and return it
if (tree.isVisible(path)) {
TreeCellRenderer r = tree.getCellRenderer();
if (r == null) {
return null;
}
TreeUI ui = tree.getUI();
if (ui != null) {
int row = ui.getRowForPath(JTree.this, path);
boolean selected = tree.isPathSelected(path);
boolean expanded = tree.isExpanded(path);
boolean hasFocus = false; // how to tell?? -PK
return r.getTreeCellRendererComponent(tree, obj,
selected, expanded, isLeaf, row, hasFocus);
}
}
return null;
}
// AccessibleContext methods
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object; null if this
* object does not have a name
*/
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
String name = ac.getAccessibleName();
if ((name != null) && (name != "")) {
return ac.getAccessibleName();
} else {
return null;
}
}
if ((accessibleName != null) && (accessibleName != "")) {
return accessibleName;
} else {
// fall back to the client property
return (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
}
/** {@collect.stats}
* Set the localized accessible name of this object.
*
* @param s the new localized name of the object.
*/
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
} else {
super.setAccessibleName(s);
}
}
//
// *** should check tooltip text for desc. (needs MouseEvent)
//
/** {@collect.stats}
* Get the accessible description of this object.
*
* @return the localized description of the object; null if
* this object does not have a description
*/
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return super.getAccessibleDescription();
}
}
/** {@collect.stats}
* Set the accessible description of this object.
*
* @param s the new localized description of the object
*/
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
} else {
super.setAccessibleDescription(s);
}
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return AccessibleRole.UNKNOWN;
}
}
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet states;
if (ac != null) {
states = ac.getAccessibleStateSet();
} else {
states = new AccessibleStateSet();
}
// need to test here, 'cause the underlying component
// is a cellRenderer, which is never showing...
if (isShowing()) {
states.add(AccessibleState.SHOWING);
} else if (states.contains(AccessibleState.SHOWING)) {
states.remove(AccessibleState.SHOWING);
}
if (isVisible()) {
states.add(AccessibleState.VISIBLE);
} else if (states.contains(AccessibleState.VISIBLE)) {
states.remove(AccessibleState.VISIBLE);
}
if (tree.isPathSelected(path)){
states.add(AccessibleState.SELECTED);
}
if (path == getLeadSelectionPath()) {
states.add(AccessibleState.ACTIVE);
}
if (!isLeaf) {
states.add(AccessibleState.EXPANDABLE);
}
if (tree.isExpanded(path)) {
states.add(AccessibleState.EXPANDED);
} else {
states.add(AccessibleState.COLLAPSED);
}
if (tree.isEditable()) {
states.add(AccessibleState.EDITABLE);
}
return states;
}
/** {@collect.stats}
* Get the Accessible parent of this object.
*
* @return the Accessible parent of this object; null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
// someone wants to know, so we need to create our parent
// if we don't have one (hey, we're a talented kid!)
if (accessibleParent == null) {
Object[] objPath = path.getPath();
if (objPath.length > 1) {
Object objParent = objPath[objPath.length-2];
if (treeModel != null) {
index = treeModel.getIndexOfChild(objParent, obj);
}
Object[] objParentPath = new Object[objPath.length-1];
java.lang.System.arraycopy(objPath, 0, objParentPath,
0, objPath.length-1);
TreePath parentPath = new TreePath(objParentPath);
accessibleParent = new AccessibleJTreeNode(tree,
parentPath,
null);
this.setAccessibleParent(accessibleParent);
} else if (treeModel != null) {
accessibleParent = tree; // we're the top!
index = 0; // we're an only child!
this.setAccessibleParent(accessibleParent);
}
}
return accessibleParent;
}
/** {@collect.stats}
* Get the index of this object in its accessible parent.
*
* @return the index of this object in its parent; -1 if this
* object does not have an accessible parent.
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
// index is invalid 'till we have an accessibleParent...
if (accessibleParent == null) {
getAccessibleParent();
}
Object[] objPath = path.getPath();
if (objPath.length > 1) {
Object objParent = objPath[objPath.length-2];
if (treeModel != null) {
index = treeModel.getIndexOfChild(objParent, obj);
}
}
return index;
}
/** {@collect.stats}
* Returns the number of accessible children in the object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
return treeModel.getChildCount(obj);
}
/** {@collect.stats}
* Return the specified Accessible child of the object.
*
* @param i zero-based index of child
* @return the Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
Object childObj = treeModel.getChild(obj, i);
Object[] objPath = path.getPath();
Object[] objChildPath = new Object[objPath.length+1];
java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
objChildPath[objChildPath.length-1] = childObj;
TreePath childPath = new TreePath(objChildPath);
return new AccessibleJTreeNode(JTree.this, childPath, this);
}
}
/** {@collect.stats}
* Gets the locale of the component. If the component does not have
* a locale, then the locale of its parent is returned.
*
* @return This component's locale. If this component does not have
* a locale, the locale of its parent is returned.
* @exception IllegalComponentStateException
* If the Component does not have its own locale and has not yet
* been added to a containment hierarchy such that the locale can be
* determined from the containing parent.
* @see #setLocale
*/
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return tree.getLocale();
}
}
/** {@collect.stats}
* Add a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
*
* @param l The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
} else {
super.addPropertyChangeListener(l);
}
}
/** {@collect.stats}
* Remove a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param l The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
} else {
super.removePropertyChangeListener(l);
}
}
/** {@collect.stats}
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Get the AccessibleComponent associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleComponent interface on behalf of itself.
*
* @return this object
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
/** {@collect.stats}
* Get the AccessibleSelection associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleSelection, or null
*/
public AccessibleSelection getAccessibleSelection() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null && isLeaf) {
return getCurrentAccessibleContext().getAccessibleSelection();
} else {
return this;
}
}
/** {@collect.stats}
* Get the AccessibleText associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleText, or null
*/
public AccessibleText getAccessibleText() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return getCurrentAccessibleContext().getAccessibleText();
} else {
return null;
}
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleValue, or null
*/
public AccessibleValue getAccessibleValue() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return getCurrentAccessibleContext().getAccessibleValue();
} else {
return null;
}
}
// AccessibleComponent methods
/** {@collect.stats}
* Get the background color of this object.
*
* @return the background color, if supported, of the object;
* otherwise, null
*/
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
/** {@collect.stats}
* Set the background color of this object.
*
* @param c the new Color for the background
*/
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
/** {@collect.stats}
* Get the foreground color of this object.
*
* @return the foreground color, if supported, of the object;
* otherwise, null
*/
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
public boolean isVisible() {
Rectangle pathBounds = tree.getPathBounds(path);
Rectangle parentBounds = tree.getVisibleRect();
if (pathBounds != null && parentBounds != null &&
parentBounds.intersects(pathBounds)) {
return true;
} else {
return false;
}
}
public void setVisible(boolean b) {
}
public boolean isShowing() {
return (tree.isShowing() && isVisible());
}
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
public Point getLocationOnScreen() {
if (tree != null) {
Point treeLocation = tree.getLocationOnScreen();
Rectangle pathBounds = tree.getPathBounds(path);
if (treeLocation != null && pathBounds != null) {
Point nodeLocation = new Point(pathBounds.x,
pathBounds.y);
nodeLocation.translate(treeLocation.x, treeLocation.y);
return nodeLocation;
} else {
return null;
}
} else {
return null;
}
}
protected Point getLocationInJTree() {
Rectangle r = tree.getPathBounds(path);
if (r != null) {
return r.getLocation();
} else {
return null;
}
}
public Point getLocation() {
Rectangle r = getBounds();
if (r != null) {
return r.getLocation();
} else {
return null;
}
}
public void setLocation(Point p) {
}
public Rectangle getBounds() {
Rectangle r = tree.getPathBounds(path);
Accessible parent = getAccessibleParent();
if (parent != null) {
if (parent instanceof AccessibleJTreeNode) {
Point parentLoc = ((AccessibleJTreeNode) parent).getLocationInJTree();
if (parentLoc != null && r != null) {
r.translate(-parentLoc.x, -parentLoc.y);
} else {
return null; // not visible!
}
}
}
return r;
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
public Dimension getSize() {
return getBounds().getSize();
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
/** {@collect.stats}
* Returns the <code>Accessible</code> child, if one exists,
* contained at the local coordinate <code>Point</code>.
* Otherwise returns <code>null</code>.
*
* @param p point in local coordinates of this
* <code>Accessible</code>
* @return the <code>Accessible</code>, if it exists,
* at the specified location; else <code>null</code>
*/
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
// AccessibleSelection methods
/** {@collect.stats}
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
int count = 0;
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
TreePath childPath = getChildTreePath(i);
if (tree.isPathSelected(childPath)) {
count++;
}
}
return count;
}
/** {@collect.stats}
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be null.
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
int childCount = getAccessibleChildrenCount();
if (i < 0 || i >= childCount) {
return null; // out of range
}
int count = 0;
for (int j = 0; j < childCount && i >= count; j++) {
TreePath childPath = getChildTreePath(j);
if (tree.isPathSelected(childPath)) {
if (count == i) {
return new AccessibleJTreeNode(tree, childPath, this);
} else {
count++;
}
}
}
return null;
}
/** {@collect.stats}
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
int childCount = getAccessibleChildrenCount();
if (i < 0 || i >= childCount) {
return false; // out of range
} else {
TreePath childPath = getChildTreePath(i);
return tree.isPathSelected(childPath);
}
}
/** {@collect.stats}
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i >= 0 && i < getAccessibleChildrenCount()) {
TreePath path = getChildTreePath(i);
JTree.this.addSelectionPath(path);
}
}
}
/** {@collect.stats}
* Removes the specified selected item in the object from the
* object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i >= 0 && i < getAccessibleChildrenCount()) {
TreePath path = getChildTreePath(i);
JTree.this.removeSelectionPath(path);
}
}
}
/** {@collect.stats}
* Clears the selection in the object, so that nothing in the
* object is selected.
*/
public void clearAccessibleSelection() {
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
removeAccessibleSelection(i);
}
}
/** {@collect.stats}
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
*/
public void selectAllAccessibleSelection() {
TreeModel model = JTree.this.getModel();
if (model != null) {
int childCount = getAccessibleChildrenCount();
TreePath path;
for (int i = 0; i < childCount; i++) {
path = getChildTreePath(i);
JTree.this.addSelectionPath(path);
}
}
}
// AccessibleAction methods
/** {@collect.stats}
* Returns the number of accessible actions available in this
* tree node. If this node is not a leaf, there is at least
* one action (toggle expand), in addition to any available
* on the object behind the TreeCellRenderer.
*
* @return the number of Actions in this object
*/
public int getAccessibleActionCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return (aa.getAccessibleActionCount() + (isLeaf ? 0 : 1));
}
}
return isLeaf ? 0 : 1;
}
/** {@collect.stats}
* Return a description of the specified action of the tree node.
* If this node is not a leaf, there is at least one action
* description (toggle expand), in addition to any available
* on the object behind the TreeCellRenderer.
*
* @param i zero-based index of the actions
* @return a description of the action
*/
public String getAccessibleActionDescription(int i) {
if (i < 0 || i >= getAccessibleActionCount()) {
return null;
}
AccessibleContext ac = getCurrentAccessibleContext();
if (i == 0) {
// TIGER - 4766636
return AccessibleAction.TOGGLE_EXPAND;
} else if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return aa.getAccessibleActionDescription(i - 1);
}
}
return null;
}
/** {@collect.stats}
* Perform the specified Action on the tree node. If this node
* is not a leaf, there is at least one action which can be
* done (toggle expand), in addition to any available on the
* object behind the TreeCellRenderer.
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
*/
public boolean doAccessibleAction(int i) {
if (i < 0 || i >= getAccessibleActionCount()) {
return false;
}
AccessibleContext ac = getCurrentAccessibleContext();
if (i == 0) {
if (JTree.this.isExpanded(path)) {
JTree.this.collapsePath(path);
} else {
JTree.this.expandPath(path);
}
return true;
} else if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return aa.doAccessibleAction(i - 1);
}
}
return false;
}
} // inner class AccessibleJTreeNode
} // inner class AccessibleJTree
} // End of class JTree
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.util.EventListener;
import java.util.BitSet;
import java.io.Serializable;
import javax.swing.event.*;
/** {@collect.stats}
* Default data model for list selections.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Philip Milne
* @author Hans Muller
* @see ListSelectionModel
*/
public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable
{
private static final int MIN = -1;
private static final int MAX = Integer.MAX_VALUE;
private int selectionMode = MULTIPLE_INTERVAL_SELECTION;
private int minIndex = MAX;
private int maxIndex = MIN;
private int anchorIndex = -1;
private int leadIndex = -1;
private int firstAdjustedIndex = MAX;
private int lastAdjustedIndex = MIN;
private boolean isAdjusting = false;
private int firstChangedIndex = MAX;
private int lastChangedIndex = MIN;
private BitSet value = new BitSet(32);
protected EventListenerList listenerList = new EventListenerList();
protected boolean leadAnchorNotificationEnabled = true;
/** {@collect.stats} {@inheritDoc} */
public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }
/** {@collect.stats} {@inheritDoc} */
public int getMaxSelectionIndex() { return maxIndex; }
/** {@collect.stats} {@inheritDoc} */
public boolean getValueIsAdjusting() { return isAdjusting; }
/** {@collect.stats} {@inheritDoc} */
public int getSelectionMode() { return selectionMode; }
/** {@collect.stats}
* {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public void setSelectionMode(int selectionMode) {
switch (selectionMode) {
case SINGLE_SELECTION:
case SINGLE_INTERVAL_SELECTION:
case MULTIPLE_INTERVAL_SELECTION:
this.selectionMode = selectionMode;
break;
default:
throw new IllegalArgumentException("invalid selectionMode");
}
}
/** {@collect.stats} {@inheritDoc} */
public boolean isSelectedIndex(int index) {
return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index);
}
/** {@collect.stats} {@inheritDoc} */
public boolean isSelectionEmpty() {
return (minIndex > maxIndex);
}
/** {@collect.stats} {@inheritDoc} */
public void addListSelectionListener(ListSelectionListener l) {
listenerList.add(ListSelectionListener.class, l);
}
/** {@collect.stats} {@inheritDoc} */
public void removeListSelectionListener(ListSelectionListener l) {
listenerList.remove(ListSelectionListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the list selection listeners
* registered on this <code>DefaultListSelectionModel</code>.
*
* @return all of this model's <code>ListSelectionListener</code>s
* or an empty
* array if no list selection listeners are currently registered
*
* @see #addListSelectionListener
* @see #removeListSelectionListener
*
* @since 1.4
*/
public ListSelectionListener[] getListSelectionListeners() {
return (ListSelectionListener[])listenerList.getListeners(
ListSelectionListener.class);
}
/** {@collect.stats}
* Notifies listeners that we have ended a series of adjustments.
*/
protected void fireValueChanged(boolean isAdjusting) {
if (lastChangedIndex == MIN) {
return;
}
/* Change the values before sending the event to the
* listeners in case the event causes a listener to make
* another change to the selection.
*/
int oldFirstChangedIndex = firstChangedIndex;
int oldLastChangedIndex = lastChangedIndex;
firstChangedIndex = MAX;
lastChangedIndex = MIN;
fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex, isAdjusting);
}
/** {@collect.stats}
* Notifies <code>ListSelectionListeners</code> that the value
* of the selection, in the closed interval <code>firstIndex</code>,
* <code>lastIndex</code>, has changed.
*/
protected void fireValueChanged(int firstIndex, int lastIndex) {
fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());
}
/** {@collect.stats}
* @param firstIndex the first index in the interval
* @param lastIndex the last index in the interval
* @param isAdjusting true if this is the final change in a series of
* adjustments
* @see EventListenerList
*/
protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
{
Object[] listeners = listenerList.getListenerList();
ListSelectionEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListSelectionListener.class) {
if (e == null) {
e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);
}
((ListSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
private void fireValueChanged() {
if (lastAdjustedIndex == MIN) {
return;
}
/* If getValueAdjusting() is true, (eg. during a drag opereration)
* record the bounds of the changes so that, when the drag finishes (and
* setValueAdjusting(false) is called) we can post a single event
* with bounds covering all of these individual adjustments.
*/
if (getValueIsAdjusting()) {
firstChangedIndex = Math.min(firstChangedIndex, firstAdjustedIndex);
lastChangedIndex = Math.max(lastChangedIndex, lastAdjustedIndex);
}
/* Change the values before sending the event to the
* listeners in case the event causes a listener to make
* another change to the selection.
*/
int oldFirstAdjustedIndex = firstAdjustedIndex;
int oldLastAdjustedIndex = lastAdjustedIndex;
firstAdjustedIndex = MAX;
lastAdjustedIndex = MIN;
fireValueChanged(oldFirstAdjustedIndex, oldLastAdjustedIndex);
}
/** {@collect.stats}
* Returns an array of all the objects currently registered as
* <code><em>Foo</em>Listener</code>s
* upon this model.
* <code><em>Foo</em>Listener</code>s
* are registered using the <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as <code><em>Foo</em>Listener.class</code>.
* For example, you can query a <code>DefaultListSelectionModel</code>
* instance <code>m</code>
* for its list selection listeners
* with the following code:
*
* <pre>ListSelectionListener[] lsls = (ListSelectionListener[])(m.getListeners(ListSelectionListener.class));</pre>
*
* If no such listeners exist,
* this method returns an empty array.
*
* @param listenerType the type of listeners requested;
* this parameter should specify an interface
* that descends from <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s
* on this model,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code> doesn't
* specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getListSelectionListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
// Updates first and last change indices
private void markAsDirty(int r) {
firstAdjustedIndex = Math.min(firstAdjustedIndex, r);
lastAdjustedIndex = Math.max(lastAdjustedIndex, r);
}
// Sets the state at this index and update all relevant state.
private void set(int r) {
if (value.get(r)) {
return;
}
value.set(r);
markAsDirty(r);
// Update minimum and maximum indices
minIndex = Math.min(minIndex, r);
maxIndex = Math.max(maxIndex, r);
}
// Clears the state at this index and update all relevant state.
private void clear(int r) {
if (!value.get(r)) {
return;
}
value.clear(r);
markAsDirty(r);
// Update minimum and maximum indices
/*
If (r > minIndex) the minimum has not changed.
The case (r < minIndex) is not possible because r'th value was set.
We only need to check for the case when lowest entry has been cleared,
and in this case we need to search for the first value set above it.
*/
if (r == minIndex) {
for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {
if (value.get(minIndex)) {
break;
}
}
}
/*
If (r < maxIndex) the maximum has not changed.
The case (r > maxIndex) is not possible because r'th value was set.
We only need to check for the case when highest entry has been cleared,
and in this case we need to search for the first value set below it.
*/
if (r == maxIndex) {
for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {
if (value.get(maxIndex)) {
break;
}
}
}
/* Performance note: This method is called from inside a loop in
changeSelection() but we will only iterate in the loops
above on the basis of one iteration per deselected cell - in total.
Ie. the next time this method is called the work of the previous
deselection will not be repeated.
We also don't need to worry about the case when the min and max
values are in their unassigned states. This cannot happen because
this method's initial check ensures that the selection was not empty
and therefore that the minIndex and maxIndex had 'real' values.
If we have cleared the whole selection, set the minIndex and maxIndex
to their cannonical values so that the next set command always works
just by using Math.min and Math.max.
*/
if (isSelectionEmpty()) {
minIndex = MAX;
maxIndex = MIN;
}
}
/** {@collect.stats}
* Sets the value of the leadAnchorNotificationEnabled flag.
* @see #isLeadAnchorNotificationEnabled()
*/
public void setLeadAnchorNotificationEnabled(boolean flag) {
leadAnchorNotificationEnabled = flag;
}
/** {@collect.stats}
* Returns the value of the <code>leadAnchorNotificationEnabled</code> flag.
* When <code>leadAnchorNotificationEnabled</code> is true the model
* generates notification events with bounds that cover all the changes to
* the selection plus the changes to the lead and anchor indices.
* Setting the flag to false causes a narrowing of the event's bounds to
* include only the elements that have been selected or deselected since
* the last change. Either way, the model continues to maintain the lead
* and anchor variables internally. The default is true.
* <p>
* Note: It is possible for the lead or anchor to be changed without a
* change to the selection. Notification of these changes is often
* important, such as when the new lead or anchor needs to be updated in
* the view. Therefore, caution is urged when changing the default value.
*
* @return the value of the <code>leadAnchorNotificationEnabled</code> flag
* @see #setLeadAnchorNotificationEnabled(boolean)
*/
public boolean isLeadAnchorNotificationEnabled() {
return leadAnchorNotificationEnabled;
}
private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) {
if (leadAnchorNotificationEnabled) {
if (this.anchorIndex != anchorIndex) {
if (this.anchorIndex != -1) { // The unassigned state.
markAsDirty(this.anchorIndex);
}
markAsDirty(anchorIndex);
}
if (this.leadIndex != leadIndex) {
if (this.leadIndex != -1) { // The unassigned state.
markAsDirty(this.leadIndex);
}
markAsDirty(leadIndex);
}
}
this.anchorIndex = anchorIndex;
this.leadIndex = leadIndex;
}
private boolean contains(int a, int b, int i) {
return (i >= a) && (i <= b);
}
private void changeSelection(int clearMin, int clearMax,
int setMin, int setMax, boolean clearFirst) {
for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) {
boolean shouldClear = contains(clearMin, clearMax, i);
boolean shouldSet = contains(setMin, setMax, i);
if (shouldSet && shouldClear) {
if (clearFirst) {
shouldClear = false;
}
else {
shouldSet = false;
}
}
if (shouldSet) {
set(i);
}
if (shouldClear) {
clear(i);
}
}
fireValueChanged();
}
/** {@collect.stats}
* Change the selection with the effect of first clearing the values
* in the inclusive range [clearMin, clearMax] then setting the values
* in the inclusive range [setMin, setMax]. Do this in one pass so
* that no values are cleared if they would later be set.
*/
private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) {
changeSelection(clearMin, clearMax, setMin, setMax, true);
}
/** {@collect.stats} {@inheritDoc} */
public void clearSelection() {
removeSelectionIntervalImpl(minIndex, maxIndex, false);
}
/** {@collect.stats}
* Changes the selection to be between {@code index0} and {@code index1}
* inclusive. {@code index0} doesn't have to be less than or equal to
* {@code index1}.
* <p>
* In {@code SINGLE_SELECTION} selection mode, only the second index
* is used.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
*/
public void setSelectionInterval(int index0, int index1) {
if (index0 == -1 || index1 == -1) {
return;
}
if (getSelectionMode() == SINGLE_SELECTION) {
index0 = index1;
}
updateLeadAnchorIndices(index0, index1);
int clearMin = minIndex;
int clearMax = maxIndex;
int setMin = Math.min(index0, index1);
int setMax = Math.max(index0, index1);
changeSelection(clearMin, clearMax, setMin, setMax);
}
/** {@collect.stats}
* Changes the selection to be the set union of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* <p>
* In {@code SINGLE_SELECTION} selection mode, this is equivalent
* to calling {@code setSelectionInterval}, and only the second index
* is used. In {@code SINGLE_INTERVAL_SELECTION} selection mode, this
* method behaves like {@code setSelectionInterval}, unless the given
* interval is immediately adjacent to or overlaps the existing selection,
* and can therefore be used to grow it.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change. Note that
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval.
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
* @see #setSelectionInterval
*/
public void addSelectionInterval(int index0, int index1)
{
if (index0 == -1 || index1 == -1) {
return;
}
// If we only allow a single selection, channel through
// setSelectionInterval() to enforce the rule.
if (getSelectionMode() == SINGLE_SELECTION) {
setSelectionInterval(index0, index1);
return;
}
updateLeadAnchorIndices(index0, index1);
int clearMin = MAX;
int clearMax = MIN;
int setMin = Math.min(index0, index1);
int setMax = Math.max(index0, index1);
// If we only allow a single interval and this would result
// in multiple intervals, then set the selection to be just
// the new range.
if (getSelectionMode() == SINGLE_INTERVAL_SELECTION &&
(setMax < minIndex - 1 || setMin > maxIndex + 1)) {
setSelectionInterval(index0, index1);
return;
}
changeSelection(clearMin, clearMax, setMin, setMax);
}
/** {@collect.stats}
* Changes the selection to be the set difference of the current selection
* and the indices between {@code index0} and {@code index1} inclusive.
* {@code index0} doesn't have to be less than or equal to {@code index1}.
* <p>
* In {@code SINGLE_INTERVAL_SELECTION} selection mode, if the removal
* would produce two disjoint selections, the removal is extended through
* the greater end of the selection. For example, if the selection is
* {@code 0-10} and you supply indices {@code 5,6} (in any order) the
* resulting selection is {@code 0-4}.
* <p>
* If this represents a change to the current selection, then each
* {@code ListSelectionListener} is notified of the change.
* <p>
* If either index is {@code -1}, this method does nothing and returns
* without exception. Otherwise, if either index is less than {@code -1},
* an {@code IndexOutOfBoundsException} is thrown.
*
* @param index0 one end of the interval
* @param index1 other end of the interval
* @throws IndexOutOfBoundsException if either index is less than {@code -1}
* (and neither index is {@code -1})
* @see #addListSelectionListener
*/
public void removeSelectionInterval(int index0, int index1)
{
removeSelectionIntervalImpl(index0, index1, true);
}
// private implementation allowing the selection interval
// to be removed without affecting the lead and anchor
private void removeSelectionIntervalImpl(int index0, int index1,
boolean changeLeadAnchor) {
if (index0 == -1 || index1 == -1) {
return;
}
if (changeLeadAnchor) {
updateLeadAnchorIndices(index0, index1);
}
int clearMin = Math.min(index0, index1);
int clearMax = Math.max(index0, index1);
int setMin = MAX;
int setMax = MIN;
// If the removal would produce to two disjoint selections in a mode
// that only allows one, extend the removal to the end of the selection.
if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION &&
clearMin > minIndex && clearMax < maxIndex) {
clearMax = maxIndex;
}
changeSelection(clearMin, clearMax, setMin, setMax);
}
private void setState(int index, boolean state) {
if (state) {
set(index);
}
else {
clear(index);
}
}
/** {@collect.stats}
* Insert length indices beginning before/after index. If the value
* at index is itself selected and the selection mode is not
* SINGLE_SELECTION, set all of the newly inserted items as selected.
* Otherwise leave them unselected. This method is typically
* called to sync the selection model with a corresponding change
* in the data model.
*/
public void insertIndexInterval(int index, int length, boolean before)
{
/* The first new index will appear at insMinIndex and the last
* one will appear at insMaxIndex
*/
int insMinIndex = (before) ? index : index + 1;
int insMaxIndex = (insMinIndex + length) - 1;
/* Right shift the entire bitset by length, beginning with
* index-1 if before is true, index+1 if it's false (i.e. with
* insMinIndex).
*/
for(int i = maxIndex; i >= insMinIndex; i--) {
setState(i + length, value.get(i));
}
/* Initialize the newly inserted indices.
*/
boolean setInsertedValues = ((getSelectionMode() == SINGLE_SELECTION) ?
false : value.get(index));
for(int i = insMinIndex; i <= insMaxIndex; i++) {
setState(i, setInsertedValues);
}
int leadIndex = this.leadIndex;
if (leadIndex > index || (before && leadIndex == index)) {
leadIndex = this.leadIndex + length;
}
int anchorIndex = this.anchorIndex;
if (anchorIndex > index || (before && anchorIndex == index)) {
anchorIndex = this.anchorIndex + length;
}
if (leadIndex != this.leadIndex || anchorIndex != this.anchorIndex) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
}
fireValueChanged();
}
/** {@collect.stats}
* Remove the indices in the interval index0,index1 (inclusive) from
* the selection model. This is typically called to sync the selection
* model width a corresponding change in the data model. Note
* that (as always) index0 need not be <= index1.
*/
public void removeIndexInterval(int index0, int index1)
{
int rmMinIndex = Math.min(index0, index1);
int rmMaxIndex = Math.max(index0, index1);
int gapLength = (rmMaxIndex - rmMinIndex) + 1;
/* Shift the entire bitset to the left to close the index0, index1
* gap.
*/
for(int i = rmMinIndex; i <= maxIndex; i++) {
setState(i, value.get(i + gapLength));
}
int leadIndex = this.leadIndex;
if (leadIndex == 0 && rmMinIndex == 0) {
// do nothing
} else if (leadIndex > rmMaxIndex) {
leadIndex = this.leadIndex - gapLength;
} else if (leadIndex >= rmMinIndex) {
leadIndex = rmMinIndex - 1;
}
int anchorIndex = this.anchorIndex;
if (anchorIndex == 0 && rmMinIndex == 0) {
// do nothing
} else if (anchorIndex > rmMaxIndex) {
anchorIndex = this.anchorIndex - gapLength;
} else if (anchorIndex >= rmMinIndex) {
anchorIndex = rmMinIndex - 1;
}
if (leadIndex != this.leadIndex || anchorIndex != this.anchorIndex) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
}
fireValueChanged();
}
/** {@collect.stats} {@inheritDoc} */
public void setValueIsAdjusting(boolean isAdjusting) {
if (isAdjusting != this.isAdjusting) {
this.isAdjusting = isAdjusting;
this.fireValueChanged(isAdjusting);
}
}
/** {@collect.stats}
* Returns a string that displays and identifies this
* object's properties.
*
* @return a <code>String</code> representation of this object
*/
public String toString() {
String s = ((getValueIsAdjusting()) ? "~" : "=") + value.toString();
return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s;
}
/** {@collect.stats}
* Returns a clone of this selection model with the same selection.
* <code>listenerLists</code> are not duplicated.
*
* @exception CloneNotSupportedException if the selection model does not
* both (a) implement the Cloneable interface and (b) define a
* <code>clone</code> method.
*/
public Object clone() throws CloneNotSupportedException {
DefaultListSelectionModel clone = (DefaultListSelectionModel)super.clone();
clone.value = (BitSet)value.clone();
clone.listenerList = new EventListenerList();
return clone;
}
/** {@collect.stats} {@inheritDoc} */
public int getAnchorSelectionIndex() {
return anchorIndex;
}
/** {@collect.stats} {@inheritDoc} */
public int getLeadSelectionIndex() {
return leadIndex;
}
/** {@collect.stats}
* Set the anchor selection index, leaving all selection values unchanged.
* If leadAnchorNotificationEnabled is true, send a notification covering
* the old and new anchor cells.
*
* @see #getAnchorSelectionIndex
* @see #setLeadSelectionIndex
*/
public void setAnchorSelectionIndex(int anchorIndex) {
updateLeadAnchorIndices(anchorIndex, this.leadIndex);
fireValueChanged();
}
/** {@collect.stats}
* Set the lead selection index, leaving all selection values unchanged.
* If leadAnchorNotificationEnabled is true, send a notification covering
* the old and new lead cells.
*
* @param leadIndex the new lead selection index
*
* @see #setAnchorSelectionIndex
* @see #setLeadSelectionIndex
* @see #getLeadSelectionIndex
*
* @since 1.5
*/
public void moveLeadSelectionIndex(int leadIndex) {
// disallow a -1 lead unless the anchor is already -1
if (leadIndex == -1) {
if (this.anchorIndex != -1) {
return;
}
/* PENDING(shannonh) - The following check is nice, to be consistent with
setLeadSelectionIndex. However, it is not absolutely
necessary: One could work around it by setting the anchor
to something valid, modifying the lead, and then moving
the anchor back to -1. For this reason, there's no sense
in adding it at this time, as that would require
updating the spec and officially committing to it.
// otherwise, don't do anything if the anchor is -1
} else if (this.anchorIndex == -1) {
return;
*/
}
updateLeadAnchorIndices(this.anchorIndex, leadIndex);
fireValueChanged();
}
/** {@collect.stats}
* Sets the lead selection index, ensuring that values between the
* anchor and the new lead are either all selected or all deselected.
* If the value at the anchor index is selected, first clear all the
* values in the range [anchor, oldLeadIndex], then select all the values
* values in the range [anchor, newLeadIndex], where oldLeadIndex is the old
* leadIndex and newLeadIndex is the new one.
* <p>
* If the value at the anchor index is not selected, do the same thing in
* reverse selecting values in the old range and deslecting values in the
* new one.
* <p>
* Generate a single event for this change and notify all listeners.
* For the purposes of generating minimal bounds in this event, do the
* operation in a single pass; that way the first and last index inside the
* ListSelectionEvent that is broadcast will refer to cells that actually
* changed value because of this method. If, instead, this operation were
* done in two steps the effect on the selection state would be the same
* but two events would be generated and the bounds around the changed
* values would be wider, including cells that had been first cleared only
* to later be set.
* <p>
* This method can be used in the <code>mouseDragged</code> method
* of a UI class to extend a selection.
*
* @see #getLeadSelectionIndex
* @see #setAnchorSelectionIndex
*/
public void setLeadSelectionIndex(int leadIndex) {
int anchorIndex = this.anchorIndex;
// only allow a -1 lead if the anchor is already -1
if (leadIndex == -1) {
if (anchorIndex == -1) {
updateLeadAnchorIndices(anchorIndex, leadIndex);
fireValueChanged();
}
return;
// otherwise, don't do anything if the anchor is -1
} else if (anchorIndex == -1) {
return;
}
if (this.leadIndex == -1) {
this.leadIndex = leadIndex;
}
boolean shouldSelect = value.get(this.anchorIndex);
if (getSelectionMode() == SINGLE_SELECTION) {
anchorIndex = leadIndex;
shouldSelect = true;
}
int oldMin = Math.min(this.anchorIndex, this.leadIndex);
int oldMax = Math.max(this.anchorIndex, this.leadIndex);
int newMin = Math.min(anchorIndex, leadIndex);
int newMax = Math.max(anchorIndex, leadIndex);
updateLeadAnchorIndices(anchorIndex, leadIndex);
if (shouldSelect) {
changeSelection(oldMin, oldMax, newMin, newMax);
}
else {
changeSelection(newMin, newMax, oldMin, oldMax, false);
}
}
}
|
Java
|
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.util.*;
import static java.awt.Component.BaselineResizeBehavior;
import static javax.swing.LayoutStyle.ComponentPlacement;
import static javax.swing.SwingConstants.HORIZONTAL;
import static javax.swing.SwingConstants.VERTICAL;
/** {@collect.stats}
* {@code GroupLayout} is a {@code LayoutManager} that hierarchically
* groups components in order to position them in a {@code Container}.
* {@code GroupLayout} is intended for use by builders, but may be
* hand-coded as well.
* Grouping is done by instances of the {@link Group Group} class. {@code
* GroupLayout} supports two types of groups. A sequential group
* positions its child elements sequentially, one after another. A
* parallel group aligns its child elements in one of four ways.
* <p>
* Each group may contain any number of elements, where an element is
* a {@code Group}, {@code Component}, or gap. A gap can be thought
* of as an invisible component with a minimum, preferred and maximum
* size. In addition {@code GroupLayout} supports a preferred gap,
* whose value comes from {@code LayoutStyle}.
* <p>
* Elements are similar to a spring. Each element has a range as
* specified by a minimum, preferred and maximum. Gaps have either a
* developer-specified range, or a range determined by {@code
* LayoutStyle}. The range for {@code Component}s is determined from
* the {@code Component}'s {@code getMinimumSize}, {@code
* getPreferredSize} and {@code getMaximumSize} methods. In addition,
* when adding {@code Component}s you may specify a particular range
* to use instead of that from the component. The range for a {@code
* Group} is determined by the type of group. A {@code ParallelGroup}'s
* range is the maximum of the ranges of its elements. A {@code
* SequentialGroup}'s range is the sum of the ranges of its elements.
* <p>
* {@code GroupLayout} treats each axis independently. That is, there
* is a group representing the horizontal axis, and a group
* representing the vertical axis. The horizontal group is
* responsible for determining the minimum, preferred and maximum size
* along the horizontal axis as well as setting the x and width of the
* components contained in it. The vertical group is responsible for
* determining the minimum, preferred and maximum size along the
* vertical axis as well as setting the y and height of the
* components contained in it. Each {@code Component} must exist in both
* a horizontal and vertical group, otherwise an {@code IllegalStateException}
* is thrown during layout, or when the minimum, preferred or
* maximum size is requested.
* <p>
* The following diagram shows a sequential group along the horizontal
* axis. The sequential group contains three components. A parallel group
* was used along the vertical axis.
* <p align="center">
* <img src="doc-files/groupLayout.1.gif">
* <p>
* To reinforce that each axis is treated independently the diagram shows
* the range of each group and element along each axis. The
* range of each component has been projected onto the axes,
* and the groups are rendered in blue (horizontal) and red (vertical).
* For readability there is a gap between each of the elements in the
* sequential group.
* <p>
* The sequential group along the horizontal axis is rendered as a solid
* blue line. Notice the sequential group is the sum of the children elements
* it contains.
* <p>
* Along the vertical axis the parallel group is the maximum of the height
* of each of the components. As all three components have the same height,
* the parallel group has the same height.
* <p>
* The following diagram shows the same three components, but with the
* parallel group along the horizontal axis and the sequential group along
* the vertical axis.
* <p>
* <p align="center">
* <img src="doc-files/groupLayout.2.gif">
* <p>
* As {@code c1} is the largest of the three components, the parallel
* group is sized to {@code c1}. As {@code c2} and {@code c3} are smaller
* than {@code c1} they are aligned based on the alignment specified
* for the component (if specified) or the default alignment of the
* parallel group. In the diagram {@code c2} and {@code c3} were created
* with an alignment of {@code LEADING}. If the component orientation were
* right-to-left then {@code c2} and {@code c3} would be positioned on
* the opposite side.
* <p>
* The following diagram shows a sequential group along both the horizontal
* and vertical axis.
* <p align="center">
* <img src="doc-files/groupLayout.3.gif">
* <p>
* {@code GroupLayout} provides the ability to insert gaps between
* {@code Component}s. The size of the gap is determined by an
* instance of {@code LayoutStyle}. This may be turned on using the
* {@code setAutoCreateGaps} method. Similarly, you may use
* the {@code setAutoCreateContainerGaps} method to insert gaps
* between components that touch the edge of the parent container and the
* container.
* <p>
* The following builds a panel consisting of two labels in
* one column, followed by two textfields in the next column:
* <pre>
* JComponent panel = ...;
* GroupLayout layout = new GroupLayout(panel);
* panel.setLayout(layout);
*
* // Turn on automatically adding gaps between components
* layout.setAutoCreateGaps(true);
*
* // Turn on automatically creating gaps between components that touch
* // the edge of the container and the container.
* layout.setAutoCreateContainerGaps(true);
*
* // Create a sequential group for the horizontal axis.
*
* GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
*
* // The sequential group in turn contains two parallel groups.
* // One parallel group contains the labels, the other the text fields.
* // Putting the labels in a parallel group along the horizontal axis
* // positions them at the same x location.
* //
* // Variable indentation is used to reinforce the level of grouping.
* hGroup.addGroup(layout.createParallelGroup().
* addComponent(label1).addComponent(label2));
* hGroup.addGroup(layout.createParallelGroup().
* addComponent(tf1).addComponent(tf2));
* layout.setHorizontalGroup(hGroup);
*
* // Create a sequential group for the vertical axis.
* GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
*
* // The sequential group contains two parallel groups that align
* // the contents along the baseline. The first parallel group contains
* // the first label and text field, and the second parallel group contains
* // the second label and text field. By using a sequential group
* // the labels and text fields are positioned vertically after one another.
* vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
* addComponent(label1).addComponent(tf1));
* vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
* addComponent(label2).addComponent(tf2));
* layout.setVerticalGroup(vGroup);
* </pre>
* <p>
* When run the following is produced.
* <p align="center">
* <img src="doc-files/groupLayout.example.png">
* <p>
* This layout consists of the following.
* <ul><li>The horizontal axis consists of a sequential group containing two
* parallel groups. The first parallel group contains the labels,
* and the second parallel group contains the text fields.
* <li>The vertical axis consists of a sequential group
* containing two parallel groups. The parallel groups are configured
* to align their components along the baseline. The first parallel
* group contains the first label and first text field, and
* the second group consists of the second label and second
* text field.
* </ul>
* There are a couple of things to notice in this code:
* <ul>
* <li>You need not explicitly add the components to the container; this
* is indirectly done by using one of the {@code add} methods of
* {@code Group}.
* <li>The various {@code add} methods return
* the caller. This allows for easy chaining of invocations. For
* example, {@code group.addComponent(label1).addComponent(label2);} is
* equivalent to
* {@code group.addComponent(label1); group.addComponent(label2);}.
* <li>There are no public constructors for {@code Group}s; instead
* use the create methods of {@code GroupLayout}.
* </ul>
*
* @author Tomas Pavek
* @author Jan Stola
* @author Scott Violet
* @since 1.6
*/
public class GroupLayout implements LayoutManager2 {
// Used in size calculations
private static final int MIN_SIZE = 0;
private static final int PREF_SIZE = 1;
private static final int MAX_SIZE = 2;
// Used by prepare, indicates min, pref or max isn't going to be used.
private static final int SPECIFIC_SIZE = 3;
private static final int UNSET = Integer.MIN_VALUE;
/** {@collect.stats}
* Indicates the size from the component or gap should be used for a
* particular range value.
*
* @see Group
*/
public static final int DEFAULT_SIZE = -1;
/** {@collect.stats}
* Indicates the preferred size from the component or gap should
* be used for a particular range value.
*
* @see Group
*/
public static final int PREFERRED_SIZE = -2;
// Whether or not we automatically try and create the preferred
// padding between components.
private boolean autocreatePadding;
// Whether or not we automatically try and create the preferred
// padding between components the touch the edge of the container and
// the container.
private boolean autocreateContainerPadding;
/** {@collect.stats}
* Group responsible for layout along the horizontal axis. This is NOT
* the user specified group, use getHorizontalGroup to dig that out.
*/
private Group horizontalGroup;
/** {@collect.stats}
* Group responsible for layout along the vertical axis. This is NOT
* the user specified group, use getVerticalGroup to dig that out.
*/
private Group verticalGroup;
// Maps from Component to ComponentInfo. This is used for tracking
// information specific to a Component.
private Map<Component,ComponentInfo> componentInfos;
// Container we're doing layout for.
private Container host;
// Used by areParallelSiblings, cached to avoid excessive garbage.
private Set<Spring> tmpParallelSet;
// Indicates Springs have changed in some way since last change.
private boolean springsChanged;
// Indicates invalidateLayout has been invoked.
private boolean isValid;
// Whether or not any preferred padding (or container padding) springs
// exist
private boolean hasPreferredPaddingSprings;
/** {@collect.stats}
* The LayoutStyle instance to use, if null the sharedInstance is used.
*/
private LayoutStyle layoutStyle;
/** {@collect.stats}
* If true, components that are not visible are treated as though they
* aren't there.
*/
private boolean honorsVisibility;
/** {@collect.stats}
* Enumeration of the possible ways {@code ParallelGroup} can align
* its children.
*
* @see #createParallelGroup(Alignment)
* @since 1.6
*/
public enum Alignment {
/** {@collect.stats}
* Indicates the elements should be
* aligned to the origin. For the horizontal axis with a left to
* right orientation this means aligned to the left edge. For the
* vertical axis leading means aligned to the top edge.
*
* @see #createParallelGroup(Alignment)
*/
LEADING,
/** {@collect.stats}
* Indicates the elements should be aligned to the end of the
* region. For the horizontal axis with a left to right
* orientation this means aligned to the right edge. For the
* vertical axis trailing means aligned to the bottom edge.
*
* @see #createParallelGroup(Alignment)
*/
TRAILING,
/** {@collect.stats}
* Indicates the elements should be centered in
* the region.
*
* @see #createParallelGroup(Alignment)
*/
CENTER,
/** {@collect.stats}
* Indicates the elements should be aligned along
* their baseline.
*
* @see #createParallelGroup(Alignment)
* @see #createBaselineGroup(boolean,boolean)
*/
BASELINE
}
private static void checkSize(int min, int pref, int max,
boolean isComponentSpring) {
checkResizeType(min, isComponentSpring);
if (!isComponentSpring && pref < 0) {
throw new IllegalArgumentException("Pref must be >= 0");
} else if (isComponentSpring) {
checkResizeType(pref, true);
}
checkResizeType(max, isComponentSpring);
checkLessThan(min, pref);
checkLessThan(pref, max);
}
private static void checkResizeType(int type, boolean isComponentSpring) {
if (type < 0 && ((isComponentSpring && type != DEFAULT_SIZE &&
type != PREFERRED_SIZE) ||
(!isComponentSpring && type != PREFERRED_SIZE))) {
throw new IllegalArgumentException("Invalid size");
}
}
private static void checkLessThan(int min, int max) {
if (min >= 0 && max >= 0 && min > max) {
throw new IllegalArgumentException(
"Following is not met: min<=pref<=max");
}
}
/** {@collect.stats}
* Creates a {@code GroupLayout} for the specified {@code Container}.
*
* @param host the {@code Container} the {@code GroupLayout} is
* the {@code LayoutManager} for
* @throws IllegalArgumentException if host is {@code null}
*/
public GroupLayout(Container host) {
if (host == null) {
throw new IllegalArgumentException("Container must be non-null");
}
honorsVisibility = true;
this.host = host;
setHorizontalGroup(createParallelGroup(Alignment.LEADING, true));
setVerticalGroup(createParallelGroup(Alignment.LEADING, true));
componentInfos = new HashMap<Component,ComponentInfo>();
tmpParallelSet = new HashSet<Spring>();
}
/** {@collect.stats}
* Sets whether component visiblity is considered when sizing and
* positioning components. A value of {@code true} indicates that
* non-visible components should not be treated as part of the
* layout. A value of {@code false} indicates that components should be
* positioned and sized regardless of visibility.
* <p>
* A value of {@code false} is useful when the visibility of components
* is dynamically adjusted and you don't want surrounding components and
* the sizing to change.
* <p>
* The specified value is used for components that do not have an
* explicit visibility specified.
* <p>
* The default is {@code true}.
*
* @param honorsVisibility whether component visiblity is considered when
* sizing and positioning components
* @see #setHonorsVisibility(Component,Boolean)
*/
public void setHonorsVisibility(boolean honorsVisibility) {
if (this.honorsVisibility != honorsVisibility) {
this.honorsVisibility = honorsVisibility;
springsChanged = true;
isValid = false;
invalidateHost();
}
}
/** {@collect.stats}
* Returns whether component visiblity is considered when sizing and
* positioning components.
*
* @return whether component visiblity is considered when sizing and
* positioning components
*/
public boolean getHonorsVisibility() {
return honorsVisibility;
}
/** {@collect.stats}
* Sets whether the component's visiblity is considered for
* sizing and positioning. A value of {@code Boolean.TRUE}
* indicates that if {@code component} is not visible it should
* not be treated as part of the layout. A value of {@code false}
* indicates that {@code component} is positioned and sized
* regardless of it's visibility. A value of {@code null}
* indicates the value specified by the single argument method {@code
* setHonorsVisibility} should be used.
* <p>
* If {@code component} is not a child of the {@code Container} this
* {@code GroupLayout} is managine, it will be added to the
* {@code Container}.
*
* @param component the component
* @param honorsVisibility whether {@code component}'s visiblity should be
* considered for sizing and positioning
* @throws IllegalArgumentException if {@code component} is {@code null}
* @see #setHonorsVisibility(Component,Boolean)
*/
public void setHonorsVisibility(Component component,
Boolean honorsVisibility) {
if (component == null) {
throw new IllegalArgumentException("Component must be non-null");
}
getComponentInfo(component).setHonorsVisibility(honorsVisibility);
springsChanged = true;
isValid = false;
invalidateHost();
}
/** {@collect.stats}
* Sets whether a gap between components should automatically be
* created. For example, if this is {@code true} and you add two
* components to a {@code SequentialGroup} a gap between the
* two components is automatically be created. The default is
* {@code false}.
*
* @param autoCreatePadding whether a gap between components is
* automatically created
*/
public void setAutoCreateGaps(boolean autoCreatePadding) {
if (this.autocreatePadding != autoCreatePadding) {
this.autocreatePadding = autoCreatePadding;
invalidateHost();
}
}
/** {@collect.stats}
* Returns {@code true} if gaps between components are automatically
* created.
*
* @return {@code true} if gaps between components are automatically
* created
*/
public boolean getAutoCreateGaps() {
return autocreatePadding;
}
/** {@collect.stats}
* Sets whether a gap between the container and components that
* touch the border of the container should automatically be
* created. The default is {@code false}.
*
* @param autoCreateContainerPadding whether a gap between the container and
* components that touch the border of the container should
* automatically be created
*/
public void setAutoCreateContainerGaps(boolean autoCreateContainerPadding){
if (this.autocreateContainerPadding != autoCreateContainerPadding) {
this.autocreateContainerPadding = autoCreateContainerPadding;
horizontalGroup = createTopLevelGroup(getHorizontalGroup());
verticalGroup = createTopLevelGroup(getVerticalGroup());
invalidateHost();
}
}
/** {@collect.stats}
* Returns {@code true} if gaps between the container and components that
* border the container are automatically created.
*
* @return {@code true} if gaps between the container and components that
* border the container are automatically created
*/
public boolean getAutoCreateContainerGaps() {
return autocreateContainerPadding;
}
/** {@collect.stats}
* Sets the {@code Group} that positions and sizes
* components along the horizontal axis.
*
* @param group the {@code Group} that positions and sizes
* components along the horizontal axis
* @throws IllegalArgumentException if group is {@code null}
*/
public void setHorizontalGroup(Group group) {
if (group == null) {
throw new IllegalArgumentException("Group must be non-null");
}
horizontalGroup = createTopLevelGroup(group);
invalidateHost();
}
/** {@collect.stats}
* Returns the {@code Group} that positions and sizes components
* along the horizontal axis.
*
* @return the {@code Group} responsible for positioning and
* sizing component along the horizontal axis
*/
private Group getHorizontalGroup() {
int index = 0;
if (horizontalGroup.springs.size() > 1) {
index = 1;
}
return (Group)horizontalGroup.springs.get(index);
}
/** {@collect.stats}
* Sets the {@code Group} that positions and sizes
* components along the vertical axis.
*
* @param group the {@code Group} that positions and sizes
* components along the vertical axis
* @throws IllegalArgumentException if group is {@code null}
*/
public void setVerticalGroup(Group group) {
if (group == null) {
throw new IllegalArgumentException("Group must be non-null");
}
verticalGroup = createTopLevelGroup(group);
invalidateHost();
}
/** {@collect.stats}
* Returns the {@code Group} that positions and sizes components
* along the vertical axis.
*
* @return the {@code Group} responsible for positioning and
* sizing component along the vertical axis
*/
private Group getVerticalGroup() {
int index = 0;
if (verticalGroup.springs.size() > 1) {
index = 1;
}
return (Group)verticalGroup.springs.get(index);
}
/** {@collect.stats}
* Wraps the user specified group in a sequential group. If
* container gaps should be generated the necessary springs are
* added.
*/
private Group createTopLevelGroup(Group specifiedGroup) {
SequentialGroup group = createSequentialGroup();
if (getAutoCreateContainerGaps()) {
group.addSpring(new ContainerAutoPreferredGapSpring());
group.addGroup(specifiedGroup);
group.addSpring(new ContainerAutoPreferredGapSpring());
} else {
group.addGroup(specifiedGroup);
}
return group;
}
/** {@collect.stats}
* Creates and returns a {@code SequentialGroup}.
*
* @return a new {@code SequentialGroup}
*/
public SequentialGroup createSequentialGroup() {
return new SequentialGroup();
}
/** {@collect.stats}
* Creates and returns a {@code ParallelGroup} with an alignment of
* {@code Alignment.LEADING}. This is a cover method for the more
* general {@code createParallelGroup(Alignment)} method.
*
* @return a new {@code ParallelGroup}
* @see #createParallelGroup(Alignment)
*/
public ParallelGroup createParallelGroup() {
return createParallelGroup(Alignment.LEADING);
}
/** {@collect.stats}
* Creates and returns a {@code ParallelGroup} with the specified
* alignment. This is a cover method for the more general {@code
* createParallelGroup(Alignment,boolean)} method with {@code true}
* supplied for the second argument.
*
* @param alignment the alignment for the elements of the group
* @throws IllegalArgumentException if {@code alignment} is {@code null}
* @return a new {@code ParallelGroup}
* @see #createBaselineGroup
* @see ParallelGroup
*/
public ParallelGroup createParallelGroup(Alignment alignment) {
return createParallelGroup(alignment, true);
}
/** {@collect.stats}
* Creates and returns a {@code ParallelGroup} with the specified
* alignment and resize behavior. The {@code
* alignment} argument specifies how children elements are
* positioned that do not fill the group. For example, if a {@code
* ParallelGroup} with an alignment of {@code TRAILING} is given
* 100 and a child only needs 50, the child is
* positioned at the position 50 (with a component orientation of
* left-to-right).
* <p>
* Baseline alignment is only useful when used along the vertical
* axis. A {@code ParallelGroup} created with a baseline alignment
* along the horizontal axis is treated as {@code LEADING}.
* <p>
* Refer to {@link GroupLayout.ParallelGroup ParallelGroup} for details on
* the behavior of baseline groups.
*
* @param alignment the alignment for the elements of the group
* @param resizable {@code true} if the group is resizable; if the group
* is not resizable the preferred size is used for the
* minimum and maximum size of the group
* @throws IllegalArgumentException if {@code alignment} is {@code null}
* @return a new {@code ParallelGroup}
* @see #createBaselineGroup
* @see GroupLayout.ParallelGroup
*/
public ParallelGroup createParallelGroup(Alignment alignment,
boolean resizable){
if (alignment == Alignment.BASELINE) {
return new BaselineGroup(resizable);
}
return new ParallelGroup(alignment, resizable);
}
/** {@collect.stats}
* Creates and returns a {@code ParallelGroup} that aligns it's
* elements along the baseline.
*
* @param resizable whether the group is resizable
* @param anchorBaselineToTop whether the baseline is anchored to
* the top or bottom of the group
* @see #createBaselineGroup
* @see ParallelGroup
*/
public ParallelGroup createBaselineGroup(boolean resizable,
boolean anchorBaselineToTop) {
return new BaselineGroup(resizable, anchorBaselineToTop);
}
/** {@collect.stats}
* Forces the specified components to have the same size
* regardless of their preferred, minimum or maximum sizes. Components that
* are linked are given the maximum of the preferred size of each of
* the linked components. For example, if you link two components with
* a preferred width of 10 and 20, both components are given a width of 20.
* <p>
* This can be used multiple times to force any number of
* components to share the same size.
* <p>
* Linked Components are not be resizable.
*
* @param components the {@code Component}s that are to have the same size
* @throws IllegalArgumentException if {@code components} is
* {@code null}, or contains {@code null}
* @see #linkSize(int,Component[])
*/
public void linkSize(Component... components) {
linkSize(SwingConstants.HORIZONTAL, components);
linkSize(SwingConstants.VERTICAL, components);
}
/** {@collect.stats}
* Forces the specified components to have the same size along the
* specified axis regardless of their preferred, minimum or
* maximum sizes. Components that are linked are given the maximum
* of the preferred size of each of the linked components. For
* example, if you link two components along the horizontal axis
* and the preferred width is 10 and 20, both components are given
* a width of 20.
* <p>
* This can be used multiple times to force any number of
* components to share the same size.
* <p>
* Linked {@code Component}s are not be resizable.
*
* @param components the {@code Component}s that are to have the same size
* @param axis the axis to link the size along; one of
* {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstans.VERTICAL}
* @throws IllegalArgumentException if {@code components} is
* {@code null}, or contains {@code null}; or {@code axis}
* is not {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstants.VERTICAL}
*/
public void linkSize(int axis, Component... components) {
if (components == null) {
throw new IllegalArgumentException("Components must be non-null");
}
for (int counter = components.length - 1; counter >= 0; counter--) {
Component c = components[counter];
if (components[counter] == null) {
throw new IllegalArgumentException(
"Components must be non-null");
}
// Force the component to be added
getComponentInfo(c);
}
int glAxis;
if (axis == SwingConstants.HORIZONTAL) {
glAxis = HORIZONTAL;
} else if (axis == SwingConstants.VERTICAL) {
glAxis = VERTICAL;
} else {
throw new IllegalArgumentException("Axis must be one of " +
"SwingConstants.HORIZONTAL or SwingConstants.VERTICAL");
}
LinkInfo master = getComponentInfo(
components[components.length - 1]).getLinkInfo(glAxis);
for (int counter = components.length - 2; counter >= 0; counter--) {
master.add(getComponentInfo(components[counter]));
}
invalidateHost();
}
/** {@collect.stats}
* Replaces an existing component with a new one.
*
* @param existingComponent the component that should be removed
* and replaced with {@code newComponent}
* @param newComponent the component to put in
* {@code existingComponent}'s place
* @throws IllegalArgumentException if either of the components are
* {@code null} or {@code existingComponent} is not being managed
* by this layout manager
*/
public void replace(Component existingComponent, Component newComponent) {
if (existingComponent == null || newComponent == null) {
throw new IllegalArgumentException("Components must be non-null");
}
// Make sure all the components have been registered, otherwise we may
// not update the correct Springs.
if (springsChanged) {
registerComponents(horizontalGroup, HORIZONTAL);
registerComponents(verticalGroup, VERTICAL);
}
ComponentInfo info = componentInfos.remove(existingComponent);
if (info == null) {
throw new IllegalArgumentException("Component must already exist");
}
host.remove(existingComponent);
if (newComponent.getParent() != host) {
host.add(newComponent);
}
info.setComponent(newComponent);
componentInfos.put(newComponent, info);
invalidateHost();
}
/** {@collect.stats}
* Sets the {@code LayoutStyle} used to calculate the preferred
* gaps between components. A value of {@code null} indicates the
* shared instance of {@code LayoutStyle} should be used.
*
* @param layoutStyle the {@code LayoutStyle} to use
* @see LayoutStyle
*/
public void setLayoutStyle(LayoutStyle layoutStyle) {
this.layoutStyle = layoutStyle;
invalidateHost();
}
/** {@collect.stats}
* Returns the {@code LayoutStyle} used for calculating the preferred
* gap between components. This returns the value specified to
* {@code setLayoutStyle}, which may be {@code null}.
*
* @return the {@code LayoutStyle} used for calculating the preferred
* gap between components
*/
public LayoutStyle getLayoutStyle() {
return layoutStyle;
}
private LayoutStyle getLayoutStyle0() {
LayoutStyle layoutStyle = getLayoutStyle();
if (layoutStyle == null) {
layoutStyle = LayoutStyle.getInstance();
}
return layoutStyle;
}
private void invalidateHost() {
if (host instanceof JComponent) {
((JComponent)host).revalidate();
} else {
host.invalidate();
}
host.repaint();
}
//
// LayoutManager
//
/** {@collect.stats}
* Notification that a {@code Component} has been added to
* the parent container. You should not invoke this method
* directly, instead you should use one of the {@code Group}
* methods to add a {@code Component}.
*
* @param name the string to be associated with the component
* @param component the {@code Component} to be added
*/
public void addLayoutComponent(String name, Component component) {
}
/** {@collect.stats}
* Notification that a {@code Component} has been removed from
* the parent container. You should not invoke this method
* directly, instead invoke {@code remove} on the parent
* {@code Container}.
*
* @param component the component to be removed
* @see java.awt.Component#remove
*/
public void removeLayoutComponent(Component component) {
ComponentInfo info = componentInfos.remove(component);
if (info != null) {
info.dispose();
springsChanged = true;
isValid = false;
}
}
/** {@collect.stats}
* Returns the preferred size for the specified container.
*
* @param parent the container to return the preferred size for
* @return the preferred size for {@code parent}
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} this was created with
* @throws IllegalStateException if any of the components added to
* this layout are not in both a horizontal and vertical group
* @see java.awt.Container#getPreferredSize
*/
public Dimension preferredLayoutSize(Container parent) {
checkParent(parent);
prepare(PREF_SIZE);
return adjustSize(horizontalGroup.getPreferredSize(HORIZONTAL),
verticalGroup.getPreferredSize(VERTICAL));
}
/** {@collect.stats}
* Returns the minimum size for the specified container.
*
* @param parent the container to return the size for
* @return the minimum size for {@code parent}
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} that this was created with
* @throws IllegalStateException if any of the components added to
* this layout are not in both a horizontal and vertical group
* @see java.awt.Container#getMinimumSize
*/
public Dimension minimumLayoutSize(Container parent) {
checkParent(parent);
prepare(MIN_SIZE);
return adjustSize(horizontalGroup.getMinimumSize(HORIZONTAL),
verticalGroup.getMinimumSize(VERTICAL));
}
/** {@collect.stats}
* Lays out the specified container.
*
* @param parent the container to be laid out
* @throws IllegalStateException if any of the components added to
* this layout are not in both a horizontal and vertical group
*/
public void layoutContainer(Container parent) {
// Step 1: Prepare for layout.
prepare(SPECIFIC_SIZE);
Insets insets = parent.getInsets();
int width = parent.getWidth() - insets.left - insets.right;
int height = parent.getHeight() - insets.top - insets.bottom;
boolean ltr = isLeftToRight();
if (getAutoCreateGaps() || getAutoCreateContainerGaps() ||
hasPreferredPaddingSprings) {
// Step 2: Calculate autopadding springs
calculateAutopadding(horizontalGroup, HORIZONTAL, SPECIFIC_SIZE, 0,
width);
calculateAutopadding(verticalGroup, VERTICAL, SPECIFIC_SIZE, 0,
height);
}
// Step 3: set the size of the groups.
horizontalGroup.setSize(HORIZONTAL, 0, width);
verticalGroup.setSize(VERTICAL, 0, height);
// Step 4: apply the size to the components.
for (ComponentInfo info : componentInfos.values()) {
info.setBounds(insets, width, ltr);
}
}
//
// LayoutManager2
//
/** {@collect.stats}
* Notification that a {@code Component} has been added to
* the parent container. You should not invoke this method
* directly, instead you should use one of the {@code Group}
* methods to add a {@code Component}.
*
* @param component the component added
* @param constraints description of where to place the component
*/
public void addLayoutComponent(Component component, Object constraints) {
}
/** {@collect.stats}
* Returns the maximum size for the specified container.
*
* @param parent the container to return the size for
* @return the maximum size for {@code parent}
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} that this was created with
* @throws IllegalStateException if any of the components added to
* this layout are not in both a horizontal and vertical group
* @see java.awt.Container#getMaximumSize
*/
public Dimension maximumLayoutSize(Container parent) {
checkParent(parent);
prepare(MAX_SIZE);
return adjustSize(horizontalGroup.getMaximumSize(HORIZONTAL),
verticalGroup.getMaximumSize(VERTICAL));
}
/** {@collect.stats}
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*
* @param parent the {@code Container} hosting this {@code LayoutManager}
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} that this was created with
* @return the alignment; this implementation returns {@code .5}
*/
public float getLayoutAlignmentX(Container parent) {
checkParent(parent);
return .5f;
}
/** {@collect.stats}
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*
* @param parent the {@code Container} hosting this {@code LayoutManager}
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} that this was created with
* @return alignment; this implementation returns {@code .5}
*/
public float getLayoutAlignmentY(Container parent) {
checkParent(parent);
return .5f;
}
/** {@collect.stats}
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*
* @param parent the {@code Container} hosting this LayoutManager
* @throws IllegalArgumentException if {@code parent} is not
* the same {@code Container} that this was created with
*/
public void invalidateLayout(Container parent) {
checkParent(parent);
// invalidateLayout is called from Container.invalidate, which
// does NOT grab the treelock. All other methods do. To make sure
// there aren't any possible threading problems we grab the tree lock
// here.
synchronized(parent.getTreeLock()) {
isValid = false;
}
}
private void prepare(int sizeType) {
boolean visChanged = false;
// Step 1: If not-valid, clear springs and update visibility.
if (!isValid) {
isValid = true;
horizontalGroup.setSize(HORIZONTAL, UNSET, UNSET);
verticalGroup.setSize(VERTICAL, UNSET, UNSET);
for (ComponentInfo ci : componentInfos.values()) {
if (ci.updateVisibility()) {
visChanged = true;
}
ci.clearCachedSize();
}
}
// Step 2: Make sure components are bound to ComponentInfos
if (springsChanged) {
registerComponents(horizontalGroup, HORIZONTAL);
registerComponents(verticalGroup, VERTICAL);
}
// Step 3: Adjust the autopadding. This removes existing
// autopadding, then recalculates where it should go.
if (springsChanged || visChanged) {
checkComponents();
horizontalGroup.removeAutopadding();
verticalGroup.removeAutopadding();
if (getAutoCreateGaps()) {
insertAutopadding(true);
} else if (hasPreferredPaddingSprings ||
getAutoCreateContainerGaps()) {
insertAutopadding(false);
}
springsChanged = false;
}
// Step 4: (for min/pref/max size calculations only) calculate the
// autopadding. This invokes for unsetting the calculated values, then
// recalculating them.
// If sizeType == SPECIFIC_SIZE, it indicates we're doing layout, this
// step will be done later on.
if (sizeType != SPECIFIC_SIZE && (getAutoCreateGaps() ||
getAutoCreateContainerGaps() || hasPreferredPaddingSprings)) {
calculateAutopadding(horizontalGroup, HORIZONTAL, sizeType, 0, 0);
calculateAutopadding(verticalGroup, VERTICAL, sizeType, 0, 0);
}
}
private void calculateAutopadding(Group group, int axis, int sizeType,
int origin, int size) {
group.unsetAutopadding();
switch(sizeType) {
case MIN_SIZE:
size = group.getMinimumSize(axis);
break;
case PREF_SIZE:
size = group.getPreferredSize(axis);
break;
case MAX_SIZE:
size = group.getMaximumSize(axis);
break;
default:
break;
}
group.setSize(axis, origin, size);
group.calculateAutopadding(axis);
}
private void checkComponents() {
for (ComponentInfo info : componentInfos.values()) {
if (info.horizontalSpring == null) {
throw new IllegalStateException(info.component +
" is not attached to a horizontal group");
}
if (info.verticalSpring == null) {
throw new IllegalStateException(info.component +
" is not attached to a vertical group");
}
}
}
private void registerComponents(Group group, int axis) {
List<Spring> springs = group.springs;
for (int counter = springs.size() - 1; counter >= 0; counter--) {
Spring spring = springs.get(counter);
if (spring instanceof ComponentSpring) {
((ComponentSpring)spring).installIfNecessary(axis);
} else if (spring instanceof Group) {
registerComponents((Group)spring, axis);
}
}
}
private Dimension adjustSize(int width, int height) {
Insets insets = host.getInsets();
return new Dimension(width + insets.left + insets.right,
height + insets.top + insets.bottom);
}
private void checkParent(Container parent) {
if (parent != host) {
throw new IllegalArgumentException(
"GroupLayout can only be used with one Container at a time");
}
}
/** {@collect.stats}
* Returns the {@code ComponentInfo} for the specified Component,
* creating one if necessary.
*/
private ComponentInfo getComponentInfo(Component component) {
ComponentInfo info = (ComponentInfo)componentInfos.get(component);
if (info == null) {
info = new ComponentInfo(component);
componentInfos.put(component, info);
if (component.getParent() != host) {
host.add(component);
}
}
return info;
}
/** {@collect.stats}
* Adjusts the autopadding springs for the horizontal and vertical
* groups. If {@code insert} is {@code true} this will insert auto padding
* springs, otherwise this will only adjust the springs that
* comprise auto preferred padding springs.
*/
private void insertAutopadding(boolean insert) {
horizontalGroup.insertAutopadding(HORIZONTAL,
new ArrayList<AutoPreferredGapSpring>(1),
new ArrayList<AutoPreferredGapSpring>(1),
new ArrayList<ComponentSpring>(1),
new ArrayList<ComponentSpring>(1), insert);
verticalGroup.insertAutopadding(VERTICAL,
new ArrayList<AutoPreferredGapSpring>(1),
new ArrayList<AutoPreferredGapSpring>(1),
new ArrayList<ComponentSpring>(1),
new ArrayList<ComponentSpring>(1), insert);
}
/** {@collect.stats}
* Returns {@code true} if the two Components have a common ParallelGroup
* ancestor along the particular axis.
*/
private boolean areParallelSiblings(Component source, Component target,
int axis) {
ComponentInfo sourceInfo = getComponentInfo(source);
ComponentInfo targetInfo = getComponentInfo(target);
Spring sourceSpring;
Spring targetSpring;
if (axis == HORIZONTAL) {
sourceSpring = sourceInfo.horizontalSpring;
targetSpring = targetInfo.horizontalSpring;
} else {
sourceSpring = sourceInfo.verticalSpring;
targetSpring = targetInfo.verticalSpring;
}
Set<Spring> sourcePath = tmpParallelSet;
sourcePath.clear();
Spring spring = sourceSpring.getParent();
while (spring != null) {
sourcePath.add(spring);
spring = spring.getParent();
}
spring = targetSpring.getParent();
while (spring != null) {
if (sourcePath.contains(spring)) {
sourcePath.clear();
while (spring != null) {
if (spring instanceof ParallelGroup) {
return true;
}
spring = spring.getParent();
}
return false;
}
spring = spring.getParent();
}
sourcePath.clear();
return false;
}
private boolean isLeftToRight() {
return host.getComponentOrientation().isLeftToRight();
}
/** {@collect.stats}
* Returns a string representation of this {@code GroupLayout}.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this {@code GroupLayout}
**/
public String toString() {
if (springsChanged) {
registerComponents(horizontalGroup, HORIZONTAL);
registerComponents(verticalGroup, VERTICAL);
}
StringBuffer buffer = new StringBuffer();
buffer.append("HORIZONTAL\n");
createSpringDescription(buffer, horizontalGroup, " ", HORIZONTAL);
buffer.append("\nVERTICAL\n");
createSpringDescription(buffer, verticalGroup, " ", VERTICAL);
return buffer.toString();
}
private void createSpringDescription(StringBuffer buffer, Spring spring,
String indent, int axis) {
String origin = "";
String padding = "";
if (spring instanceof ComponentSpring) {
ComponentSpring cSpring = (ComponentSpring)spring;
origin = Integer.toString(cSpring.getOrigin()) + " ";
String name = cSpring.getComponent().getName();
if (name != null) {
origin = "name=" + name + ", ";
}
}
if (spring instanceof AutoPreferredGapSpring) {
AutoPreferredGapSpring paddingSpring =
(AutoPreferredGapSpring)spring;
padding = ", userCreated=" + paddingSpring.getUserCreated() +
", matches=" + paddingSpring.getMatchDescription();
}
buffer.append(indent + spring.getClass().getName() + " " +
Integer.toHexString(spring.hashCode()) + " " +
origin +
", size=" + spring.getSize() +
", alignment=" + spring.getAlignment() +
" prefs=[" + spring.getMinimumSize(axis) +
" " + spring.getPreferredSize(axis) +
" " + spring.getMaximumSize(axis) +
padding + "]\n");
if (spring instanceof Group) {
List<Spring> springs = ((Group)spring).springs;
indent += " ";
for (int counter = 0; counter < springs.size(); counter++) {
createSpringDescription(buffer, springs.get(counter), indent,
axis);
}
}
}
/** {@collect.stats}
* Spring consists of a range: min, pref and max, a value some where in
* the middle of that, and a location. Spring caches the
* min/max/pref. If the min/pref/max has internally changes, or needs
* to be updated you must invoke clear.
*/
private abstract class Spring {
private int size;
private int min;
private int max;
private int pref;
private Spring parent;
private Alignment alignment;
Spring() {
min = pref = max = UNSET;
}
/** {@collect.stats}
* Calculates and returns the minimum size.
*
* @param axis the axis of layout; one of HORIZONTAL or VERTICAL
* @return the minimum size
*/
abstract int calculateMinimumSize(int axis);
/** {@collect.stats}
* Calculates and returns the preferred size.
*
* @param axis the axis of layout; one of HORIZONTAL or VERTICAL
* @return the preferred size
*/
abstract int calculatePreferredSize(int axis);
/** {@collect.stats}
* Calculates and returns the minimum size.
*
* @param axis the axis of layout; one of HORIZONTAL or VERTICAL
* @return the minimum size
*/
abstract int calculateMaximumSize(int axis);
/** {@collect.stats}
* Sets the parent of this Spring.
*/
void setParent(Spring parent) {
this.parent = parent;
}
/** {@collect.stats}
* Returns the parent of this spring.
*/
Spring getParent() {
return parent;
}
// This is here purely as a conveniance for ParallelGroup to avoid
// having to track alignment separately.
void setAlignment(Alignment alignment) {
this.alignment = alignment;
}
/** {@collect.stats}
* Alignment for this Spring, this may be null.
*/
Alignment getAlignment() {
return alignment;
}
/** {@collect.stats}
* Returns the minimum size.
*/
final int getMinimumSize(int axis) {
if (min == UNSET) {
min = constrain(calculateMinimumSize(axis));
}
return min;
}
/** {@collect.stats}
* Returns the preferred size.
*/
final int getPreferredSize(int axis) {
if (pref == UNSET) {
pref = constrain(calculatePreferredSize(axis));
}
return pref;
}
/** {@collect.stats}
* Returns the maximum size.
*/
final int getMaximumSize(int axis) {
if (max == UNSET) {
max = constrain(calculateMaximumSize(axis));
}
return max;
}
/** {@collect.stats}
* Sets the value and location of the spring. Subclasses
* will want to invoke super, then do any additional sizing.
*
* @param axis HORIZONTAL or VERTICAL
* @param origin of this Spring
* @param size of the Spring. If size is UNSET, this invokes
* clear.
*/
void setSize(int axis, int origin, int size) {
this.size = size;
if (size == UNSET) {
unset();
}
}
/** {@collect.stats}
* Resets the cached min/max/pref.
*/
void unset() {
size = min = pref = max = UNSET;
}
/** {@collect.stats}
* Returns the current size.
*/
int getSize() {
return size;
}
int constrain(int value) {
return Math.min(value, Short.MAX_VALUE);
}
int getBaseline() {
return -1;
}
BaselineResizeBehavior getBaselineResizeBehavior() {
return BaselineResizeBehavior.OTHER;
}
final boolean isResizable(int axis) {
int min = getMinimumSize(axis);
int pref = getPreferredSize(axis);
return (min != pref || pref != getMaximumSize(axis));
}
/** {@collect.stats}
* Returns {@code true} if this spring will ALWAYS have a zero
* size. This should NOT check the current size, rather it's
* meant to quickly test if this Spring will always have a
* zero size.
*
* @param treatAutopaddingAsZeroSized if {@code true}, auto padding
* springs should be treated as having a size of {@code 0}
* @return {@code true} if this spring will have a zero size,
* {@code false} otherwise
*/
abstract boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized);
}
/** {@collect.stats}
* {@code Group} provides the basis for the two types of
* operations supported by {@code GroupLayout}: laying out
* components one after another ({@link SequentialGroup SequentialGroup})
* or aligned ({@link ParallelGroup ParallelGroup}). {@code Group} and
* its subclasses have no public constructor; to create one use
* one of {@code createSequentialGroup} or
* {@code createParallelGroup}. Additionally, taking a {@code Group}
* created from one {@code GroupLayout} and using it with another
* will produce undefined results.
* <p>
* Various methods in {@code Group} and its subclasses allow you
* to explicitly specify the range. The arguments to these methods
* can take two forms, either a value greater than or equal to 0,
* or one of {@code DEFAULT_SIZE} or {@code PREFERRED_SIZE}. A
* value greater than or equal to {@code 0} indicates a specific
* size. {@code DEFAULT_SIZE} indicates the corresponding size
* from the component should be used. For example, if {@code
* DEFAULT_SIZE} is passed as the minimum size argument, the
* minimum size is obtained from invoking {@code getMinimumSize}
* on the component. Likewise, {@code PREFERRED_SIZE} indicates
* the value from {@code getPreferredSize} should be used.
* The following example adds {@code myComponent} to {@code group}
* with specific values for the range. That is, the minimum is
* explicitly specified as 100, preferred as 200, and maximum as
* 300.
* <pre>
* group.addComponent(myComponent, 100, 200, 300);
* </pre>
* The following example adds {@code myComponent} to {@code group} using
* a combination of the forms. The minimum size is forced to be the
* same as the preferred size, the preferred size is determined by
* using {@code myComponent.getPreferredSize} and the maximum is
* determined by invoking {@code getMaximumSize} on the component.
* <pre>
* group.addComponent(myComponent, GroupLayout.PREFERRED_SIZE,
* GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE);
* </pre>
* <p>
* Unless otherwise specified all the methods of {@code Group} and
* its subclasses that allow you to specify a range throw an
* {@code IllegalArgumentException} if passed an invalid range. An
* invalid range is one in which any of the values are < 0 and
* not one of {@code PREFERRED_SIZE} or {@code DEFAULT_SIZE}, or
* the following is not met (for specific values): {@code min}
* <= {@code pref} <= {@code max}.
* <p>
* Similarly any methods that take a {@code Component} throw a
* {@code NullPointerException} if passed {@code null} and any methods
* that take a {@code Group} throw an {@code IllegalArgumentException} if
* passed {@code null}.
*
* @see #createSequentialGroup
* @see #createParallelGroup
* @since 1.6
*/
public abstract class Group extends Spring {
// private int origin;
// private int size;
List<Spring> springs;
Group() {
springs = new ArrayList<Spring>();
}
/** {@collect.stats}
* Adds a {@code Group} to this {@code Group}.
*
* @param group the {@code Group} to add
* @return this {@code Group}
*/
public Group addGroup(Group group) {
return addSpring(group);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code Group}.
*
* @param component the {@code Component} to add
* @return this {@code Group}
*/
public Group addComponent(Component component) {
return addComponent(component, DEFAULT_SIZE, DEFAULT_SIZE,
DEFAULT_SIZE);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code Group}
* with the specified size.
*
* @param component the {@code Component} to add
* @param min the minimum size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @param pref the preferred size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @param max the maximum size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @return this {@code Group}
*/
public Group addComponent(Component component, int min, int pref,
int max) {
return addSpring(new ComponentSpring(component, min, pref, max));
}
/** {@collect.stats}
* Adds a rigid gap to this {@code Group}.
*
* @param size the size of the gap
* @return this {@code Group}
* @throws IllegalArgumentException if {@code size} is less than
* {@code 0}
*/
public Group addGap(int size) {
return addGap(size, size, size);
}
/** {@collect.stats}
* Adds a gap to this {@code Group} with the specified size.
*
* @param min the minimum size of the gap
* @param pref the preferred size of the gap
* @param max the maximum size of the gap
* @throws IllegalArgumentException if any of the values are
* less than {@code 0}
* @return this {@code Group}
*/
public Group addGap(int min, int pref, int max) {
return addSpring(new GapSpring(min, pref, max));
}
Spring getSpring(int index) {
return springs.get(index);
}
int indexOf(Spring spring) {
return springs.indexOf(spring);
}
/** {@collect.stats}
* Adds the Spring to the list of {@code Spring}s and returns
* the receiver.
*/
Group addSpring(Spring spring) {
springs.add(spring);
spring.setParent(this);
if (!(spring instanceof AutoPreferredGapSpring) ||
!((AutoPreferredGapSpring)spring).getUserCreated()) {
springsChanged = true;
}
return this;
}
//
// Spring methods
//
void setSize(int axis, int origin, int size) {
super.setSize(axis, origin, size);
if (size == UNSET) {
for (int counter = springs.size() - 1; counter >= 0;
counter--) {
getSpring(counter).setSize(axis, origin, size);
}
} else {
setValidSize(axis, origin, size);
}
}
/** {@collect.stats}
* This is invoked from {@code setSize} if passed a value
* other than UNSET.
*/
abstract void setValidSize(int axis, int origin, int size);
int calculateMinimumSize(int axis) {
return calculateSize(axis, MIN_SIZE);
}
int calculatePreferredSize(int axis) {
return calculateSize(axis, PREF_SIZE);
}
int calculateMaximumSize(int axis) {
return calculateSize(axis, MAX_SIZE);
}
/** {@collect.stats}
* Calculates the specified size. This is called from
* one of the {@code getMinimumSize0},
* {@code getPreferredSize0} or
* {@code getMaximumSize0} methods. This will invoke
* to {@code operator} to combine the values.
*/
int calculateSize(int axis, int type) {
int count = springs.size();
if (count == 0) {
return 0;
}
if (count == 1) {
return getSpringSize(getSpring(0), axis, type);
}
int size = constrain(operator(getSpringSize(getSpring(0), axis,
type), getSpringSize(getSpring(1), axis, type)));
for (int counter = 2; counter < count; counter++) {
size = constrain(operator(size, getSpringSize(
getSpring(counter), axis, type)));
}
return size;
}
int getSpringSize(Spring spring, int axis, int type) {
switch(type) {
case MIN_SIZE:
return spring.getMinimumSize(axis);
case PREF_SIZE:
return spring.getPreferredSize(axis);
case MAX_SIZE:
return spring.getMaximumSize(axis);
}
assert false;
return 0;
}
/** {@collect.stats}
* Used to compute how the two values representing two springs
* will be combined. For example, a group that layed things out
* one after the next would return {@code a + b}.
*/
abstract int operator(int a, int b);
//
// Padding
//
/** {@collect.stats}
* Adjusts the autopadding springs in this group and its children.
* If {@code insert} is true this will insert auto padding
* springs, otherwise this will only adjust the springs that
* comprise auto preferred padding springs.
*
* @param axis the axis of the springs; HORIZONTAL or VERTICAL
* @param leadingPadding List of AutopaddingSprings that occur before
* this Group
* @param trailingPadding any trailing autopadding springs are added
* to this on exit
* @param leading List of ComponentSprings that occur before this Group
* @param trailing any trailing ComponentSpring are added to this
* List
* @param insert Whether or not to insert AutopaddingSprings or just
* adjust any existing AutopaddingSprings.
*/
abstract void insertAutopadding(int axis,
List<AutoPreferredGapSpring> leadingPadding,
List<AutoPreferredGapSpring> trailingPadding,
List<ComponentSpring> leading, List<ComponentSpring> trailing,
boolean insert);
/** {@collect.stats}
* Removes any AutopaddingSprings for this Group and its children.
*/
void removeAutopadding() {
unset();
for (int counter = springs.size() - 1; counter >= 0; counter--) {
Spring spring = springs.get(counter);
if (spring instanceof AutoPreferredGapSpring) {
if (((AutoPreferredGapSpring)spring).getUserCreated()) {
((AutoPreferredGapSpring)spring).reset();
} else {
springs.remove(counter);
}
} else if (spring instanceof Group) {
((Group)spring).removeAutopadding();
}
}
}
void unsetAutopadding() {
// Clear cached pref/min/max.
unset();
for (int counter = springs.size() - 1; counter >= 0; counter--) {
Spring spring = springs.get(counter);
if (spring instanceof AutoPreferredGapSpring) {
((AutoPreferredGapSpring)spring).unset();
} else if (spring instanceof Group) {
((Group)spring).unsetAutopadding();
}
}
}
void calculateAutopadding(int axis) {
for (int counter = springs.size() - 1; counter >= 0; counter--) {
Spring spring = springs.get(counter);
if (spring instanceof AutoPreferredGapSpring) {
// Force size to be reset.
spring.unset();
((AutoPreferredGapSpring)spring).calculatePadding(axis);
} else if (spring instanceof Group) {
((Group)spring).calculateAutopadding(axis);
}
}
// Clear cached pref/min/max.
unset();
}
@Override
boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized) {
for (int i = springs.size() - 1; i >= 0; i--) {
Spring spring = springs.get(i);
if (!spring.willHaveZeroSize(treatAutopaddingAsZeroSized)) {
return false;
}
}
return true;
}
}
/** {@collect.stats}
* A {@code Group} that positions and sizes its elements
* sequentially, one after another. This class has no public
* constructor, use the {@code createSequentialGroup} method
* to create one.
* <p>
* In order to align a {@code SequentialGroup} along the baseline
* of a baseline aligned {@code ParallelGroup} you need to specify
* which of the elements of the {@code SequentialGroup} is used to
* determine the baseline. The element used to calculate the
* baseline is specified using one of the {@code add} methods that
* take a {@code boolean}. The last element added with a value of
* {@code true} for {@code useAsBaseline} is used to calculate the
* baseline.
*
* @see #createSequentialGroup
* @since 1.6
*/
public class SequentialGroup extends Group {
private Spring baselineSpring;
SequentialGroup() {
}
/** {@collect.stats}
* {@inheritDoc}
*/
public SequentialGroup addGroup(Group group) {
return (SequentialGroup)super.addGroup(group);
}
/** {@collect.stats}
* Adds a {@code Group} to this {@code Group}.
*
* @param group the {@code Group} to add
* @param useAsBaseline whether the specified {@code Group} should
* be used to calculate the baseline for this {@code Group}
* @return this {@code Group}
*/
public SequentialGroup addGroup(boolean useAsBaseline, Group group) {
super.addGroup(group);
if (useAsBaseline) {
baselineSpring = group;
}
return this;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public SequentialGroup addComponent(Component component) {
return (SequentialGroup)super.addComponent(component);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code Group}.
*
* @param useAsBaseline whether the specified {@code Component} should
* be used to calculate the baseline for this {@code Group}
* @param component the {@code Component} to add
* @return this {@code Group}
*/
public SequentialGroup addComponent(boolean useAsBaseline,
Component component) {
super.addComponent(component);
if (useAsBaseline) {
baselineSpring = springs.get(springs.size() - 1);
}
return this;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public SequentialGroup addComponent(Component component, int min,
int pref, int max) {
return (SequentialGroup)super.addComponent(
component, min, pref, max);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code Group}
* with the specified size.
*
* @param useAsBaseline whether the specified {@code Component} should
* be used to calculate the baseline for this {@code Group}
* @param component the {@code Component} to add
* @param min the minimum size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @param pref the preferred size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @param max the maximum size or one of {@code DEFAULT_SIZE} or
* {@code PREFERRED_SIZE}
* @return this {@code Group}
*/
public SequentialGroup addComponent(boolean useAsBaseline,
Component component, int min, int pref, int max) {
super.addComponent(component, min, pref, max);
if (useAsBaseline) {
baselineSpring = springs.get(springs.size() - 1);
}
return this;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public SequentialGroup addGap(int size) {
return (SequentialGroup)super.addGap(size);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public SequentialGroup addGap(int min, int pref, int max) {
return (SequentialGroup)super.addGap(min, pref, max);
}
/** {@collect.stats}
* Adds an element representing the preferred gap between two
* components. The element created to represent the gap is not
* resizable.
*
* @param comp1 the first component
* @param comp2 the second component
* @param type the type of gap; one of the constants defined by
* {@code LayoutStyle}
* @return this {@code SequentialGroup}
* @throws IllegalArgumentException if {@code type}, {@code comp1} or
* {@code comp2} is {@code null}
* @see LayoutStyle
*/
public SequentialGroup addPreferredGap(JComponent comp1,
JComponent comp2, ComponentPlacement type) {
return addPreferredGap(comp1, comp2, type, DEFAULT_SIZE,
PREFERRED_SIZE);
}
/** {@collect.stats}
* Adds an element representing the preferred gap between two
* components.
*
* @param comp1 the first component
* @param comp2 the second component
* @param type the type of gap
* @param pref the preferred size of the grap; one of
* {@code DEFAULT_SIZE} or a value >= 0
* @param max the maximum size of the gap; one of
* {@code DEFAULT_SIZE}, {@code PREFERRED_SIZE}
* or a value >= 0
* @return this {@code SequentialGroup}
* @throws IllegalArgumentException if {@code type}, {@code comp1} or
* {@code comp2} is {@code null}
* @see LayoutStyle
*/
public SequentialGroup addPreferredGap(JComponent comp1,
JComponent comp2, ComponentPlacement type, int pref,
int max) {
if (type == null) {
throw new IllegalArgumentException("Type must be non-null");
}
if (comp1 == null || comp2 == null) {
throw new IllegalArgumentException(
"Components must be non-null");
}
checkPreferredGapValues(pref, max);
return (SequentialGroup)addSpring(new PreferredGapSpring(
comp1, comp2, type, pref, max));
}
/** {@collect.stats}
* Adds an element representing the preferred gap between the
* nearest components. During layout, neighboring
* components are found, and the size of the added gap is set
* based on the preferred gap between the components. If no
* neighboring components are found the gap has a size of {@code 0}.
* <p>
* The element created to represent the gap is not
* resizable.
*
* @param type the type of gap; one of
* {@code LayoutStyle.ComponentPlacement.RELATED} or
* {@code LayoutStyle.ComponentPlacement.UNRELATED}
* @return this {@code SequentialGroup}
* @see LayoutStyle
* @throws IllegalArgumentException if {@code type} is not one of
* {@code LayoutStyle.ComponentPlacement.RELATED} or
* {@code LayoutStyle.ComponentPlacement.UNRELATED}
*/
public SequentialGroup addPreferredGap(ComponentPlacement type) {
return addPreferredGap(type, DEFAULT_SIZE, DEFAULT_SIZE);
}
/** {@collect.stats}
* Adds an element representing the preferred gap between the
* nearest components. During layout, neighboring
* components are found, and the minimum of this
* gap is set based on the size of the preferred gap between the
* neighboring components. If no neighboring components are found the
* minimum size is set to 0.
*
* @param type the type of gap; one of
* {@code LayoutStyle.ComponentPlacement.RELATED} or
* {@code LayoutStyle.ComponentPlacement.UNRELATED}
* @param pref the preferred size of the grap; one of
* {@code DEFAULT_SIZE} or a value >= 0
* @param max the maximum size of the gap; one of
* {@code DEFAULT_SIZE}, {@code PREFERRED_SIZE}
* or a value >= 0
* @return this {@code SequentialGroup}
* @throws IllegalArgumentException if {@code type} is not one of
* {@code LayoutStyle.ComponentPlacement.RELATED} or
* {@code LayoutStyle.ComponentPlacement.UNRELATED}
* @see LayoutStyle
*/
public SequentialGroup addPreferredGap(ComponentPlacement type,
int pref, int max) {
if (type != ComponentPlacement.RELATED &&
type != ComponentPlacement.UNRELATED) {
throw new IllegalArgumentException(
"Type must be one of " +
"LayoutStyle.ComponentPlacement.RELATED or " +
"LayoutStyle.ComponentPlacement.UNRELATED");
}
checkPreferredGapValues(pref, max);
hasPreferredPaddingSprings = true;
return (SequentialGroup)addSpring(new AutoPreferredGapSpring(
type, pref, max));
}
/** {@collect.stats}
* Adds an element representing the preferred gap between an edge
* the container and components that touch the border of the
* container. This has no effect if the added gap does not
* touch an edge of the parent container.
* <p>
* The element created to represent the gap is not
* resizable.
*
* @return this {@code SequentialGroup}
*/
public SequentialGroup addContainerGap() {
return addContainerGap(DEFAULT_SIZE, DEFAULT_SIZE);
}
/** {@collect.stats}
* Adds an element representing the preferred gap between one
* edge of the container and the next or previous {@code
* Component} with the specified size. This has no
* effect if the next or previous element is not a {@code
* Component} and does not touch one edge of the parent
* container.
*
* @param pref the preferred size; one of {@code DEFAULT_SIZE} or a
* value >= 0
* @param max the maximum size; one of {@code DEFAULT_SIZE},
* {@code PREFERRED_SIZE} or a value >= 0
* @return this {@code SequentialGroup}
*/
public SequentialGroup addContainerGap(int pref, int max) {
if ((pref < 0 && pref != DEFAULT_SIZE) ||
(max < 0 && max != DEFAULT_SIZE && max != PREFERRED_SIZE)||
(pref >= 0 && max >= 0 && pref > max)) {
throw new IllegalArgumentException(
"Pref and max must be either DEFAULT_VALUE " +
"or >= 0 and pref <= max");
}
hasPreferredPaddingSprings = true;
return (SequentialGroup)addSpring(
new ContainerAutoPreferredGapSpring(pref, max));
}
int operator(int a, int b) {
return constrain(a) + constrain(b);
}
void setValidSize(int axis, int origin, int size) {
int pref = getPreferredSize(axis);
if (size == pref) {
// Layout at preferred size
for (Spring spring : springs) {
int springPref = spring.getPreferredSize(axis);
spring.setSize(axis, origin, springPref);
origin += springPref;
}
} else if (springs.size() == 1) {
Spring spring = getSpring(0);
spring.setSize(axis, origin, Math.min(
Math.max(size, spring.getMinimumSize(axis)),
spring.getMaximumSize(axis)));
} else if (springs.size() > 1) {
// Adjust between min/pref
setValidSizeNotPreferred(axis, origin, size);
}
}
private void setValidSizeNotPreferred(int axis, int origin, int size) {
int delta = size - getPreferredSize(axis);
assert delta != 0;
boolean useMin = (delta < 0);
int springCount = springs.size();
if (useMin) {
delta *= -1;
}
// The following algorithm if used for resizing springs:
// 1. Calculate the resizability of each spring (pref - min or
// max - pref) into a list.
// 2. Sort the list in ascending order
// 3. Iterate through each of the resizable Springs, attempting
// to give them (pref - size) / resizeCount
// 4. For any Springs that can not accomodate that much space
// add the remainder back to the amount to distribute and
// recalculate how must space the remaining springs will get.
// 5. Set the size of the springs.
// First pass, sort the resizable springs into the List resizable
List<SpringDelta> resizable = buildResizableList(axis, useMin);
int resizableCount = resizable.size();
if (resizableCount > 0) {
// How much we would like to give each Spring.
int sDelta = delta / resizableCount;
// Remaining space.
int slop = delta - sDelta * resizableCount;
int[] sizes = new int[springCount];
int sign = useMin ? -1 : 1;
// Second pass, accumulate the resulting deltas (relative to
// preferred) into sizes.
for (int counter = 0; counter < resizableCount; counter++) {
SpringDelta springDelta = resizable.get(counter);
if ((counter + 1) == resizableCount) {
sDelta += slop;
}
springDelta.delta = Math.min(sDelta, springDelta.delta);
delta -= springDelta.delta;
if (springDelta.delta != sDelta && counter + 1 <
resizableCount) {
// Spring didn't take all the space, reset how much
// each spring will get.
sDelta = delta / (resizableCount - counter - 1);
slop = delta - sDelta * (resizableCount - counter - 1);
}
sizes[springDelta.index] = sign * springDelta.delta;
}
// And finally set the size of each spring
for (int counter = 0; counter < springCount; counter++) {
Spring spring = getSpring(counter);
int sSize = spring.getPreferredSize(axis) + sizes[counter];
spring.setSize(axis, origin, sSize);
origin += sSize;
}
} else {
// Nothing resizable, use the min or max of each of the
// springs.
for (int counter = 0; counter < springCount; counter++) {
Spring spring = getSpring(counter);
int sSize;
if (useMin) {
sSize = spring.getMinimumSize(axis);
} else {
sSize = spring.getMaximumSize(axis);
}
spring.setSize(axis, origin, sSize);
origin += sSize;
}
}
}
/** {@collect.stats}
* Returns the sorted list of SpringDelta's for the current set of
* Springs. The list is ordered based on the amount of flexibility of
* the springs.
*/
private List<SpringDelta> buildResizableList(int axis,
boolean useMin) {
// First pass, figure out what is resizable
int size = springs.size();
List<SpringDelta> sorted = new ArrayList<SpringDelta>(size);
for (int counter = 0; counter < size; counter++) {
Spring spring = getSpring(counter);
int sDelta;
if (useMin) {
sDelta = spring.getPreferredSize(axis) -
spring.getMinimumSize(axis);
} else {
sDelta = spring.getMaximumSize(axis) -
spring.getPreferredSize(axis);
}
if (sDelta > 0) {
sorted.add(new SpringDelta(counter, sDelta));
}
}
Collections.sort(sorted);
return sorted;
}
private int indexOfNextNonZeroSpring(
int index, boolean treatAutopaddingAsZeroSized) {
while (index < springs.size()) {
Spring spring = springs.get(index);
if (!spring.willHaveZeroSize(treatAutopaddingAsZeroSized)) {
return index;
}
index++;
}
return index;
}
@Override
void insertAutopadding(int axis,
List<AutoPreferredGapSpring> leadingPadding,
List<AutoPreferredGapSpring> trailingPadding,
List<ComponentSpring> leading, List<ComponentSpring> trailing,
boolean insert) {
List<AutoPreferredGapSpring> newLeadingPadding =
new ArrayList<AutoPreferredGapSpring>(leadingPadding);
List<AutoPreferredGapSpring> newTrailingPadding =
new ArrayList<AutoPreferredGapSpring>(1);
List<ComponentSpring> newLeading =
new ArrayList<ComponentSpring>(leading);
List<ComponentSpring> newTrailing = null;
int counter = 0;
// Warning, this must use springs.size, as it may change during the
// loop.
while (counter < springs.size()) {
Spring spring = getSpring(counter);
if (spring instanceof AutoPreferredGapSpring) {
if (newLeadingPadding.size() == 0) {
// Autopadding spring. Set the sources of the
// autopadding spring based on newLeading.
AutoPreferredGapSpring padding =
(AutoPreferredGapSpring)spring;
padding.setSources(newLeading);
newLeading.clear();
counter = indexOfNextNonZeroSpring(counter + 1, true);
if (counter == springs.size()) {
// Last spring in the list, add it to
// trailingPadding.
if (!(padding instanceof
ContainerAutoPreferredGapSpring)) {
trailingPadding.add(padding);
}
} else {
newLeadingPadding.clear();
newLeadingPadding.add(padding);
}
} else {
counter = indexOfNextNonZeroSpring(counter + 1, true);
}
} else {
// Not a padding spring
if (newLeading.size() > 0 && insert) {
// There's leading ComponentSprings, create an
// autopadding spring.
AutoPreferredGapSpring padding =
new AutoPreferredGapSpring();
// Force the newly created spring to be considered
// by NOT incrementing counter
springs.add(counter, padding);
continue;
}
if (spring instanceof ComponentSpring) {
// Spring is a Component, make it the target of any
// leading AutopaddingSpring.
ComponentSpring cSpring = (ComponentSpring)spring;
if (!cSpring.isVisible()) {
counter++;
continue;
}
for (AutoPreferredGapSpring gapSpring : newLeadingPadding) {
gapSpring.addTarget(cSpring, axis);
}
newLeading.clear();
newLeadingPadding.clear();
counter = indexOfNextNonZeroSpring(counter + 1, false);
if (counter == springs.size()) {
// Last Spring, add it to trailing
trailing.add(cSpring);
} else {
// Not that last Spring, add it to leading
newLeading.add(cSpring);
}
} else if (spring instanceof Group) {
// Forward call to child Group
if (newTrailing == null) {
newTrailing = new ArrayList<ComponentSpring>(1);
} else {
newTrailing.clear();
}
newTrailingPadding.clear();
((Group)spring).insertAutopadding(axis,
newLeadingPadding, newTrailingPadding,
newLeading, newTrailing, insert);
newLeading.clear();
newLeadingPadding.clear();
counter = indexOfNextNonZeroSpring(
counter + 1, (newTrailing.size() == 0));
if (counter == springs.size()) {
trailing.addAll(newTrailing);
trailingPadding.addAll(newTrailingPadding);
} else {
newLeading.addAll(newTrailing);
newLeadingPadding.addAll(newTrailingPadding);
}
} else {
// Gap
newLeadingPadding.clear();
newLeading.clear();
counter++;
}
}
}
}
int getBaseline() {
if (baselineSpring != null) {
int baseline = baselineSpring.getBaseline();
if (baseline >= 0) {
int size = 0;
for (Spring spring : springs) {
if (spring == baselineSpring) {
return size + baseline;
} else {
size += spring.getPreferredSize(VERTICAL);
}
}
}
}
return -1;
}
BaselineResizeBehavior getBaselineResizeBehavior() {
if (isResizable(VERTICAL)) {
if (!baselineSpring.isResizable(VERTICAL)) {
// Spring to use for baseline isn't resizable. In this case
// baseline resize behavior can be determined based on how
// preceeding springs resize.
boolean leadingResizable = false;
for (Spring spring : springs) {
if (spring == baselineSpring) {
break;
} else if (spring.isResizable(VERTICAL)) {
leadingResizable = true;
break;
}
}
boolean trailingResizable = false;
for (int i = springs.size() - 1; i >= 0; i--) {
Spring spring = springs.get(i);
if (spring == baselineSpring) {
break;
}
if (spring.isResizable(VERTICAL)) {
trailingResizable = true;
break;
}
}
if (leadingResizable && !trailingResizable) {
return BaselineResizeBehavior.CONSTANT_DESCENT;
} else if (!leadingResizable && trailingResizable) {
return BaselineResizeBehavior.CONSTANT_ASCENT;
}
// If we get here, both leading and trailing springs are
// resizable. Fall through to OTHER.
} else {
BaselineResizeBehavior brb = baselineSpring.getBaselineResizeBehavior();
if (brb == BaselineResizeBehavior.CONSTANT_ASCENT) {
for (Spring spring : springs) {
if (spring == baselineSpring) {
return BaselineResizeBehavior.CONSTANT_ASCENT;
}
if (spring.isResizable(VERTICAL)) {
return BaselineResizeBehavior.OTHER;
}
}
} else if (brb == BaselineResizeBehavior.CONSTANT_DESCENT) {
for (int i = springs.size() - 1; i >= 0; i--) {
Spring spring = springs.get(i);
if (spring == baselineSpring) {
return BaselineResizeBehavior.CONSTANT_DESCENT;
}
if (spring.isResizable(VERTICAL)) {
return BaselineResizeBehavior.OTHER;
}
}
}
}
return BaselineResizeBehavior.OTHER;
}
// Not resizable, treat as constant_ascent
return BaselineResizeBehavior.CONSTANT_ASCENT;
}
private void checkPreferredGapValues(int pref, int max) {
if ((pref < 0 && pref != DEFAULT_SIZE && pref != PREFERRED_SIZE) ||
(max < 0 && max != DEFAULT_SIZE && max != PREFERRED_SIZE)||
(pref >= 0 && max >= 0 && pref > max)) {
throw new IllegalArgumentException(
"Pref and max must be either DEFAULT_SIZE, " +
"PREFERRED_SIZE, or >= 0 and pref <= max");
}
}
}
/** {@collect.stats}
* Used by SequentialGroup in calculating resizability of springs.
*/
private static final class SpringDelta implements Comparable<SpringDelta> {
// Original index.
public final int index;
// Delta, one of pref - min or max - pref.
public int delta;
public SpringDelta(int index, int delta) {
this.index = index;
this.delta = delta;
}
public int compareTo(SpringDelta o) {
return delta - o.delta;
}
public String toString() {
return super.toString() + "[index=" + index + ", delta=" +
delta + "]";
}
}
/** {@collect.stats}
* A {@code Group} that aligns and sizes it's children.
* {@code ParallelGroup} aligns it's children in
* four possible ways: along the baseline, centered, anchored to the
* leading edge, or anchored to the trailing edge.
* <h3>Baseline</h3>
* A {@code ParallelGroup} that aligns it's children along the
* baseline must first decide where the baseline is
* anchored. The baseline can either be anchored to the top, or
* anchored to the bottom of the group. That is, the distance between the
* baseline and the beginning of the group can be a constant
* distance, or the distance between the end of the group and the
* baseline can be a constant distance. The possible choices
* correspond to the {@code BaselineResizeBehavior} constants
* {@link
* java.awt.Component.BaselineResizeBehavior#CONSTANT_ASCENT CONSTANT_ASCENT} and
* {@link
* java.awt.Component.BaselineResizeBehavior#CONSTANT_DESCENT CONSTANT_DESCENT}.
* <p>
* The baseline anchor may be explicitly specified by the
* {@code createBaselineGroup} method, or determined based on the elements.
* If not explicitly specified, the baseline will be anchored to
* the bottom if all the elements with a baseline, and that are
* aligned to the baseline, have a baseline resize behavior of
* {@code CONSTANT_DESCENT}; otherwise the baseline is anchored to the top
* of the group.
* <p>
* Elements aligned to the baseline are resizable if they have have
* a baseline resize behavior of {@code CONSTANT_ASCENT} or
* {@code CONSTANT_DESCENT}. Elements with a baseline resize
* behavior of {@code OTHER} or {@code CENTER_OFFSET} are not resizable.
* <p>
* The baseline is calculated based on the preferred height of each
* of the elements that have a baseline. The baseline is
* calculated using the following algorithm:
* {@code max(maxNonBaselineHeight, maxAscent + maxDescent)}, where the
* {@code maxNonBaselineHeight} is the maximum height of all elements
* that do not have a baseline, or are not aligned along the baseline.
* {@code maxAscent} is the maximum ascent (baseline) of all elements that
* have a baseline and are aligned along the baseline.
* {@code maxDescent} is the maximum descent (preferred height - baseline)
* of all elements that have a baseline and are aligned along the baseline.
* <p>
* A {@code ParallelGroup} that aligns it's elements along the baseline
* is only useful along the vertical axis. If you create a
* baseline group and use it along the horizontal axis an
* {@code IllegalStateException} is thrown when you ask
* {@code GroupLayout} for the minimum, preferred or maximum size or
* attempt to layout the components.
* <p>
* Elements that are not aligned to the baseline and smaller than the size
* of the {@code ParallelGroup} are positioned in one of three
* ways: centered, anchored to the leading edge, or anchored to the
* trailing edge.
*
* <h3>Non-baseline {@code ParallelGroup}</h3>
* {@code ParallelGroup}s created with an alignment other than
* {@code BASELINE} align elements that are smaller than the size
* of the group in one of three ways: centered, anchored to the
* leading edge, or anchored to the trailing edge.
* <p>
* The leading edge is based on the axis and {@code
* ComponentOrientation}. For the vertical axis the top edge is
* always the leading edge, and the bottom edge is always the
* trailing edge. When the {@code ComponentOrientation} is {@code
* LEFT_TO_RIGHT}, the leading edge is the left edge and the
* trailing edge the right edge. A {@code ComponentOrientation} of
* {@code RIGHT_TO_LEFT} flips the left and right edges. Child
* elements are aligned based on the specified alignment the
* element was added with. If you do not specify an alignment, the
* alignment specified for the {@code ParallelGroup} is used.
* <p>
* To align elements along the baseline you {@code createBaselineGroup},
* or {@code createParallelGroup} with an alignment of {@code BASELINE}.
* If the group was not created with a baseline alignment, and you attempt
* to add an element specifying a baseline alignment, an
* {@code IllegalArgumentException} is thrown.
*
* @see #createParallelGroup()
* @see #createBaselineGroup(boolean,boolean)
* @since 1.6
*/
public class ParallelGroup extends Group {
// How children are layed out.
private final Alignment childAlignment;
// Whether or not we're resizable.
private final boolean resizable;
ParallelGroup(Alignment childAlignment, boolean resizable) {
this.childAlignment = childAlignment;
this.resizable = resizable;
}
/** {@collect.stats}
* {@inheritDoc}
*/
public ParallelGroup addGroup(Group group) {
return (ParallelGroup)super.addGroup(group);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public ParallelGroup addComponent(Component component) {
return (ParallelGroup)super.addComponent(component);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public ParallelGroup addComponent(Component component, int min, int pref,
int max) {
return (ParallelGroup)super.addComponent(component, min, pref, max);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public ParallelGroup addGap(int pref) {
return (ParallelGroup)super.addGap(pref);
}
/** {@collect.stats}
* {@inheritDoc}
*/
public ParallelGroup addGap(int min, int pref, int max) {
return (ParallelGroup)super.addGap(min, pref, max);
}
/** {@collect.stats}
* Adds a {@code Group} to this {@code ParallelGroup} with the
* specified alignment. If the child is smaller than the
* {@code Group} it is aligned based on the specified
* alignment.
*
* @param alignment the alignment
* @param group the {@code Group} to add
* @return this {@code ParallelGroup}
* @throws IllegalArgumentException if {@code alignment} is
* {@code null}
*/
public ParallelGroup addGroup(Alignment alignment, Group group) {
checkChildAlignment(alignment);
group.setAlignment(alignment);
return (ParallelGroup)addSpring(group);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code ParallelGroup} with
* the specified alignment.
*
* @param alignment the alignment
* @param component the {@code Component} to add
* @return this {@code Group}
* @throws IllegalArgumentException if {@code alignment} is
* {@code null}
*/
public ParallelGroup addComponent(Component component,
Alignment alignment) {
return addComponent(component, alignment, DEFAULT_SIZE, DEFAULT_SIZE,
DEFAULT_SIZE);
}
/** {@collect.stats}
* Adds a {@code Component} to this {@code ParallelGroup} with the
* specified alignment and size.
*
* @param alignment the alignment
* @param component the {@code Component} to add
* @param min the minimum size
* @param pref the preferred size
* @param max the maximum size
* @throws IllegalArgumentException if {@code alignment} is
* {@code null}
* @return this {@code Group}
*/
public ParallelGroup addComponent(Component component,
Alignment alignment, int min, int pref, int max) {
checkChildAlignment(alignment);
ComponentSpring spring = new ComponentSpring(component,
min, pref, max);
spring.setAlignment(alignment);
return (ParallelGroup)addSpring(spring);
}
boolean isResizable() {
return resizable;
}
int operator(int a, int b) {
return Math.max(a, b);
}
int calculateMinimumSize(int axis) {
if (!isResizable()) {
return getPreferredSize(axis);
}
return super.calculateMinimumSize(axis);
}
int calculateMaximumSize(int axis) {
if (!isResizable()) {
return getPreferredSize(axis);
}
return super.calculateMaximumSize(axis);
}
void setValidSize(int axis, int origin, int size) {
for (Spring spring : springs) {
setChildSize(spring, axis, origin, size);
}
}
void setChildSize(Spring spring, int axis, int origin, int size) {
Alignment alignment = spring.getAlignment();
int springSize = Math.min(
Math.max(spring.getMinimumSize(axis), size),
spring.getMaximumSize(axis));
if (alignment == null) {
alignment = childAlignment;
}
switch (alignment) {
case TRAILING:
spring.setSize(axis, origin + size - springSize,
springSize);
break;
case CENTER:
spring.setSize(axis, origin +
(size - springSize) / 2,springSize);
break;
default: // LEADING, or BASELINE
spring.setSize(axis, origin, springSize);
break;
}
}
@Override
void insertAutopadding(int axis,
List<AutoPreferredGapSpring> leadingPadding,
List<AutoPreferredGapSpring> trailingPadding,
List<ComponentSpring> leading, List<ComponentSpring> trailing,
boolean insert) {
for (Spring spring : springs) {
if (spring instanceof ComponentSpring) {
if (((ComponentSpring)spring).isVisible()) {
for (AutoPreferredGapSpring gapSpring :
leadingPadding) {
gapSpring.addTarget((ComponentSpring)spring, axis);
}
trailing.add((ComponentSpring)spring);
}
} else if (spring instanceof Group) {
((Group)spring).insertAutopadding(axis, leadingPadding,
trailingPadding, leading, trailing, insert);
} else if (spring instanceof AutoPreferredGapSpring) {
((AutoPreferredGapSpring)spring).setSources(leading);
trailingPadding.add((AutoPreferredGapSpring)spring);
}
}
}
private void checkChildAlignment(Alignment alignment) {
checkChildAlignment(alignment, (this instanceof BaselineGroup));
}
private void checkChildAlignment(Alignment alignment,
boolean allowsBaseline) {
if (alignment == null) {
throw new IllegalArgumentException("Alignment must be non-null");
}
if (!allowsBaseline && alignment == Alignment.BASELINE) {
throw new IllegalArgumentException("Alignment must be one of:" +
"LEADING, TRAILING or CENTER");
}
}
}
/** {@collect.stats}
* An extension of {@code ParallelGroup} that aligns its
* constituent {@code Spring}s along the baseline.
*/
private class BaselineGroup extends ParallelGroup {
// Whether or not all child springs have a baseline
private boolean allSpringsHaveBaseline;
// max(spring.getBaseline()) of all springs aligned along the baseline
// that have a baseline
private int prefAscent;
// max(spring.getPreferredSize().height - spring.getBaseline()) of all
// springs aligned along the baseline that have a baseline
private int prefDescent;
// Whether baselineAnchoredToTop was explicitly set
private boolean baselineAnchorSet;
// Whether the baseline is anchored to the top or the bottom.
// If anchored to the top the baseline is always at prefAscent,
// otherwise the baseline is at (height - prefDescent)
private boolean baselineAnchoredToTop;
// Whether or not the baseline has been calculated.
private boolean calcedBaseline;
BaselineGroup(boolean resizable) {
super(Alignment.LEADING, resizable);
prefAscent = prefDescent = -1;
calcedBaseline = false;
}
BaselineGroup(boolean resizable, boolean baselineAnchoredToTop) {
this(resizable);
this.baselineAnchoredToTop = baselineAnchoredToTop;
baselineAnchorSet = true;
}
void unset() {
super.unset();
prefAscent = prefDescent = -1;
calcedBaseline = false;
}
void setValidSize(int axis, int origin, int size) {
checkAxis(axis);
if (prefAscent == -1) {
super.setValidSize(axis, origin, size);
} else {
// do baseline layout
baselineLayout(origin, size);
}
}
int calculateSize(int axis, int type) {
checkAxis(axis);
if (!calcedBaseline) {
calculateBaselineAndResizeBehavior();
}
if (type == MIN_SIZE) {
return calculateMinSize();
}
if (type == MAX_SIZE) {
return calculateMaxSize();
}
if (allSpringsHaveBaseline) {
return prefAscent + prefDescent;
}
return Math.max(prefAscent + prefDescent,
super.calculateSize(axis, type));
}
private void calculateBaselineAndResizeBehavior() {
// calculate baseline
prefAscent = 0;
prefDescent = 0;
int baselineSpringCount = 0;
BaselineResizeBehavior resizeBehavior = null;
for (Spring spring : springs) {
if (spring.getAlignment() == null ||
spring.getAlignment() == Alignment.BASELINE) {
int baseline = spring.getBaseline();
if (baseline >= 0) {
if (spring.isResizable(VERTICAL)) {
BaselineResizeBehavior brb = spring.
getBaselineResizeBehavior();
if (resizeBehavior == null) {
resizeBehavior = brb;
} else if (brb != resizeBehavior) {
resizeBehavior = BaselineResizeBehavior.
CONSTANT_ASCENT;
}
}
prefAscent = Math.max(prefAscent, baseline);
prefDescent = Math.max(prefDescent, spring.
getPreferredSize(VERTICAL) - baseline);
baselineSpringCount++;
}
}
}
if (!baselineAnchorSet) {
if (resizeBehavior == BaselineResizeBehavior.CONSTANT_DESCENT){
this.baselineAnchoredToTop = false;
} else {
this.baselineAnchoredToTop = true;
}
}
allSpringsHaveBaseline = (baselineSpringCount == springs.size());
calcedBaseline = true;
}
private int calculateMaxSize() {
int maxAscent = prefAscent;
int maxDescent = prefDescent;
int nonBaselineMax = 0;
for (Spring spring : springs) {
int baseline;
int springMax = spring.getMaximumSize(VERTICAL);
if ((spring.getAlignment() == null ||
spring.getAlignment() == Alignment.BASELINE) &&
(baseline = spring.getBaseline()) >= 0) {
int springPref = spring.getPreferredSize(VERTICAL);
if (springPref != springMax) {
switch (spring.getBaselineResizeBehavior()) {
case CONSTANT_ASCENT:
if (baselineAnchoredToTop) {
maxDescent = Math.max(maxDescent,
springMax - baseline);
}
break;
case CONSTANT_DESCENT:
if (!baselineAnchoredToTop) {
maxAscent = Math.max(maxAscent,
springMax - springPref + baseline);
}
break;
default: // CENTER_OFFSET and OTHER, not resizable
break;
}
}
} else {
// Not aligned along the baseline, or no baseline.
nonBaselineMax = Math.max(nonBaselineMax, springMax);
}
}
return Math.max(nonBaselineMax, maxAscent + maxDescent);
}
private int calculateMinSize() {
int minAscent = 0;
int minDescent = 0;
int nonBaselineMin = 0;
if (baselineAnchoredToTop) {
minAscent = prefAscent;
} else {
minDescent = prefDescent;
}
for (Spring spring : springs) {
int springMin = spring.getMinimumSize(VERTICAL);
int baseline;
if ((spring.getAlignment() == null ||
spring.getAlignment() == Alignment.BASELINE) &&
(baseline = spring.getBaseline()) >= 0) {
int springPref = spring.getPreferredSize(VERTICAL);
BaselineResizeBehavior brb = spring.
getBaselineResizeBehavior();
switch (brb) {
case CONSTANT_ASCENT:
if (baselineAnchoredToTop) {
minDescent = Math.max(springMin - baseline,
minDescent);
} else {
minAscent = Math.max(baseline, minAscent);
}
break;
case CONSTANT_DESCENT:
if (!baselineAnchoredToTop) {
minAscent = Math.max(
baseline - (springPref - springMin),
minAscent);
} else {
minDescent = Math.max(springPref - baseline,
minDescent);
}
break;
default:
// CENTER_OFFSET and OTHER are !resizable, use
// the preferred size.
minAscent = Math.max(baseline, minAscent);
minDescent = Math.max(springPref - baseline,
minDescent);
break;
}
} else {
// Not aligned along the baseline, or no baseline.
nonBaselineMin = Math.max(nonBaselineMin, springMin);
}
}
return Math.max(nonBaselineMin, minAscent + minDescent);
}
/** {@collect.stats}
* Lays out springs that have a baseline along the baseline. All
* others are centered.
*/
private void baselineLayout(int origin, int size) {
int ascent;
int descent;
if (baselineAnchoredToTop) {
ascent = prefAscent;
descent = size - ascent;
} else {
ascent = size - prefDescent;
descent = prefDescent;
}
for (Spring spring : springs) {
Alignment alignment = spring.getAlignment();
if (alignment == null || alignment == Alignment.BASELINE) {
int baseline = spring.getBaseline();
if (baseline >= 0) {
int springMax = spring.getMaximumSize(VERTICAL);
int springPref = spring.getPreferredSize(VERTICAL);
int height = springPref;
int y;
switch(spring.getBaselineResizeBehavior()) {
case CONSTANT_ASCENT:
y = origin + ascent - baseline;
height = Math.min(descent, springMax -
baseline) + baseline;
break;
case CONSTANT_DESCENT:
height = Math.min(ascent, springMax -
springPref + baseline) +
(springPref - baseline);
y = origin + ascent +
(springPref - baseline) - height;
break;
default: // CENTER_OFFSET & OTHER, not resizable
y = origin + ascent - baseline;
break;
}
spring.setSize(VERTICAL, y, height);
} else {
setChildSize(spring, VERTICAL, origin, size);
}
} else {
setChildSize(spring, VERTICAL, origin, size);
}
}
}
int getBaseline() {
if (springs.size() > 1) {
// Force the baseline to be calculated
getPreferredSize(VERTICAL);
return prefAscent;
} else if (springs.size() == 1) {
return springs.get(0).getBaseline();
}
return -1;
}
BaselineResizeBehavior getBaselineResizeBehavior() {
if (springs.size() == 1) {
return springs.get(0).getBaselineResizeBehavior();
}
if (baselineAnchoredToTop) {
return BaselineResizeBehavior.CONSTANT_ASCENT;
}
return BaselineResizeBehavior.CONSTANT_DESCENT;
}
// If the axis is VERTICAL, throws an IllegalStateException
private void checkAxis(int axis) {
if (axis == HORIZONTAL) {
throw new IllegalStateException(
"Baseline must be used along vertical axis");
}
}
}
private final class ComponentSpring extends Spring {
private Component component;
private int origin;
// min/pref/max are either a value >= 0 or one of
// DEFAULT_SIZE or PREFERRED_SIZE
private final int min;
private final int pref;
private final int max;
// Baseline for the component, computed as necessary.
private int baseline = -1;
// Whether or not the size has been requested yet.
private boolean installed;
private ComponentSpring(Component component, int min, int pref,
int max) {
this.component = component;
if (component == null) {
throw new IllegalArgumentException(
"Component must be non-null");
}
checkSize(min, pref, max, true);
this.min = min;
this.max = max;
this.pref = pref;
// getComponentInfo makes sure component is a child of the
// Container GroupLayout is the LayoutManager for.
getComponentInfo(component);
}
int calculateMinimumSize(int axis) {
if (isLinked(axis)) {
return getLinkSize(axis, MIN_SIZE);
}
return calculateNonlinkedMinimumSize(axis);
}
int calculatePreferredSize(int axis) {
if (isLinked(axis)) {
return getLinkSize(axis, PREF_SIZE);
}
int min = getMinimumSize(axis);
int pref = calculateNonlinkedPreferredSize(axis);
int max = getMaximumSize(axis);
return Math.min(max, Math.max(min, pref));
}
int calculateMaximumSize(int axis) {
if (isLinked(axis)) {
return getLinkSize(axis, MAX_SIZE);
}
return Math.max(getMinimumSize(axis),
calculateNonlinkedMaximumSize(axis));
}
boolean isVisible() {
return getComponentInfo(getComponent()).isVisible();
}
int calculateNonlinkedMinimumSize(int axis) {
if (!isVisible()) {
return 0;
}
if (min >= 0) {
return min;
}
if (min == PREFERRED_SIZE) {
return calculateNonlinkedPreferredSize(axis);
}
assert (min == DEFAULT_SIZE);
return getSizeAlongAxis(axis, component.getMinimumSize());
}
int calculateNonlinkedPreferredSize(int axis) {
if (!isVisible()) {
return 0;
}
if (pref >= 0) {
return pref;
}
assert (pref == DEFAULT_SIZE || pref == PREFERRED_SIZE);
return getSizeAlongAxis(axis, component.getPreferredSize());
}
int calculateNonlinkedMaximumSize(int axis) {
if (!isVisible()) {
return 0;
}
if (max >= 0) {
return max;
}
if (max == PREFERRED_SIZE) {
return calculateNonlinkedPreferredSize(axis);
}
assert (max == DEFAULT_SIZE);
return getSizeAlongAxis(axis, component.getMaximumSize());
}
private int getSizeAlongAxis(int axis, Dimension size) {
return (axis == HORIZONTAL) ? size.width : size.height;
}
private int getLinkSize(int axis, int type) {
if (!isVisible()) {
return 0;
}
ComponentInfo ci = getComponentInfo(component);
return ci.getLinkSize(axis, type);
}
void setSize(int axis, int origin, int size) {
super.setSize(axis, origin, size);
this.origin = origin;
if (size == UNSET) {
baseline = -1;
}
}
int getOrigin() {
return origin;
}
void setComponent(Component component) {
this.component = component;
}
Component getComponent() {
return component;
}
int getBaseline() {
if (baseline == -1) {
Spring horizontalSpring = getComponentInfo(component).
horizontalSpring;
int width = horizontalSpring.getPreferredSize(HORIZONTAL);
int height = getPreferredSize(VERTICAL);
if (width > 0 && height > 0) {
baseline = component.getBaseline(width, height);
}
}
return baseline;
}
BaselineResizeBehavior getBaselineResizeBehavior() {
return getComponent().getBaselineResizeBehavior();
}
private boolean isLinked(int axis) {
return getComponentInfo(component).isLinked(axis);
}
void installIfNecessary(int axis) {
if (!installed) {
installed = true;
if (axis == HORIZONTAL) {
getComponentInfo(component).horizontalSpring = this;
} else {
getComponentInfo(component).verticalSpring = this;
}
}
}
@Override
boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized) {
return !isVisible();
}
}
/** {@collect.stats}
* Spring representing the preferred distance between two components.
*/
private class PreferredGapSpring extends Spring {
private final JComponent source;
private final JComponent target;
private final ComponentPlacement type;
private final int pref;
private final int max;
PreferredGapSpring(JComponent source, JComponent target,
ComponentPlacement type, int pref, int max) {
this.source = source;
this.target = target;
this.type = type;
this.pref = pref;
this.max = max;
}
int calculateMinimumSize(int axis) {
return getPadding(axis);
}
int calculatePreferredSize(int axis) {
if (pref == DEFAULT_SIZE || pref == PREFERRED_SIZE) {
return getMinimumSize(axis);
}
int min = getMinimumSize(axis);
int max = getMaximumSize(axis);
return Math.min(max, Math.max(min, pref));
}
int calculateMaximumSize(int axis) {
if (max == PREFERRED_SIZE || max == DEFAULT_SIZE) {
return getPadding(axis);
}
return Math.max(getMinimumSize(axis), max);
}
private int getPadding(int axis) {
int position;
if (axis == HORIZONTAL) {
position = SwingConstants.EAST;
} else {
position = SwingConstants.SOUTH;
}
return getLayoutStyle0().getPreferredGap(source,
target, type, position, host);
}
@Override
boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized) {
return false;
}
}
/** {@collect.stats}
* Spring represented a certain amount of space.
*/
private class GapSpring extends Spring {
private final int min;
private final int pref;
private final int max;
GapSpring(int min, int pref, int max) {
checkSize(min, pref, max, false);
this.min = min;
this.pref = pref;
this.max = max;
}
int calculateMinimumSize(int axis) {
if (min == PREFERRED_SIZE) {
return getPreferredSize(axis);
}
return min;
}
int calculatePreferredSize(int axis) {
return pref;
}
int calculateMaximumSize(int axis) {
if (max == PREFERRED_SIZE) {
return getPreferredSize(axis);
}
return max;
}
@Override
boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized) {
return false;
}
}
/** {@collect.stats}
* Spring reprensenting the distance between any number of sources and
* targets. The targets and sources are computed during layout. An
* instance of this can either be dynamically created when
* autocreatePadding is true, or explicitly created by the developer.
*/
private class AutoPreferredGapSpring extends Spring {
List<ComponentSpring> sources;
ComponentSpring source;
private List<AutoPreferredGapMatch> matches;
int size;
int lastSize;
private final int pref;
private final int max;
// Type of gap
private ComponentPlacement type;
private boolean userCreated;
private AutoPreferredGapSpring() {
this.pref = PREFERRED_SIZE;
this.max = PREFERRED_SIZE;
this.type = ComponentPlacement.RELATED;
}
AutoPreferredGapSpring(int pref, int max) {
this.pref = pref;
this.max = max;
}
AutoPreferredGapSpring(ComponentPlacement type, int pref, int max) {
this.type = type;
this.pref = pref;
this.max = max;
this.userCreated = true;
}
public void setSource(ComponentSpring source) {
this.source = source;
}
public void setSources(List<ComponentSpring> sources) {
this.sources = new ArrayList<ComponentSpring>(sources);
}
public void setUserCreated(boolean userCreated) {
this.userCreated = userCreated;
}
public boolean getUserCreated() {
return userCreated;
}
void unset() {
lastSize = getSize();
super.unset();
size = 0;
}
public void reset() {
size = 0;
sources = null;
source = null;
matches = null;
}
public void calculatePadding(int axis) {
size = UNSET;
int maxPadding = UNSET;
if (matches != null) {
LayoutStyle p = getLayoutStyle0();
int position;
if (axis == HORIZONTAL) {
if (isLeftToRight()) {
position = SwingConstants.EAST;
} else {
position = SwingConstants.WEST;
}
} else {
position = SwingConstants.SOUTH;
}
for (int i = matches.size() - 1; i >= 0; i--) {
AutoPreferredGapMatch match = matches.get(i);
maxPadding = Math.max(maxPadding,
calculatePadding(p, position, match.source,
match.target));
}
}
if (size == UNSET) {
size = 0;
}
if (maxPadding == UNSET) {
maxPadding = 0;
}
if (lastSize != UNSET) {
size += Math.min(maxPadding, lastSize);
}
}
private int calculatePadding(LayoutStyle p, int position,
ComponentSpring source,
ComponentSpring target) {
int delta = target.getOrigin() - (source.getOrigin() +
source.getSize());
if (delta >= 0) {
int padding;
if ((source.getComponent() instanceof JComponent) &&
(target.getComponent() instanceof JComponent)) {
padding = p.getPreferredGap(
(JComponent)source.getComponent(),
(JComponent)target.getComponent(), type, position,
host);
} else {
padding = 10;
}
if (padding > delta) {
size = Math.max(size, padding - delta);
}
return padding;
}
return 0;
}
public void addTarget(ComponentSpring spring, int axis) {
int oAxis = (axis == HORIZONTAL) ? VERTICAL : HORIZONTAL;
if (source != null) {
if (areParallelSiblings(source.getComponent(),
spring.getComponent(), oAxis)) {
addValidTarget(source, spring);
}
} else {
Component component = spring.getComponent();
for (int counter = sources.size() - 1; counter >= 0;
counter--){
ComponentSpring source = sources.get(counter);
if (areParallelSiblings(source.getComponent(),
component, oAxis)) {
addValidTarget(source, spring);
}
}
}
}
private void addValidTarget(ComponentSpring source,
ComponentSpring target) {
if (matches == null) {
matches = new ArrayList<AutoPreferredGapMatch>(1);
}
matches.add(new AutoPreferredGapMatch(source, target));
}
int calculateMinimumSize(int axis) {
return size;
}
int calculatePreferredSize(int axis) {
if (pref == PREFERRED_SIZE || pref == DEFAULT_SIZE) {
return size;
}
return Math.max(size, pref);
}
int calculateMaximumSize(int axis) {
if (max >= 0) {
return Math.max(getPreferredSize(axis), max);
}
return size;
}
String getMatchDescription() {
return (matches == null) ? "" : matches.toString();
}
public String toString() {
return super.toString() + getMatchDescription();
}
@Override
boolean willHaveZeroSize(boolean treatAutopaddingAsZeroSized) {
return treatAutopaddingAsZeroSized;
}
}
/** {@collect.stats}
* Represents two springs that should have autopadding inserted between
* them.
*/
private final static class AutoPreferredGapMatch {
public final ComponentSpring source;
public final ComponentSpring target;
AutoPreferredGapMatch(ComponentSpring source, ComponentSpring target) {
this.source = source;
this.target = target;
}
private String toString(ComponentSpring spring) {
return spring.getComponent().getName();
}
public String toString() {
return "[" + toString(source) + "-" + toString(target) + "]";
}
}
/** {@collect.stats}
* An extension of AutopaddingSpring used for container level padding.
*/
private class ContainerAutoPreferredGapSpring extends
AutoPreferredGapSpring {
private List<ComponentSpring> targets;
ContainerAutoPreferredGapSpring() {
super();
setUserCreated(true);
}
ContainerAutoPreferredGapSpring(int pref, int max) {
super(pref, max);
setUserCreated(true);
}
public void addTarget(ComponentSpring spring, int axis) {
if (targets == null) {
targets = new ArrayList<ComponentSpring>(1);
}
targets.add(spring);
}
public void calculatePadding(int axis) {
LayoutStyle p = getLayoutStyle0();
int maxPadding = 0;
int position;
size = 0;
if (targets != null) {
// Leading
if (axis == HORIZONTAL) {
if (isLeftToRight()) {
position = SwingConstants.WEST;
} else {
position = SwingConstants.EAST;
}
} else {
position = SwingConstants.SOUTH;
}
for (int i = targets.size() - 1; i >= 0; i--) {
ComponentSpring targetSpring = targets.get(i);
int padding = 10;
if (targetSpring.getComponent() instanceof JComponent) {
padding = p.getContainerGap(
(JComponent)targetSpring.getComponent(),
position, host);
maxPadding = Math.max(padding, maxPadding);
padding -= targetSpring.getOrigin();
} else {
maxPadding = Math.max(padding, maxPadding);
}
size = Math.max(size, padding);
}
} else {
// Trailing
if (axis == HORIZONTAL) {
if (isLeftToRight()) {
position = SwingConstants.EAST;
} else {
position = SwingConstants.WEST;
}
} else {
position = SwingConstants.SOUTH;
}
if (sources != null) {
for (int i = sources.size() - 1; i >= 0; i--) {
ComponentSpring sourceSpring = sources.get(i);
maxPadding = Math.max(maxPadding,
updateSize(p, sourceSpring, position));
}
} else if (source != null) {
maxPadding = updateSize(p, source, position);
}
}
if (lastSize != UNSET) {
size += Math.min(maxPadding, lastSize);
}
}
private int updateSize(LayoutStyle p, ComponentSpring sourceSpring,
int position) {
int padding = 10;
if (sourceSpring.getComponent() instanceof JComponent) {
padding = p.getContainerGap(
(JComponent)sourceSpring.getComponent(), position,
host);
}
int delta = Math.max(0, getParent().getSize() -
sourceSpring.getSize() - sourceSpring.getOrigin());
size = Math.max(size, padding - delta);
return padding;
}
String getMatchDescription() {
if (targets != null) {
return "leading: " + targets.toString();
}
if (sources != null) {
return "trailing: " + sources.toString();
}
return "--";
}
}
// LinkInfo contains the set of ComponentInfosthat are linked along a
// particular axis.
private static class LinkInfo {
private final int axis;
private final List<ComponentInfo> linked;
private int size;
LinkInfo(int axis) {
linked = new ArrayList<ComponentInfo>();
size = UNSET;
this.axis = axis;
}
public void add(ComponentInfo child) {
LinkInfo childMaster = child.getLinkInfo(axis, false);
if (childMaster == null) {
linked.add(child);
child.setLinkInfo(axis, this);
} else if (childMaster != this) {
linked.addAll(childMaster.linked);
for (ComponentInfo childInfo : childMaster.linked) {
childInfo.setLinkInfo(axis, this);
}
}
clearCachedSize();
}
public void remove(ComponentInfo info) {
linked.remove(info);
info.setLinkInfo(axis, null);
if (linked.size() == 1) {
linked.get(0).setLinkInfo(axis, null);
}
clearCachedSize();
}
public void clearCachedSize() {
size = UNSET;
}
public int getSize(int axis) {
if (size == UNSET) {
size = calculateLinkedSize(axis);
}
return size;
}
private int calculateLinkedSize(int axis) {
int size = 0;
for (ComponentInfo info : linked) {
ComponentSpring spring;
if (axis == HORIZONTAL) {
spring = info.horizontalSpring;
} else {
assert (axis == VERTICAL);
spring = info.verticalSpring;
}
size = Math.max(size,
spring.calculateNonlinkedPreferredSize(axis));
}
return size;
}
}
/** {@collect.stats}
* Tracks the horizontal/vertical Springs for a Component.
* This class is also used to handle Springs that have their sizes
* linked.
*/
private class ComponentInfo {
// Component being layed out
private Component component;
ComponentSpring horizontalSpring;
ComponentSpring verticalSpring;
// If the component's size is linked to other components, the
// horizontalMaster and/or verticalMaster reference the group of
// linked components.
private LinkInfo horizontalMaster;
private LinkInfo verticalMaster;
private boolean visible;
private Boolean honorsVisibility;
ComponentInfo(Component component) {
this.component = component;
updateVisibility();
}
public void dispose() {
// Remove horizontal/vertical springs
removeSpring(horizontalSpring);
horizontalSpring = null;
removeSpring(verticalSpring);
verticalSpring = null;
// Clean up links
if (horizontalMaster != null) {
horizontalMaster.remove(this);
}
if (verticalMaster != null) {
verticalMaster.remove(this);
}
}
void setHonorsVisibility(Boolean honorsVisibility) {
this.honorsVisibility = honorsVisibility;
}
private void removeSpring(Spring spring) {
if (spring != null) {
((Group)spring.getParent()).springs.remove(spring);
}
}
public boolean isVisible() {
return visible;
}
/** {@collect.stats}
* Updates the cached visibility.
*
* @return true if the visibility changed
*/
boolean updateVisibility() {
boolean honorsVisibility;
if (this.honorsVisibility == null) {
honorsVisibility = GroupLayout.this.getHonorsVisibility();
} else {
honorsVisibility = this.honorsVisibility;
}
boolean newVisible = (honorsVisibility) ?
component.isVisible() : true;
if (visible != newVisible) {
visible = newVisible;
return true;
}
return false;
}
public void setBounds(Insets insets, int parentWidth, boolean ltr) {
int x = horizontalSpring.getOrigin();
int w = horizontalSpring.getSize();
int y = verticalSpring.getOrigin();
int h = verticalSpring.getSize();
if (!ltr) {
x = parentWidth - x - w;
}
component.setBounds(x + insets.left, y + insets.top, w, h);
}
public void setComponent(Component component) {
this.component = component;
if (horizontalSpring != null) {
horizontalSpring.setComponent(component);
}
if (verticalSpring != null) {
verticalSpring.setComponent(component);
}
}
public Component getComponent() {
return component;
}
/** {@collect.stats}
* Returns true if this component has its size linked to
* other components.
*/
public boolean isLinked(int axis) {
if (axis == HORIZONTAL) {
return horizontalMaster != null;
}
assert (axis == VERTICAL);
return (verticalMaster != null);
}
private void setLinkInfo(int axis, LinkInfo linkInfo) {
if (axis == HORIZONTAL) {
horizontalMaster = linkInfo;
} else {
assert (axis == VERTICAL);
verticalMaster = linkInfo;
}
}
public LinkInfo getLinkInfo(int axis) {
return getLinkInfo(axis, true);
}
private LinkInfo getLinkInfo(int axis, boolean create) {
if (axis == HORIZONTAL) {
if (horizontalMaster == null && create) {
// horizontalMaster field is directly set by adding
// us to the LinkInfo.
new LinkInfo(HORIZONTAL).add(this);
}
return horizontalMaster;
} else {
assert (axis == VERTICAL);
if (verticalMaster == null && create) {
// verticalMaster field is directly set by adding
// us to the LinkInfo.
new LinkInfo(VERTICAL).add(this);
}
return verticalMaster;
}
}
public void clearCachedSize() {
if (horizontalMaster != null) {
horizontalMaster.clearCachedSize();
}
if (verticalMaster != null) {
verticalMaster.clearCachedSize();
}
}
int getLinkSize(int axis, int type) {
if (axis == HORIZONTAL) {
return horizontalMaster.getSize(axis);
} else {
assert (axis == VERTICAL);
return verticalMaster.getSize(axis);
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.io.Serializable;
import java.awt.Component;
import java.awt.Adjustable;
import java.awt.Dimension;
import java.awt.event.AdjustmentListener;
import java.awt.event.AdjustmentEvent;
import java.awt.Graphics;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* An implementation of a scrollbar. The user positions the knob in the
* scrollbar to determine the contents of the viewing area. The
* program typically adjusts the display so that the end of the
* scrollbar represents the end of the displayable contents, or 100%
* of the contents. The start of the scrollbar is the beginning of the
* displayable contents, or 0%. The position of the knob within
* those bounds then translates to the corresponding percentage of
* the displayable contents.
* <p>
* Typically, as the position of the knob in the scrollbar changes
* a corresponding change is made to the position of the JViewport on
* the underlying view, changing the contents of the JViewport.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JScrollPane
* @beaninfo
* attribute: isContainer false
* description: A component that helps determine the visible content range of an area.
*
* @author David Kloba
*/
public class JScrollBar extends JComponent implements Adjustable, Accessible
{
/** {@collect.stats}
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ScrollBarUI";
/** {@collect.stats}
* All changes from the model are treated as though the user moved
* the scrollbar knob.
*/
private ChangeListener fwdAdjustmentEvents = new ModelListener();
/** {@collect.stats}
* The model that represents the scrollbar's minimum, maximum, extent
* (aka "visibleAmount") and current value.
* @see #setModel
*/
protected BoundedRangeModel model;
/** {@collect.stats}
* @see #setOrientation
*/
protected int orientation;
/** {@collect.stats}
* @see #setUnitIncrement
*/
protected int unitIncrement;
/** {@collect.stats}
* @see #setBlockIncrement
*/
protected int blockIncrement;
private void checkOrientation(int orientation) {
switch (orientation) {
case VERTICAL:
case HORIZONTAL:
break;
default:
throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
}
}
/** {@collect.stats}
* Creates a scrollbar with the specified orientation,
* value, extent, minimum, and maximum.
* The "extent" is the size of the viewable area. It is also known
* as the "visible amount".
* <p>
* Note: Use <code>setBlockIncrement</code> to set the block
* increment to a size slightly smaller than the view's extent.
* That way, when the user jumps the knob to an adjacent position,
* one or two lines of the original contents remain in view.
*
* @exception IllegalArgumentException if orientation is not one of VERTICAL, HORIZONTAL
*
* @see #setOrientation
* @see #setValue
* @see #setVisibleAmount
* @see #setMinimum
* @see #setMaximum
*/
public JScrollBar(int orientation, int value, int extent, int min, int max)
{
checkOrientation(orientation);
this.unitIncrement = 1;
this.blockIncrement = (extent == 0) ? 1 : extent;
this.orientation = orientation;
this.model = new DefaultBoundedRangeModel(value, extent, min, max);
this.model.addChangeListener(fwdAdjustmentEvents);
setRequestFocusEnabled(false);
updateUI();
}
/** {@collect.stats}
* Creates a scrollbar with the specified orientation
* and the following initial values:
* <pre>
* minimum = 0
* maximum = 100
* value = 0
* extent = 10
* </pre>
*/
public JScrollBar(int orientation) {
this(orientation, 0, 10, 0, 100);
}
/** {@collect.stats}
* Creates a vertical scrollbar with the following initial values:
* <pre>
* minimum = 0
* maximum = 100
* value = 0
* extent = 10
* </pre>
*/
public JScrollBar() {
this(VERTICAL);
}
/** {@collect.stats}
* Sets the L&F object that renders this component.
*
* @param ui the <code>ScrollBarUI</code> L&F object
* @see UIDefaults#getUI
* @since 1.4
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel
*/
public void setUI(ScrollBarUI ui) {
super.setUI(ui);
}
/** {@collect.stats}
* Returns the delegate that implements the look and feel for
* this component.
*
* @see JComponent#setUI
*/
public ScrollBarUI getUI() {
return (ScrollBarUI)ui;
}
/** {@collect.stats}
* Overrides <code>JComponent.updateUI</code>.
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((ScrollBarUI)UIManager.getUI(this));
}
/** {@collect.stats}
* Returns the name of the LookAndFeel class for this component.
*
* @return "ScrollBarUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/** {@collect.stats}
* Returns the component's orientation (horizontal or vertical).
*
* @return VERTICAL or HORIZONTAL
* @see #setOrientation
* @see java.awt.Adjustable#getOrientation
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* Set the scrollbar's orientation to either VERTICAL or
* HORIZONTAL.
*
* @exception IllegalArgumentException if orientation is not one of VERTICAL, HORIZONTAL
* @see #getOrientation
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The scrollbar's orientation.
* enum: VERTICAL JScrollBar.VERTICAL
* HORIZONTAL JScrollBar.HORIZONTAL
*/
public void setOrientation(int orientation)
{
checkOrientation(orientation);
int oldValue = this.orientation;
this.orientation = orientation;
firePropertyChange("orientation", oldValue, orientation);
if ((oldValue != orientation) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldValue == VERTICAL)
? AccessibleState.VERTICAL : AccessibleState.HORIZONTAL),
((orientation == VERTICAL)
? AccessibleState.VERTICAL : AccessibleState.HORIZONTAL));
}
if (orientation != oldValue) {
revalidate();
}
}
/** {@collect.stats}
* Returns data model that handles the scrollbar's four
* fundamental properties: minimum, maximum, value, extent.
*
* @see #setModel
*/
public BoundedRangeModel getModel() {
return model;
}
/** {@collect.stats}
* Sets the model that handles the scrollbar's four
* fundamental properties: minimum, maximum, value, extent.
*
* @see #getModel
* @beaninfo
* bound: true
* expert: true
* description: The scrollbar's BoundedRangeModel.
*/
public void setModel(BoundedRangeModel newModel) {
Integer oldValue = null;
BoundedRangeModel oldModel = model;
if (model != null) {
model.removeChangeListener(fwdAdjustmentEvents);
oldValue = new Integer(model.getValue());
}
model = newModel;
if (model != null) {
model.addChangeListener(fwdAdjustmentEvents);
}
firePropertyChange("model", oldModel, model);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
oldValue, new Integer(model.getValue()));
}
}
/** {@collect.stats}
* Returns the amount to change the scrollbar's value by,
* given a unit up/down request. A ScrollBarUI implementation
* typically calls this method when the user clicks on a scrollbar
* up/down arrow and uses the result to update the scrollbar's
* value. Subclasses my override this method to compute
* a value, e.g. the change required to scroll up or down one
* (variable height) line text or one row in a table.
* <p>
* The JScrollPane component creates scrollbars (by default)
* that override this method and delegate to the viewports
* Scrollable view, if it has one. The Scrollable interface
* provides a more specialized version of this method.
*
* @param direction is -1 or 1 for up/down respectively
* @return the value of the unitIncrement property
* @see #setUnitIncrement
* @see #setValue
* @see Scrollable#getScrollableUnitIncrement
*/
public int getUnitIncrement(int direction) {
return unitIncrement;
}
/** {@collect.stats}
* Sets the unitIncrement property.
* <p>
* Note, that if the argument is equal to the value of Integer.MIN_VALUE,
* the most look and feels will not provide the scrolling to the right/down.
* @see #getUnitIncrement
* @beaninfo
* preferred: true
* bound: true
* description: The scrollbar's unit increment.
*/
public void setUnitIncrement(int unitIncrement) {
int oldValue = this.unitIncrement;
this.unitIncrement = unitIncrement;
firePropertyChange("unitIncrement", oldValue, unitIncrement);
}
/** {@collect.stats}
* Returns the amount to change the scrollbar's value by,
* given a block (usually "page") up/down request. A ScrollBarUI
* implementation typically calls this method when the user clicks
* above or below the scrollbar "knob" to change the value
* up or down by large amount. Subclasses my override this
* method to compute a value, e.g. the change required to scroll
* up or down one paragraph in a text document.
* <p>
* The JScrollPane component creates scrollbars (by default)
* that override this method and delegate to the viewports
* Scrollable view, if it has one. The Scrollable interface
* provides a more specialized version of this method.
*
* @param direction is -1 or 1 for up/down respectively
* @return the value of the blockIncrement property
* @see #setBlockIncrement
* @see #setValue
* @see Scrollable#getScrollableBlockIncrement
*/
public int getBlockIncrement(int direction) {
return blockIncrement;
}
/** {@collect.stats}
* Sets the blockIncrement property.
* <p>
* Note, that if the argument is equal to the value of Integer.MIN_VALUE,
* the most look and feels will not provide the scrolling to the right/down.
* @see #getBlockIncrement()
* @beaninfo
* preferred: true
* bound: true
* description: The scrollbar's block increment.
*/
public void setBlockIncrement(int blockIncrement) {
int oldValue = this.blockIncrement;
this.blockIncrement = blockIncrement;
firePropertyChange("blockIncrement", oldValue, blockIncrement);
}
/** {@collect.stats}
* For backwards compatibility with java.awt.Scrollbar.
* @see Adjustable#getUnitIncrement
* @see #getUnitIncrement(int)
*/
public int getUnitIncrement() {
return unitIncrement;
}
/** {@collect.stats}
* For backwards compatibility with java.awt.Scrollbar.
* @see Adjustable#getBlockIncrement
* @see #getBlockIncrement(int)
*/
public int getBlockIncrement() {
return blockIncrement;
}
/** {@collect.stats}
* Returns the scrollbar's value.
* @return the model's value property
* @see #setValue
*/
public int getValue() {
return getModel().getValue();
}
/** {@collect.stats}
* Sets the scrollbar's value. This method just forwards the value
* to the model.
*
* @see #getValue
* @see BoundedRangeModel#setValue
* @beaninfo
* preferred: true
* description: The scrollbar's current value.
*/
public void setValue(int value) {
BoundedRangeModel m = getModel();
int oldValue = m.getValue();
m.setValue(value);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(oldValue),
new Integer(m.getValue()));
}
}
/** {@collect.stats}
* Returns the scrollbar's extent, aka its "visibleAmount". In many
* scrollbar look and feel implementations the size of the
* scrollbar "knob" or "thumb" is proportional to the extent.
*
* @return the value of the model's extent property
* @see #setVisibleAmount
*/
public int getVisibleAmount() {
return getModel().getExtent();
}
/** {@collect.stats}
* Set the model's extent property.
*
* @see #getVisibleAmount
* @see BoundedRangeModel#setExtent
* @beaninfo
* preferred: true
* description: The amount of the view that is currently visible.
*/
public void setVisibleAmount(int extent) {
getModel().setExtent(extent);
}
/** {@collect.stats}
* Returns the minimum value supported by the scrollbar
* (usually zero).
*
* @return the value of the model's minimum property
* @see #setMinimum
*/
public int getMinimum() {
return getModel().getMinimum();
}
/** {@collect.stats}
* Sets the model's minimum property.
*
* @see #getMinimum
* @see BoundedRangeModel#setMinimum
* @beaninfo
* preferred: true
* description: The scrollbar's minimum value.
*/
public void setMinimum(int minimum) {
getModel().setMinimum(minimum);
}
/** {@collect.stats}
* The maximum value of the scrollbar is maximum - extent.
*
* @return the value of the model's maximum property
* @see #setMaximum
*/
public int getMaximum() {
return getModel().getMaximum();
}
/** {@collect.stats}
* Sets the model's maximum property. Note that the scrollbar's value
* can only be set to maximum - extent.
*
* @see #getMaximum
* @see BoundedRangeModel#setMaximum
* @beaninfo
* preferred: true
* description: The scrollbar's maximum value.
*/
public void setMaximum(int maximum) {
getModel().setMaximum(maximum);
}
/** {@collect.stats}
* True if the scrollbar knob is being dragged.
*
* @return the value of the model's valueIsAdjusting property
* @see #setValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return getModel().getValueIsAdjusting();
}
/** {@collect.stats}
* Sets the model's valueIsAdjusting property. Scrollbar look and
* feel implementations should set this property to true when
* a knob drag begins, and to false when the drag ends. The
* scrollbar model will not generate ChangeEvents while
* valueIsAdjusting is true.
*
* @see #getValueIsAdjusting
* @see BoundedRangeModel#setValueIsAdjusting
* @beaninfo
* expert: true
* description: True if the scrollbar thumb is being dragged.
*/
public void setValueIsAdjusting(boolean b) {
BoundedRangeModel m = getModel();
boolean oldValue = m.getValueIsAdjusting();
m.setValueIsAdjusting(b);
if ((oldValue != b) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldValue) ? AccessibleState.BUSY : null),
((b) ? AccessibleState.BUSY : null));
}
}
/** {@collect.stats}
* Sets the four BoundedRangeModel properties after forcing
* the arguments to obey the usual constraints:
* <pre>
* minimum <= value <= value+extent <= maximum
* </pre>
* <p>
*
* @see BoundedRangeModel#setRangeProperties
* @see #setValue
* @see #setVisibleAmount
* @see #setMinimum
* @see #setMaximum
*/
public void setValues(int newValue, int newExtent, int newMin, int newMax)
{
BoundedRangeModel m = getModel();
int oldValue = m.getValue();
m.setRangeProperties(newValue, newExtent, newMin, newMax, m.getValueIsAdjusting());
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
new Integer(oldValue),
new Integer(m.getValue()));
}
}
/** {@collect.stats}
* Adds an AdjustmentListener. Adjustment listeners are notified
* each time the scrollbar's model changes. Adjustment events are
* provided for backwards compatibility with java.awt.Scrollbar.
* <p>
* Note that the AdjustmentEvents type property will always have a
* placeholder value of AdjustmentEvent.TRACK because all changes
* to a BoundedRangeModels value are considered equivalent. To change
* the value of a BoundedRangeModel one just sets its value property,
* i.e. model.setValue(123). No information about the origin of the
* change, e.g. it's a block decrement, is provided. We don't try
* fabricate the origin of the change here.
*
* @param l the AdjustmentLister to add
* @see #removeAdjustmentListener
* @see BoundedRangeModel#addChangeListener
*/
public void addAdjustmentListener(AdjustmentListener l) {
listenerList.add(AdjustmentListener.class, l);
}
/** {@collect.stats}
* Removes an AdjustmentEvent listener.
*
* @param l the AdjustmentLister to remove
* @see #addAdjustmentListener
*/
public void removeAdjustmentListener(AdjustmentListener l) {
listenerList.remove(AdjustmentListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>AdjustmentListener</code>s added
* to this JScrollBar with addAdjustmentListener().
*
* @return all of the <code>AdjustmentListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public AdjustmentListener[] getAdjustmentListeners() {
return (AdjustmentListener[])listenerList.getListeners(
AdjustmentListener.class);
}
/** {@collect.stats}
* Notify listeners that the scrollbar's model has changed.
*
* @see #addAdjustmentListener
* @see EventListenerList
*/
protected void fireAdjustmentValueChanged(int id, int type, int value) {
fireAdjustmentValueChanged(id, type, value, getValueIsAdjusting());
}
/** {@collect.stats}
* Notify listeners that the scrollbar's model has changed.
*
* @see #addAdjustmentListener
* @see EventListenerList
*/
private void fireAdjustmentValueChanged(int id, int type, int value,
boolean isAdjusting) {
Object[] listeners = listenerList.getListenerList();
AdjustmentEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i]==AdjustmentListener.class) {
if (e == null) {
e = new AdjustmentEvent(this, id, type, value, isAdjusting);
}
((AdjustmentListener)listeners[i+1]).adjustmentValueChanged(e);
}
}
}
/** {@collect.stats}
* This class listens to ChangeEvents on the model and forwards
* AdjustmentEvents for the sake of backwards compatibility.
* Unfortunately there's no way to determine the proper
* type of the AdjustmentEvent as all updates to the model's
* value are considered equivalent.
*/
private class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
Object obj = e.getSource();
if (obj instanceof BoundedRangeModel) {
int id = AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED;
int type = AdjustmentEvent.TRACK;
BoundedRangeModel model = (BoundedRangeModel)obj;
int value = model.getValue();
boolean isAdjusting = model.getValueIsAdjusting();
fireAdjustmentValueChanged(id, type, value, isAdjusting);
}
}
}
// PENDING(hmuller) - the next three methods should be removed
/** {@collect.stats}
* The scrollbar is flexible along it's scrolling axis and
* rigid along the other axis.
*/
public Dimension getMinimumSize() {
Dimension pref = getPreferredSize();
if (orientation == VERTICAL) {
return new Dimension(pref.width, 5);
} else {
return new Dimension(5, pref.height);
}
}
/** {@collect.stats}
* The scrollbar is flexible along it's scrolling axis and
* rigid along the other axis.
*/
public Dimension getMaximumSize() {
Dimension pref = getPreferredSize();
if (getOrientation() == VERTICAL) {
return new Dimension(pref.width, Short.MAX_VALUE);
} else {
return new Dimension(Short.MAX_VALUE, pref.height);
}
}
/** {@collect.stats}
* Enables the component so that the knob position can be changed.
* When the disabled, the knob position cannot be changed.
*
* @param x a boolean value, where true enables the component and
* false disables it
*/
public void setEnabled(boolean x) {
super.setEnabled(x);
Component[] children = getComponents();
for(int i = 0; i < children.length; i++) {
children[i].setEnabled(x);
}
}
/** {@collect.stats}
* See readObject() and writeObject() in JComponent for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/** {@collect.stats}
* Returns a string representation of this JScrollBar. This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this JScrollBar.
*/
protected String paramString() {
String orientationString = (orientation == HORIZONTAL ?
"HORIZONTAL" : "VERTICAL");
return super.paramString() +
",blockIncrement=" + blockIncrement +
",orientation=" + orientationString +
",unitIncrement=" + unitIncrement;
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this JScrollBar.
* For JScrollBar, the AccessibleContext takes the form of an
* AccessibleJScrollBar.
* A new AccessibleJScrollBar instance is created if necessary.
*
* @return an AccessibleJScrollBar that serves as the
* AccessibleContext of this JScrollBar
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJScrollBar();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>JScrollBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to scroll bar user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJScrollBar extends AccessibleJComponent
implements AccessibleValue {
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getValueIsAdjusting()) {
states.add(AccessibleState.BUSY);
}
if (getOrientation() == VERTICAL) {
states.add(AccessibleState.VERTICAL);
} else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SCROLL_BAR;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Get the accessible value of this object.
*
* @return The current value of this object.
*/
public Number getCurrentAccessibleValue() {
return new Integer(getValue());
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
// TIGER - 4422535
if (n == null) {
return false;
}
setValue(n.intValue());
return true;
}
/** {@collect.stats}
* Get the minimum accessible value of this object.
*
* @return The minimum value of this object.
*/
public Number getMinimumAccessibleValue() {
return new Integer(getMinimum());
}
/** {@collect.stats}
* Get the maximum accessible value of this object.
*
* @return The maximum value of this object.
*/
public Number getMaximumAccessibleValue() {
// TIGER - 4422362
return new Integer(model.getMaximum() - model.getExtent());
}
} // AccessibleJScrollBar
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import java.awt.*;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.event.*;
/** {@collect.stats}
* This is the abstract superclass for color choosers. If you want to add
* a new color chooser panel into a <code>JColorChooser</code>, subclass
* this class.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Tom Santos
* @author Steve Wilson
*/
public abstract class AbstractColorChooserPanel extends JPanel {
/** {@collect.stats}
*
*/
private JColorChooser chooser;
/** {@collect.stats}
*
*/
private ChangeListener colorListener;
/** {@collect.stats}
*
*/
private boolean dirty = true;
/** {@collect.stats}
* Invoked automatically when the model's state changes.
* It is also called by <code>installChooserPanel</code> to allow
* you to set up the initial state of your chooser.
* Override this method to update your <code>ChooserPanel</code>.
*/
public abstract void updateChooser();
/** {@collect.stats}
* Builds a new chooser panel.
*/
protected abstract void buildChooser();
/** {@collect.stats}
* Returns a string containing the display name of the panel.
* @return the name of the display panel
*/
public abstract String getDisplayName();
/** {@collect.stats}
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation returns 0, indicating the
* <code>AbstractColorChooserPanel</code> does not support a mnemonic,
* subclasses wishing a mnemonic will need to override this.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return 0;
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation returns -1, indicating the
* <code>AbstractColorChooserPanel</code> does not support a mnemonic,
* subclasses wishing a mnemonic will need to override this.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return -1;
}
/** {@collect.stats}
* Returns the small display icon for the panel.
* @return the small display icon
*/
public abstract Icon getSmallDisplayIcon();
/** {@collect.stats}
* Returns the large display icon for the panel.
* @return the large display icon
*/
public abstract Icon getLargeDisplayIcon();
/** {@collect.stats}
* Invoked when the panel is added to the chooser.
* If you override this, be sure to call <code>super</code>.
* @param enclosingChooser the panel to be added
* @exception RuntimeException if the chooser panel has already been
* installed
*/
public void installChooserPanel(JColorChooser enclosingChooser) {
if (chooser != null) {
throw new RuntimeException ("This chooser panel is already installed");
}
chooser = enclosingChooser;
buildChooser();
updateChooser();
colorListener = new ModelListener();
getColorSelectionModel().addChangeListener(colorListener);
}
/** {@collect.stats}
* Invoked when the panel is removed from the chooser.
* If override this, be sure to call <code>super</code>.
*/
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
getColorSelectionModel().removeChangeListener(colorListener);
chooser = null;
}
/** {@collect.stats}
* Returns the model that the chooser panel is editing.
* @return the <code>ColorSelectionModel</code> model this panel
* is editing
*/
public ColorSelectionModel getColorSelectionModel() {
return chooser.getSelectionModel();
}
/** {@collect.stats}
* Returns the color that is currently selected.
* @return the <code>Color</code> that is selected
*/
protected Color getColorFromModel() {
return getColorSelectionModel().getSelectedColor();
}
/** {@collect.stats}
* Draws the panel.
* @param g the <code>Graphics</code> object
*/
public void paint(Graphics g) {
if (dirty) {
updateChooser();
dirty = false;
}
super.paint(g);
}
/** {@collect.stats}
* Returns an integer from the defaults table. If <code>key</code> does
* not map to a valid <code>Integer</code>, <code>default</code> is
* returned.
*
* @param key an <code>Object</code> specifying the int
* @param defaultValue Returned value if <code>key</code> is not available,
* or is not an Integer
* @return the int
*/
static int getInt(Object key, int defaultValue) {
Object value = UIManager.get(key);
if (value instanceof Integer) {
return ((Integer)value).intValue();
}
if (value instanceof String) {
try {
return Integer.parseInt((String)value);
} catch (NumberFormatException nfe) {}
}
return defaultValue;
}
/** {@collect.stats}
*
*/
class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
if (isShowing()) { // isVisible
updateChooser();
dirty = false;
} else {
dirty = true;
}
}
}
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import java.awt.*;
import java.io.*;
/** {@collect.stats}
* Center-positioning layout manager.
* @author Tom Santos
* @author Steve Wilson
*/
class CenterLayout implements LayoutManager, Serializable {
public void addLayoutComponent(String name, Component comp) { }
public void removeLayoutComponent(Component comp) { }
public Dimension preferredLayoutSize( Container container ) {
Component c = container.getComponent( 0 );
if ( c != null ) {
Dimension size = c.getPreferredSize();
Insets insets = container.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
else {
return new Dimension( 0, 0 );
}
}
public Dimension minimumLayoutSize(Container cont) {
return preferredLayoutSize(cont);
}
public void layoutContainer(Container container) {
try {
Component c = container.getComponent( 0 );
c.setSize( c.getPreferredSize() );
Dimension size = c.getSize();
Dimension containerSize = container.getSize();
Insets containerInsets = container.getInsets();
containerSize.width -= containerInsets.left + containerInsets.right;
containerSize.height -= containerInsets.top + containerInsets.bottom;
int componentLeft = (containerSize.width / 2) - (size.width / 2);
int componentTop = (containerSize.height / 2) - (size.height / 2);
componentLeft += containerInsets.left;
componentTop += containerInsets.top;
c.setBounds( componentLeft, componentTop, size.width, size.height );
}
catch( Exception e ) {
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.io.Serializable;
/** {@collect.stats}
* A better GridLayout class
*
* @author Steve Wilson
*/
class SmartGridLayout implements LayoutManager, Serializable {
int rows = 2;
int columns = 2;
int xGap = 2;
int yGap = 2;
int componentCount = 0;
Component[][] layoutGrid;
public SmartGridLayout(int numColumns, int numRows) {
rows = numRows;
columns = numColumns;
layoutGrid = new Component[numColumns][numRows];
}
public void layoutContainer(Container c) {
buildLayoutGrid(c);
int[] rowHeights = new int[rows];
int[] columnWidths = new int[columns];
for (int row = 0; row < rows; row++) {
rowHeights[row] = computeRowHeight(row);
}
for (int column = 0; column < columns; column++) {
columnWidths[column] = computeColumnWidth(column);
}
Insets insets = c.getInsets();
if (c.getComponentOrientation().isLeftToRight()) {
int horizLoc = insets.left;
for (int column = 0; column < columns; column++) {
int vertLoc = insets.top;
for (int row = 0; row < rows; row++) {
Component current = layoutGrid[column][row];
current.setBounds(horizLoc, vertLoc, columnWidths[column], rowHeights[row]);
// System.out.println(current.getBounds());
vertLoc += (rowHeights[row] + yGap);
}
horizLoc += (columnWidths[column] + xGap );
}
} else {
int horizLoc = c.getWidth() - insets.right;
for (int column = 0; column < columns; column++) {
int vertLoc = insets.top;
horizLoc -= columnWidths[column];
for (int row = 0; row < rows; row++) {
Component current = layoutGrid[column][row];
current.setBounds(horizLoc, vertLoc, columnWidths[column], rowHeights[row]);
// System.out.println(current.getBounds());
vertLoc += (rowHeights[row] + yGap);
}
horizLoc -= xGap;
}
}
}
public Dimension minimumLayoutSize(Container c) {
buildLayoutGrid(c);
Insets insets = c.getInsets();
int height = 0;
int width = 0;
for (int row = 0; row < rows; row++) {
height += computeRowHeight(row);
}
for (int column = 0; column < columns; column++) {
width += computeColumnWidth(column);
}
height += (yGap * (rows - 1)) + insets.top + insets.bottom;
width += (xGap * (columns - 1)) + insets.right + insets.left;
return new Dimension(width, height);
}
public Dimension preferredLayoutSize(Container c) {
return minimumLayoutSize(c);
}
public void addLayoutComponent(String s, Component c) {}
public void removeLayoutComponent(Component c) {}
private void buildLayoutGrid(Container c) {
Component[] children = c.getComponents();
for (int componentCount = 0; componentCount < children.length; componentCount++) {
// System.out.println("Children: " +componentCount);
int row = 0;
int column = 0;
if (componentCount != 0) {
column = componentCount % columns;
row = (componentCount - column) / columns;
}
// System.out.println("inserting into: "+ column + " " + row);
layoutGrid[column][row] = children[componentCount];
}
}
private int computeColumnWidth(int columnNum) {
int maxWidth = 1;
for (int row = 0; row < rows; row++) {
int width = layoutGrid[columnNum][row].getPreferredSize().width;
if (width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
private int computeRowHeight(int rowNum) {
int maxHeight = 1;
for (int column = 0; column < columns; column++) {
int height = layoutGrid[column][rowNum].getPreferredSize().height;
if (height > maxHeight) {
maxHeight = height;
}
}
return maxHeight;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import sun.swing.SwingUtilities2;
/** {@collect.stats}
* The standard preview panel for the color chooser.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Steve Wilson
* @see JColorChooser
*/
class DefaultPreviewPanel extends JPanel {
private int squareSize = 25;
private int squareGap = 5;
private int innerGap = 5;
private int textGap = 5;
private Font font = new Font(Font.DIALOG, Font.PLAIN, 12);
private String sampleText = UIManager.getString("ColorChooser.sampleText");
private int swatchWidth = 50;
private Color oldColor = null;
private JColorChooser getColorChooser() {
return (JColorChooser)SwingUtilities.getAncestorOfClass(
JColorChooser.class, this);
}
public Dimension getPreferredSize() {
JComponent host = getColorChooser();
if (host == null) {
host = this;
}
FontMetrics fm = host.getFontMetrics(getFont());
int ascent = fm.getAscent();
int height = fm.getHeight();
int width = SwingUtilities2.stringWidth(host, fm, sampleText);
int y = height*3 + textGap*3;
int x = squareSize * 3 + squareGap*2 + swatchWidth + width + textGap*3;
return new Dimension( x,y );
}
public void paintComponent(Graphics g) {
if (oldColor == null)
oldColor = getForeground();
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
if (this.getComponentOrientation().isLeftToRight()) {
int squareWidth = paintSquares(g, 0);
int textWidth = paintText(g, squareWidth);
paintSwatch(g, squareWidth + textWidth);
} else {
int swatchWidth = paintSwatch(g, 0);
int textWidth = paintText(g, swatchWidth);
paintSquares(g , swatchWidth + textWidth);
}
}
private int paintSwatch(Graphics g, int offsetX) {
int swatchX = offsetX;
g.setColor(oldColor);
g.fillRect(swatchX, 0, swatchWidth, (squareSize) + (squareGap/2));
g.setColor(getForeground());
g.fillRect(swatchX, (squareSize) + (squareGap/2), swatchWidth, (squareSize) + (squareGap/2) );
return (swatchX+swatchWidth);
}
private int paintText(Graphics g, int offsetX) {
g.setFont(getFont());
JComponent host = getColorChooser();
if (host == null) {
host = this;
}
FontMetrics fm = SwingUtilities2.getFontMetrics(host, g);
int ascent = fm.getAscent();
int height = fm.getHeight();
int width = SwingUtilities2.stringWidth(host, fm, sampleText);
int textXOffset = offsetX + textGap;
Color color = getForeground();
g.setColor(color);
SwingUtilities2.drawString(host, g, sampleText,textXOffset+(textGap/2),
ascent+2);
g.fillRect(textXOffset,
( height) + textGap,
width + (textGap),
height +2);
g.setColor(Color.black);
SwingUtilities2.drawString(host, g, sampleText,
textXOffset+(textGap/2),
height+ascent+textGap+2);
g.setColor(Color.white);
g.fillRect(textXOffset,
( height + textGap) * 2,
width + (textGap),
height +2);
g.setColor(color);
SwingUtilities2.drawString(host, g, sampleText,
textXOffset+(textGap/2),
((height+textGap) * 2)+ascent+2);
return width + textGap*3;
}
private int paintSquares(Graphics g, int offsetX) {
int squareXOffset = offsetX;
Color color = getForeground();
g.setColor(Color.white);
g.fillRect(squareXOffset,0,squareSize,squareSize);
g.setColor(color);
g.fillRect(squareXOffset+innerGap,
innerGap,
squareSize - (innerGap*2),
squareSize - (innerGap*2));
g.setColor(Color.white);
g.fillRect(squareXOffset+innerGap*2,
innerGap*2,
squareSize - (innerGap*4),
squareSize - (innerGap*4));
g.setColor(color);
g.fillRect(squareXOffset,squareSize+squareGap,squareSize,squareSize);
g.translate(squareSize+squareGap, 0);
g.setColor(Color.black);
g.fillRect(squareXOffset,0,squareSize,squareSize);
g.setColor(color);
g.fillRect(squareXOffset+innerGap,
innerGap,
squareSize - (innerGap*2),
squareSize - (innerGap*2));
g.setColor(Color.white);
g.fillRect(squareXOffset+innerGap*2,
innerGap*2,
squareSize - (innerGap*4),
squareSize - (innerGap*4));
g.translate(-(squareSize+squareGap), 0);
g.translate(squareSize+squareGap, squareSize+squareGap);
g.setColor(Color.white);
g.fillRect(squareXOffset,0,squareSize,squareSize);
g.setColor(color);
g.fillRect(squareXOffset+innerGap,
innerGap,
squareSize - (innerGap*2),
squareSize - (innerGap*2));
g.translate(-(squareSize+squareGap), -(squareSize+squareGap));
g.translate((squareSize+squareGap)*2, 0);
g.setColor(Color.white);
g.fillRect(squareXOffset,0,squareSize,squareSize);
g.setColor(color);
g.fillRect(squareXOffset+innerGap,
innerGap,
squareSize - (innerGap*2),
squareSize - (innerGap*2));
g.setColor(Color.black);
g.fillRect(squareXOffset+innerGap*2,
innerGap*2,
squareSize - (innerGap*4),
squareSize - (innerGap*4));
g.translate(-((squareSize+squareGap)*2), 0);
g.translate((squareSize+squareGap)*2, (squareSize+squareGap));
g.setColor(Color.black);
g.fillRect(squareXOffset,0,squareSize,squareSize);
g.setColor(color);
g.fillRect(squareXOffset+innerGap,
innerGap,
squareSize - (innerGap*2),
squareSize - (innerGap*2));
g.translate(-((squareSize+squareGap)*2), -(squareSize+squareGap));
return (squareSize*3+squareGap*2);
}
}
|
Java
|
/*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import java.awt.*;
import java.awt.image.*;
/** {@collect.stats} A helper class to make computing synthetic images a little easier.
* All you need to do is define a subclass that overrides computeRow
* to compute a row of the image. It is passed the y coordinate of the
* row and an array into which to put the pixels in
* <a href="http://java.sun.com/products/jdk/1.1/docs/api/java.awt.image.ColorModel.html#getRGBdefault()">
* standard ARGB format</a>.
* <p>Normal usage looks something like this:
* <pre> Image i = createImage(new SyntheticImage(200, 100) {
* protected void computeRow(int y, int[] row) {
* for(int i = width; --i>=0; ) {
* int grey = i*255/(width-1);
* row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
* }
* }
* }
* </pre>This creates a image 200 pixels wide and 100 pixels high
* that is a horizontal grey ramp, going from black on the left to
* white on the right.
* <p>
* If the image is to be a movie, override isStatic to return false,
* <i>y</i> cycling back to 0 is computeRow's signal that the next
* frame has started. It is acceptable (expected?) for computeRow(0,r)
* to pause until the appropriate time to start the next frame.
*
* @author James Gosling
*/
abstract class SyntheticImage implements ImageProducer {
private SyntheticImageGenerator root;
protected int width=10, height=100;
static final ColorModel cm = ColorModel.getRGBdefault();
public static final int pixMask = 0xFF;
private Thread runner;
protected SyntheticImage() { }
protected SyntheticImage(int w, int h) { width = w; height = h; }
protected void computeRow(int y, int[] row) {
int p = 255-255*y/(height-1);
p = (pixMask<<24)|(p<<16)|(p<<8)|p;
for (int i = row.length; --i>=0; ) row[i] = p;
}
public synchronized void addConsumer(ImageConsumer ic){
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.ic == ic) return;
root = new SyntheticImageGenerator(ic, root, this);
}
public synchronized boolean isConsumer(ImageConsumer ic){
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.ic == ic) return true;
return false;
}
public synchronized void removeConsumer(ImageConsumer ic) {
SyntheticImageGenerator prev = null;
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) {
if (ics.ic == ic) {
ics.useful = false;
if (prev!=null) prev.next = ics.next;
else root = ics.next;
return;
}
prev = ics;
}
}
public synchronized void startProduction(ImageConsumer ic) {
addConsumer(ic);
for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next)
if (ics.useful && !ics.isAlive())
ics.start();
}
protected boolean isStatic() { return true; }
public void nextFrame(int param) {}//Override if !isStatic
public void requestTopDownLeftRightResend(ImageConsumer ic){}
protected volatile boolean aborted = false;
}
class SyntheticImageGenerator extends Thread {
ImageConsumer ic;
boolean useful;
SyntheticImageGenerator next;
SyntheticImage parent;
SyntheticImageGenerator(ImageConsumer ic, SyntheticImageGenerator next,
SyntheticImage parent) {
super("SyntheticImageGenerator");
this.ic = ic;
this.next = next;
this.parent = parent;
useful = true;
setDaemon(true);
}
public void run() {
ImageConsumer ic = this.ic;
int w = parent.width;
int h = parent.height;
int hints = ic.SINGLEPASS|ic.COMPLETESCANLINES|ic.TOPDOWNLEFTRIGHT;
if (parent.isStatic())
hints |= ic.SINGLEFRAME;
ic.setHints(hints);
ic.setDimensions(w, h);
ic.setProperties(null);
ic.setColorModel(parent.cm);
if (useful) {
int[] row=new int[w];
doPrivileged( new Runnable() {
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
}
});
do {
for (int y = 0; y<h && useful; y++) {
parent.computeRow(y,row);
if (parent.aborted) {
ic.imageComplete(ic.IMAGEABORTED);
return;
}
ic.setPixels(0, y, w, 1, parent.cm, row, 0, w);
}
ic.imageComplete(parent.isStatic() ? ic.STATICIMAGEDONE
: ic.SINGLEFRAMEDONE );
} while(!parent.isStatic() && useful);
}
}
private final static void doPrivileged(final Runnable doRun) {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
doRun.run();
return null;
}
}
);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Color;
import java.io.Serializable;
/** {@collect.stats}
* A generic implementation of <code>ColorSelectionModel</code>.
*
* @author Steve Wilson
*
* @see java.awt.Color
*/
public class DefaultColorSelectionModel implements ColorSelectionModel, Serializable {
/** {@collect.stats}
* Only one <code>ChangeEvent</code> is needed per model instance
* since the event's only (read-only) state is the source property.
* The source of events generated here is always "this".
*/
protected transient ChangeEvent changeEvent = null;
protected EventListenerList listenerList = new EventListenerList();
private Color selectedColor;
/** {@collect.stats}
* Creates a <code>DefaultColorSelectionModel</code> with the
* current color set to <code>Color.white</code>. This is
* the default constructor.
*/
public DefaultColorSelectionModel() {
selectedColor = Color.white;
}
/** {@collect.stats}
* Creates a <code>DefaultColorSelectionModel</code> with the
* current color set to <code>color</code>, which should be
* non-<code>null</code>. Note that setting the color to
* <code>null</code> is undefined and may have unpredictable
* results.
*
* @param color the new <code>Color</code>
*/
public DefaultColorSelectionModel(Color color) {
selectedColor = color;
}
/** {@collect.stats}
* Returns the selected <code>Color</code> which should be
* non-<code>null</code>.
*
* @return the selected <code>Color</code>
*/
public Color getSelectedColor() {
return selectedColor;
}
/** {@collect.stats}
* Sets the selected color to <code>color</code>.
* Note that setting the color to <code>null</code>
* is undefined and may have unpredictable results.
* This method fires a state changed event if it sets the
* current color to a new non-<code>null</code> color;
* if the new color is the same as the current color,
* no event is fired.
*
* @param color the new <code>Color</code>
*/
public void setSelectedColor(Color color) {
if (color != null && !selectedColor.equals(color)) {
selectedColor = color;
fireStateChanged();
}
}
/** {@collect.stats}
* Adds a <code>ChangeListener</code> to the model.
*
* @param l the <code>ChangeListener</code> to be added
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/** {@collect.stats}
* Removes a <code>ChangeListener</code> from the model.
* @param l the <code>ChangeListener</code> to be removed
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>ChangeListener</code>s added
* to this <code>DefaultColorSelectionModel</code> with
* <code>addChangeListener</code>.
*
* @return all of the <code>ChangeListener</code>s added, or an empty
* array if no listeners have been added
* @since 1.4
*/
public ChangeListener[] getChangeListeners() {
return (ChangeListener[])listenerList.getListeners(
ChangeListener.class);
}
/** {@collect.stats}
* Runs each <code>ChangeListener</code>'s
* <code>stateChanged</code> method.
*
* <!-- @see #setRangeProperties //bad link-->
* @see EventListenerList
*/
protected void fireStateChanged()
{
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -=2 ) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.image.*;
/** {@collect.stats}
* Implements the default HSB Color chooser
*
* @author Tom Santos
* @author Steve Wilson
* @author Mark Davidson
* @author Shannon Hickey
*/
class DefaultHSBChooserPanel extends AbstractColorChooserPanel implements ChangeListener, HierarchyListener {
private transient HSBImage palette;
private transient HSBImage sliderPalette;
private transient Image paletteImage;
private transient Image sliderPaletteImage;
private JSlider slider;
private JSpinner hField;
private JSpinner sField;
private JSpinner bField;
private JTextField redField;
private JTextField greenField;
private JTextField blueField;
private boolean isAdjusting = false; // Flag which indicates that values are set internally
private Point paletteSelection = new Point();
private JLabel paletteLabel;
private JLabel sliderPaletteLabel;
private JRadioButton hRadio;
private JRadioButton sRadio;
private JRadioButton bRadio;
private static final int PALETTE_DIMENSION = 200;
private static final int MAX_HUE_VALUE = 359;
private static final int MAX_SATURATION_VALUE = 100;
private static final int MAX_BRIGHTNESS_VALUE = 100;
private int currentMode = HUE_MODE;
private static final int HUE_MODE = 0;
private static final int SATURATION_MODE = 1;
private static final int BRIGHTNESS_MODE = 2;
public DefaultHSBChooserPanel() {
}
private void addPaletteListeners() {
paletteLabel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e ) {
float[] hsb = new float[3];
palette.getHSBForLocation( e.getX(), e.getY(), hsb );
updateHSB( hsb[0], hsb[1], hsb[2] );
}
});
paletteLabel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e ){
int labelWidth = paletteLabel.getWidth();
int labelHeight = paletteLabel.getHeight();
int x = e.getX();
int y = e.getY();
if ( x >= labelWidth ) {
x = labelWidth - 1;
}
if ( y >= labelHeight ) {
y = labelHeight - 1;
}
if ( x < 0 ) {
x = 0;
}
if ( y < 0 ) {
y = 0;
}
float[] hsb = new float[3];
palette.getHSBForLocation( x, y, hsb );
updateHSB( hsb[0], hsb[1], hsb[2] );
}
});
}
private void updatePalette( float h, float s, float b ) {
int x = 0;
int y = 0;
switch ( currentMode ) {
case HUE_MODE:
if ( h != palette.getHue() ) {
palette.setHue( h );
palette.nextFrame();
}
x = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
break;
case SATURATION_MODE:
if ( s != palette.getSaturation() ) {
palette.setSaturation( s );
palette.nextFrame();
}
x = (int)(h * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
break;
case BRIGHTNESS_MODE:
if ( b != palette.getBrightness() ) {
palette.setBrightness( b );
palette.nextFrame();
}
x = (int)(h * PALETTE_DIMENSION);
y = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
break;
}
paletteSelection.setLocation( x, y );
paletteLabel.repaint();
}
private void updateSlider( float h, float s, float b ) {
// Update the slider palette if necessary.
// When the slider is the hue slider or the hue hasn't changed,
// the hue of the palette will not need to be updated.
if (currentMode != HUE_MODE && h != sliderPalette.getHue() ) {
sliderPalette.setHue( h );
sliderPalette.nextFrame();
}
float value = 0f;
switch ( currentMode ) {
case HUE_MODE:
value = h;
break;
case SATURATION_MODE:
value = s;
break;
case BRIGHTNESS_MODE:
value = b;
break;
}
slider.setValue( Math.round(value * (slider.getMaximum())) );
}
private void updateHSBTextFields( float hue, float saturation, float brightness ) {
int h = Math.round(hue * 359);
int s = Math.round(saturation * 100);
int b = Math.round(brightness * 100);
if (((Integer)hField.getValue()).intValue() != h) {
hField.setValue(new Integer(h));
}
if (((Integer)sField.getValue()).intValue() != s) {
sField.setValue(new Integer(s));
}
if (((Integer)bField.getValue()).intValue() != b) {
bField.setValue(new Integer(b));
}
}
/** {@collect.stats}
* Updates the values of the RGB fields to reflect the new color change
*/
private void updateRGBTextFields( Color color ) {
redField.setText(String.valueOf(color.getRed()));
greenField.setText(String.valueOf(color.getGreen()));
blueField.setText(String.valueOf(color.getBlue()));
}
/** {@collect.stats}
* Main internal method of updating the ui controls and the color model.
*/
private void updateHSB( float h, float s, float b ) {
if ( !isAdjusting ) {
isAdjusting = true;
updatePalette( h, s, b );
updateSlider( h, s, b );
updateHSBTextFields( h, s, b );
Color color = Color.getHSBColor(h, s, b);
updateRGBTextFields( color );
getColorSelectionModel().setSelectedColor( color );
isAdjusting = false;
}
}
/** {@collect.stats}
* Invoked automatically when the model's state changes.
* It is also called by <code>installChooserPanel</code> to allow
* you to set up the initial state of your chooser.
* Override this method to update your <code>ChooserPanel</code>.
*/
public void updateChooser() {
if ( !isAdjusting ) {
float[] hsb = getHSBColorFromModel();
updateHSB( hsb[0], hsb[1], hsb[2] );
}
}
public void installChooserPanel(JColorChooser enclosingChooser) {
super.installChooserPanel(enclosingChooser);
setInheritsPopupMenu(true);
addHierarchyListener(this);
}
/** {@collect.stats}
* Invoked when the panel is removed from the chooser.
*/
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
super.uninstallChooserPanel(enclosingChooser);
cleanupPalettesIfNecessary();
removeAll();
removeHierarchyListener(this);
}
/** {@collect.stats}
* Returns an float array containing the HSB values of the selected color from
* the ColorSelectionModel
*/
private float[] getHSBColorFromModel() {
Color color = getColorFromModel();
float[] hsb = new float[3];
Color.RGBtoHSB( color.getRed(), color.getGreen(), color.getBlue(), hsb );
return hsb;
}
/** {@collect.stats}
* Builds a new chooser panel.
*/
protected void buildChooser() {
setLayout(new BorderLayout());
JComponent spp = buildSliderPalettePanel();
spp.setInheritsPopupMenu(true);
add(spp, BorderLayout.BEFORE_LINE_BEGINS);
JPanel controlHolder = new JPanel(new SmartGridLayout(1,3));
JComponent hsbControls = buildHSBControls();
hsbControls.setInheritsPopupMenu(true);
controlHolder.add(hsbControls);
controlHolder.add(new JLabel(" ")); // spacer
JComponent rgbControls = buildRGBControls();
rgbControls.setInheritsPopupMenu(true);
controlHolder.add(rgbControls);
controlHolder.setInheritsPopupMenu(true);
controlHolder.setBorder(new EmptyBorder( 10, 5, 10, 5));
add( controlHolder, BorderLayout.CENTER);
}
/** {@collect.stats}
* Creates the panel with the uneditable RGB field
*/
private JComponent buildRGBControls() {
JPanel panel = new JPanel(new SmartGridLayout(2,3));
panel.setInheritsPopupMenu(true);
Color color = getColorFromModel();
redField = new JTextField( String.valueOf(color.getRed()), 3 );
redField.setEditable(false);
redField.setHorizontalAlignment( JTextField.RIGHT );
redField.setInheritsPopupMenu(true);
greenField = new JTextField(String.valueOf(color.getGreen()), 3 );
greenField.setEditable(false);
greenField.setHorizontalAlignment( JTextField.RIGHT );
greenField.setInheritsPopupMenu(true);
blueField = new JTextField( String.valueOf(color.getBlue()), 3 );
blueField.setEditable(false);
blueField.setHorizontalAlignment( JTextField.RIGHT );
blueField.setInheritsPopupMenu(true);
String redString = UIManager.getString("ColorChooser.hsbRedText");
String greenString = UIManager.getString("ColorChooser.hsbGreenText");
String blueString = UIManager.getString("ColorChooser.hsbBlueText");
panel.add( new JLabel(redString) );
panel.add( redField );
panel.add( new JLabel(greenString) );
panel.add( greenField );
panel.add( new JLabel(blueString) );
panel.add( blueField );
return panel;
}
/** {@collect.stats}
* Creates the panel with the editable HSB fields and the radio buttons.
*/
private JComponent buildHSBControls() {
String hueString = UIManager.getString("ColorChooser.hsbHueText");
String saturationString = UIManager.getString("ColorChooser.hsbSaturationText");
String brightnessString = UIManager.getString("ColorChooser.hsbBrightnessText");
RadioButtonHandler handler = new RadioButtonHandler();
hRadio = new JRadioButton(hueString);
hRadio.addActionListener(handler);
hRadio.setSelected(true);
hRadio.setInheritsPopupMenu(true);
sRadio = new JRadioButton(saturationString);
sRadio.addActionListener(handler);
sRadio.setInheritsPopupMenu(true);
bRadio = new JRadioButton(brightnessString);
bRadio.addActionListener(handler);
bRadio.setInheritsPopupMenu(true);
ButtonGroup group = new ButtonGroup();
group.add(hRadio);
group.add(sRadio);
group.add(bRadio);
float[] hsb = getHSBColorFromModel();
hField = new JSpinner(new SpinnerNumberModel((int)(hsb[0] * 359), 0, 359, 1));
sField = new JSpinner(new SpinnerNumberModel((int)(hsb[1] * 100), 0, 100, 1));
bField = new JSpinner(new SpinnerNumberModel((int)(hsb[2] * 100), 0, 100, 1));
hField.addChangeListener(this);
sField.addChangeListener(this);
bField.addChangeListener(this);
hField.setInheritsPopupMenu(true);
sField.setInheritsPopupMenu(true);
bField.setInheritsPopupMenu(true);
JPanel panel = new JPanel( new SmartGridLayout(2, 3) );
panel.add(hRadio);
panel.add(hField);
panel.add(sRadio);
panel.add(sField);
panel.add(bRadio);
panel.add(bField);
panel.setInheritsPopupMenu(true);
return panel;
}
/** {@collect.stats}
* Handler for the radio button classes.
*/
private class RadioButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Object obj = evt.getSource();
if (obj instanceof JRadioButton) {
JRadioButton button = (JRadioButton)obj;
if (button == hRadio) {
setMode(HUE_MODE);
} else if (button == sRadio) {
setMode(SATURATION_MODE);
} else if (button == bRadio) {
setMode(BRIGHTNESS_MODE);
}
}
}
}
private void setMode(int mode) {
if (currentMode == mode) {
return;
}
isAdjusting = true; // Ensure no events propagate from changing slider value.
currentMode = mode;
float[] hsb = getHSBColorFromModel();
switch (currentMode) {
case HUE_MODE:
slider.setInverted(true);
slider.setMaximum(MAX_HUE_VALUE);
palette.setValues(HSBImage.HSQUARE, hsb[0], 1.0f, 1.0f);
sliderPalette.setValues(HSBImage.HSLIDER, 0f, 1.0f, 1.0f);
break;
case SATURATION_MODE:
slider.setInverted(false);
slider.setMaximum(MAX_SATURATION_VALUE);
palette.setValues(HSBImage.SSQUARE, hsb[0], hsb[1], 1.0f);
sliderPalette.setValues(HSBImage.SSLIDER, hsb[0], 1.0f, 1.0f);
break;
case BRIGHTNESS_MODE:
slider.setInverted(false);
slider.setMaximum(MAX_BRIGHTNESS_VALUE);
palette.setValues(HSBImage.BSQUARE, hsb[0], 1.0f, hsb[2]);
sliderPalette.setValues(HSBImage.BSLIDER, hsb[0], 1.0f, 1.0f);
break;
}
isAdjusting = false;
palette.nextFrame();
sliderPalette.nextFrame();
updateChooser();
}
protected JComponent buildSliderPalettePanel() {
// This slider has to have a minimum of 0. A lot of math in this file is simplified due to this.
slider = new JSlider(JSlider.VERTICAL, 0, MAX_HUE_VALUE, 0);
slider.setInverted(true);
slider.setPaintTrack(false);
slider.setPreferredSize(new Dimension(slider.getPreferredSize().width, PALETTE_DIMENSION + 15));
slider.addChangeListener(this);
slider.setInheritsPopupMenu(true);
// We're not painting ticks, but need to ask UI classes to
// paint arrow shape anyway, if possible.
slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE);
paletteLabel = createPaletteLabel();
addPaletteListeners();
sliderPaletteLabel = new JLabel();
JPanel panel = new JPanel();
panel.add( paletteLabel );
panel.add( slider );
panel.add( sliderPaletteLabel );
initializePalettesIfNecessary();
return panel;
}
private void initializePalettesIfNecessary() {
if (palette != null) {
return;
}
float[] hsb = getHSBColorFromModel();
switch(currentMode){
case HUE_MODE:
palette = new HSBImage(HSBImage.HSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, hsb[0], 1.0f, 1.0f);
sliderPalette = new HSBImage(HSBImage.HSLIDER, 16, PALETTE_DIMENSION, 0f, 1.0f, 1.0f);
break;
case SATURATION_MODE:
palette = new HSBImage(HSBImage.SSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, hsb[1], 1.0f);
sliderPalette = new HSBImage(HSBImage.SSLIDER, 16, PALETTE_DIMENSION, 1.0f, 0f, 1.0f);
break;
case BRIGHTNESS_MODE:
palette = new HSBImage(HSBImage.BSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, 1.0f, hsb[2]);
sliderPalette = new HSBImage(HSBImage.BSLIDER, 16, PALETTE_DIMENSION, 1.0f, 1.0f, 0f);
break;
}
paletteImage = Toolkit.getDefaultToolkit().createImage(palette);
sliderPaletteImage = Toolkit.getDefaultToolkit().createImage(sliderPalette);
paletteLabel.setIcon(new ImageIcon(paletteImage));
sliderPaletteLabel.setIcon(new ImageIcon(sliderPaletteImage));
}
private void cleanupPalettesIfNecessary() {
if (palette == null) {
return;
}
palette.aborted = true;
sliderPalette.aborted = true;
palette.nextFrame();
sliderPalette.nextFrame();
palette = null;
sliderPalette = null;
paletteImage = null;
sliderPaletteImage = null;
paletteLabel.setIcon(null);
sliderPaletteLabel.setIcon(null);
}
protected JLabel createPaletteLabel() {
return new JLabel() {
protected void paintComponent( Graphics g ) {
super.paintComponent( g );
g.setColor( Color.white );
g.drawOval( paletteSelection.x - 4, paletteSelection.y - 4, 8, 8 );
}
};
}
public String getDisplayName() {
return UIManager.getString("ColorChooser.hsbNameText");
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.hsbMnemonic</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbMnemonic");</code>.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return getInt("ColorChooser.hsbMnemonic", -1);
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbDisplayedMnemonicIndex</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.hsbDisplayedMnemonicIndex");</code>.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return getInt("ColorChooser.hsbDisplayedMnemonicIndex", -1);
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
/** {@collect.stats}
* Class for the slider and palette images.
*/
class HSBImage extends SyntheticImage {
protected float h = .0f;
protected float s = .0f;
protected float b = .0f;
protected float[] hsb = new float[3];
protected boolean isDirty = true;
protected int cachedY;
protected int cachedColor;
protected int type;
private static final int HSQUARE = 0;
private static final int SSQUARE = 1;
private static final int BSQUARE = 2;
private static final int HSLIDER = 3;
private static final int SSLIDER = 4;
private static final int BSLIDER = 5;
protected HSBImage(int type, int width, int height, float h, float s, float b) {
super(width, height);
setValues(type, h, s, b);
}
public void setValues(int type, float h, float s, float b) {
this.type = type;
cachedY = -1;
cachedColor = 0;
setHue( h );
setSaturation( s );
setBrightness( b );
}
public final void setHue( float hue ) {
h = hue;
}
public final void setSaturation( float saturation ) {
s = saturation;
}
public final void setBrightness( float brightness ) {
b = brightness;
}
public final float getHue() {
return h;
}
public final float getSaturation() {
return s;
}
public final float getBrightness() {
return b;
}
protected boolean isStatic() {
return false;
}
public synchronized void nextFrame() {
isDirty = true;
notifyAll();
}
public synchronized void addConsumer(ImageConsumer ic) {
isDirty = true;
super.addConsumer(ic);
}
private int getRGBForLocation( int x, int y ) {
if (type >= HSLIDER && y == cachedY) {
return cachedColor;
}
getHSBForLocation( x, y, hsb );
cachedY = y;
cachedColor = Color.HSBtoRGB( hsb[0], hsb[1], hsb[2] );
return cachedColor;
}
public void getHSBForLocation( int x, int y, float[] hsbArray ) {
switch (type) {
case HSQUARE: {
float saturationStep = ((float)x) / width;
float brightnessStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s - saturationStep;
hsbArray[2] = b - brightnessStep;
break;
}
case SSQUARE: {
float brightnessStep = ((float)y) / height;
float step = 1.0f / ((float)width);
hsbArray[0] = x * step;
hsbArray[1] = s;
hsbArray[2] = 1.0f - brightnessStep;
break;
}
case BSQUARE: {
float saturationStep = ((float)y) / height;
float step = 1.0f / ((float)width);
hsbArray[0] = x * step;
hsbArray[1] = 1.0f - saturationStep;
hsbArray[2] = b;
break;
}
case HSLIDER: {
float step = 1.0f / ((float)height);
hsbArray[0] = y * step;
hsbArray[1] = s;
hsbArray[2] = b;
break;
}
case SSLIDER: {
float saturationStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s - saturationStep;
hsbArray[2] = b;
break;
}
case BSLIDER: {
float brightnessStep = ((float)y) / height;
hsbArray[0] = h;
hsbArray[1] = s;
hsbArray[2] = b - brightnessStep;
break;
}
}
}
/** {@collect.stats}
* Overriden method from SyntheticImage
*/
protected void computeRow( int y, int[] row ) {
if ( y == 0 ) {
synchronized ( this ) {
try {
while ( !isDirty ) {
wait();
}
} catch (InterruptedException ie) {
}
isDirty = false;
}
}
if (aborted) {
return;
}
for ( int i = 0; i < row.length; ++i ) {
row[i] = getRGBForLocation( i, y );
}
}
}
public void stateChanged(ChangeEvent e) {
if (e.getSource() == slider) {
boolean modelIsAdjusting = slider.getModel().getValueIsAdjusting();
if (!modelIsAdjusting && !isAdjusting) {
int sliderValue = slider.getValue();
int sliderRange = slider.getMaximum();
float value = (float)sliderValue / (float)sliderRange;
float[] hsb = getHSBColorFromModel();
switch ( currentMode ){
case HUE_MODE:
updateHSB(value, hsb[1], hsb[2]);
break;
case SATURATION_MODE:
updateHSB(hsb[0], value, hsb[2]);
break;
case BRIGHTNESS_MODE:
updateHSB(hsb[0], hsb[1], value);
break;
}
}
} else if (e.getSource() instanceof JSpinner) {
float hue = ((Integer)hField.getValue()).floatValue() / 359f;
float saturation = ((Integer)sField.getValue()).floatValue() / 100f;
float brightness = ((Integer)bField.getValue()).floatValue() / 100f;
updateHSB(hue, saturation, brightness);
}
}
public void hierarchyChanged(HierarchyEvent he) {
if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (isDisplayable()) {
initializePalettesIfNecessary();
} else {
cleanupPalettesIfNecessary();
}
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
/** {@collect.stats}
* The standard RGB chooser.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Steve Wilson
* @author Mark Davidson
* @see JColorChooser
* @see AbstractColorChooserPanel
*/
class DefaultRGBChooserPanel extends AbstractColorChooserPanel implements ChangeListener {
protected JSlider redSlider;
protected JSlider greenSlider;
protected JSlider blueSlider;
protected JSpinner redField;
protected JSpinner blueField;
protected JSpinner greenField;
private final int minValue = 0;
private final int maxValue = 255;
private boolean isAdjusting = false; // indicates the fields are being set internally
public DefaultRGBChooserPanel() {
super();
setInheritsPopupMenu(true);
}
/** {@collect.stats}
* Sets the values of the controls to reflect the color
*/
private void setColor( Color newColor ) {
int red = newColor.getRed();
int blue = newColor.getBlue();
int green = newColor.getGreen();
if (redSlider.getValue() != red) {
redSlider.setValue(red);
}
if (greenSlider.getValue() != green) {
greenSlider.setValue(green);
}
if (blueSlider.getValue() != blue) {
blueSlider.setValue(blue);
}
if (((Integer)redField.getValue()).intValue() != red)
redField.setValue(new Integer(red));
if (((Integer)greenField.getValue()).intValue() != green)
greenField.setValue(new Integer(green));
if (((Integer)blueField.getValue()).intValue() != blue )
blueField.setValue(new Integer(blue));
}
public String getDisplayName() {
return UIManager.getString("ColorChooser.rgbNameText");
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbMnemonic</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbMnemonic");</code>.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return getInt("ColorChooser.rgbMnemonic", -1);
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbDisplayedMnemonicIndex</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.rgbDisplayedMnemonicIndex");</code>.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return getInt("ColorChooser.rgbDisplayedMnemonicIndex", -1);
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
/** {@collect.stats}
* The background color, foreground color, and font are already set to the
* defaults from the defaults table before this method is called.
*/
public void installChooserPanel(JColorChooser enclosingChooser) {
super.installChooserPanel(enclosingChooser);
}
protected void buildChooser() {
String redString = UIManager.getString("ColorChooser.rgbRedText");
String greenString = UIManager.getString("ColorChooser.rgbGreenText");
String blueString = UIManager.getString("ColorChooser.rgbBlueText");
setLayout( new BorderLayout() );
Color color = getColorFromModel();
JPanel enclosure = new JPanel();
enclosure.setLayout( new SmartGridLayout( 3, 3 ) );
enclosure.setInheritsPopupMenu(true);
// The panel that holds the sliders
add( enclosure, BorderLayout.CENTER );
// sliderPanel.setBorder(new LineBorder(Color.black));
// The row for the red value
JLabel l = new JLabel(redString);
l.setDisplayedMnemonic(AbstractColorChooserPanel.getInt("ColorChooser.rgbRedMnemonic", -1));
enclosure.add(l);
redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getRed());
redSlider.setMajorTickSpacing( 85 );
redSlider.setMinorTickSpacing( 17 );
redSlider.setPaintTicks( true );
redSlider.setPaintLabels( true );
redSlider.setInheritsPopupMenu(true);
enclosure.add( redSlider );
redField = new JSpinner(
new SpinnerNumberModel(color.getRed(), minValue, maxValue, 1));
l.setLabelFor(redSlider);
redField.setInheritsPopupMenu(true);
JPanel redFieldHolder = new JPanel(new CenterLayout());
redFieldHolder.setInheritsPopupMenu(true);
redField.addChangeListener(this);
redFieldHolder.add(redField);
enclosure.add(redFieldHolder);
// The row for the green value
l = new JLabel(greenString);
l.setDisplayedMnemonic(AbstractColorChooserPanel.getInt("ColorChooser.rgbGreenMnemonic", -1));
enclosure.add(l);
greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getGreen());
greenSlider.setMajorTickSpacing( 85 );
greenSlider.setMinorTickSpacing( 17 );
greenSlider.setPaintTicks( true );
greenSlider.setPaintLabels( true );
greenSlider.setInheritsPopupMenu(true);
enclosure.add(greenSlider);
greenField = new JSpinner(
new SpinnerNumberModel(color.getGreen(), minValue, maxValue, 1));
l.setLabelFor(greenSlider);
greenField.setInheritsPopupMenu(true);
JPanel greenFieldHolder = new JPanel(new CenterLayout());
greenFieldHolder.add(greenField);
greenFieldHolder.setInheritsPopupMenu(true);
greenField.addChangeListener(this);
enclosure.add(greenFieldHolder);
// The slider for the blue value
l = new JLabel(blueString);
l.setDisplayedMnemonic(AbstractColorChooserPanel.getInt("ColorChooser.rgbBlueMnemonic", -1));
enclosure.add(l);
blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getBlue());
blueSlider.setMajorTickSpacing( 85 );
blueSlider.setMinorTickSpacing( 17 );
blueSlider.setPaintTicks( true );
blueSlider.setPaintLabels( true );
blueSlider.setInheritsPopupMenu(true);
enclosure.add(blueSlider);
blueField = new JSpinner(
new SpinnerNumberModel(color.getBlue(), minValue, maxValue, 1));
l.setLabelFor(blueSlider);
blueField.setInheritsPopupMenu(true);
JPanel blueFieldHolder = new JPanel(new CenterLayout());
blueFieldHolder.add(blueField);
blueField.addChangeListener(this);
blueFieldHolder.setInheritsPopupMenu(true);
enclosure.add(blueFieldHolder);
redSlider.addChangeListener( this );
greenSlider.addChangeListener( this );
blueSlider.addChangeListener( this );
redSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
greenSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
blueSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
}
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
super.uninstallChooserPanel(enclosingChooser);
removeAll();
}
public void updateChooser() {
if (!isAdjusting) {
isAdjusting = true;
setColor(getColorFromModel());
isAdjusting = false;
}
}
public void stateChanged( ChangeEvent e ) {
if ( e.getSource() instanceof JSlider && !isAdjusting) {
int red = redSlider.getValue();
int green = greenSlider.getValue();
int blue = blueSlider.getValue() ;
Color color = new Color (red, green, blue);
getColorSelectionModel().setSelectedColor(color);
} else if (e.getSource() instanceof JSpinner && !isAdjusting) {
int red = ((Integer)redField.getValue()).intValue();
int green = ((Integer)greenField.getValue()).intValue();
int blue = ((Integer)blueField.getValue()).intValue();
Color color = new Color (red, green, blue);
getColorSelectionModel().setSelectedColor(color);
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Color;
/** {@collect.stats}
* A model that supports selecting a <code>Color</code>.
*
* @author Steve Wilson
*
* @see java.awt.Color
*/
public interface ColorSelectionModel {
/** {@collect.stats}
* Returns the selected <code>Color</code> which should be
* non-<code>null</code>.
*
* @return the selected <code>Color</code>
* @see #setSelectedColor
*/
Color getSelectedColor();
/** {@collect.stats}
* Sets the selected color to <code>color</code>.
* Note that setting the color to <code>null</code>
* is undefined and may have unpredictable results.
* This method fires a state changed event if it sets the
* current color to a new non-<code>null</code> color.
*
* @param color the new <code>Color</code>
* @see #getSelectedColor
* @see #addChangeListener
*/
void setSelectedColor(Color color);
/** {@collect.stats}
* Adds <code>listener</code> as a listener to changes in the model.
* @param listener the <code>ChangeListener</code> to be added
*/
void addChangeListener(ChangeListener listener);
/** {@collect.stats}
* Removes <code>listener</code> as a listener to changes in the model.
* @param listener the <code>ChangeListener</code> to be removed
*/
void removeChangeListener(ChangeListener listener);
}
|
Java
|
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
/** {@collect.stats}
* A class designed to produce preconfigured "accessory" objects to
* insert into color choosers.
*
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Steve Wilson
*/
public class ColorChooserComponentFactory {
private ColorChooserComponentFactory() { } // can't instantiate
public static AbstractColorChooserPanel[] getDefaultChooserPanels() {
AbstractColorChooserPanel[] choosers = { new DefaultSwatchChooserPanel(),
new DefaultHSBChooserPanel(),
new DefaultRGBChooserPanel() };
return choosers;
}
public static JComponent getPreviewPanel() {
return new DefaultPreviewPanel();
}
}
|
Java
|
/*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.colorchooser;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import javax.accessibility.*;
/** {@collect.stats}
* The standard color swatch chooser.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Steve Wilson
*/
class DefaultSwatchChooserPanel extends AbstractColorChooserPanel {
SwatchPanel swatchPanel;
RecentSwatchPanel recentSwatchPanel;
MouseListener mainSwatchListener;
MouseListener recentSwatchListener;
private static String recentStr = UIManager.getString("ColorChooser.swatchesRecentText");
public DefaultSwatchChooserPanel() {
super();
setInheritsPopupMenu(true);
}
public String getDisplayName() {
return UIManager.getString("ColorChooser.swatchesNameText");
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the
* <code>KeyEvent.VK</code> constant that can be used as a mnemonic to
* access the panel. A return value <= 0 indicates there is no mnemonic.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.swatchesMnemonic</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.swatchesMnemonic");</code>.
*
* @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no
* mnemonic
* @see #getDisplayedMnemonicIndex
* @since 1.4
*/
public int getMnemonic() {
return getInt("ColorChooser.swatchesMnemonic", -1);
}
/** {@collect.stats}
* Provides a hint to the look and feel as to the index of the character in
* <code>getDisplayName</code> that should be visually identified as the
* mnemonic. The look and feel should only use this if
* <code>getMnemonic</code> returns a value > 0.
* <p>
* The return value here is a hint, it is ultimately up to the look
* and feel to honor the return value in some meaningful way. For example,
* a look and feel may wish to render each
* <code>AbstractColorChooserPanel</code> in a <code>JTabbedPane</code>,
* and further use this return value to underline a character in
* the <code>getDisplayName</code>.
* <p>
* This implementation looks up the value from the default
* <code>ColorChooser.rgbDisplayedMnemonicIndex</code>, or if it
* isn't available (or not an <code>Integer</code>) returns -1.
* The lookup for the default is done through the <code>UIManager</code>:
* <code>UIManager.get("ColorChooser.swatchesDisplayedMnemonicIndex");</code>.
*
* @return Character index to render mnemonic for; -1 to provide no
* visual identifier for this panel.
* @see #getMnemonic
* @since 1.4
*/
public int getDisplayedMnemonicIndex() {
return getInt("ColorChooser.swatchesDisplayedMnemonicIndex", -1);
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
/** {@collect.stats}
* The background color, foreground color, and font are already set to the
* defaults from the defaults table before this method is called.
*/
public void installChooserPanel(JColorChooser enclosingChooser) {
super.installChooserPanel(enclosingChooser);
}
protected void buildChooser() {
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel superHolder = new JPanel(gb);
swatchPanel = new MainSwatchPanel();
swatchPanel.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY,
getDisplayName());
swatchPanel.setInheritsPopupMenu(true);
recentSwatchPanel = new RecentSwatchPanel();
recentSwatchPanel.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY,
recentStr);
mainSwatchListener = new MainSwatchListener();
swatchPanel.addMouseListener(mainSwatchListener);
recentSwatchListener = new RecentSwatchListener();
recentSwatchPanel.addMouseListener(recentSwatchListener);
JPanel mainHolder = new JPanel(new BorderLayout());
Border border = new CompoundBorder( new LineBorder(Color.black),
new LineBorder(Color.white) );
mainHolder.setBorder(border);
mainHolder.add(swatchPanel, BorderLayout.CENTER);
gbc.anchor = GridBagConstraints.LAST_LINE_START;
gbc.gridwidth = 1;
gbc.gridheight = 2;
Insets oldInsets = gbc.insets;
gbc.insets = new Insets(0, 0, 0, 10);
superHolder.add(mainHolder, gbc);
gbc.insets = oldInsets;
recentSwatchPanel.addMouseListener(recentSwatchListener);
recentSwatchPanel.setInheritsPopupMenu(true);
JPanel recentHolder = new JPanel( new BorderLayout() );
recentHolder.setBorder(border);
recentHolder.setInheritsPopupMenu(true);
recentHolder.add(recentSwatchPanel, BorderLayout.CENTER);
JLabel l = new JLabel(recentStr);
l.setLabelFor(recentSwatchPanel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.weighty = 1.0;
superHolder.add(l, gbc);
gbc.weighty = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(0, 0, 0, 2);
superHolder.add(recentHolder, gbc);
superHolder.setInheritsPopupMenu(true);
add(superHolder);
}
public void uninstallChooserPanel(JColorChooser enclosingChooser) {
super.uninstallChooserPanel(enclosingChooser);
swatchPanel.removeMouseListener(mainSwatchListener);
recentSwatchPanel.removeMouseListener(recentSwatchListener);
swatchPanel = null;
recentSwatchPanel = null;
mainSwatchListener = null;
recentSwatchListener = null;
removeAll(); // strip out all the sub-components
}
public void updateChooser() {
}
class RecentSwatchListener extends MouseAdapter implements Serializable {
public void mousePressed(MouseEvent e) {
Color color = recentSwatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
}
}
class MainSwatchListener extends MouseAdapter implements Serializable {
public void mousePressed(MouseEvent e) {
Color color = swatchPanel.getColorForLocation(e.getX(), e.getY());
getColorSelectionModel().setSelectedColor(color);
recentSwatchPanel.setMostRecentColor(color);
}
}
}
class SwatchPanel extends JPanel {
protected Color[] colors;
protected Dimension swatchSize;
protected Dimension numSwatches;
protected Dimension gap;
public SwatchPanel() {
initValues();
initColors();
setToolTipText(""); // register for events
setOpaque(true);
setBackground(Color.white);
setRequestFocusEnabled(false);
setInheritsPopupMenu(true);
}
public boolean isFocusTraversable() {
return false;
}
protected void initValues() {
}
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0,0,getWidth(), getHeight());
for (int row = 0; row < numSwatches.height; row++) {
int y = row * (swatchSize.height + gap.height);
for (int column = 0; column < numSwatches.width; column++) {
g.setColor( getColorForCell(column, row) );
int x;
if ((!this.getComponentOrientation().isLeftToRight()) &&
(this instanceof RecentSwatchPanel)) {
x = (numSwatches.width - column - 1) * (swatchSize.width + gap.width);
} else {
x = column * (swatchSize.width + gap.width);
}
g.fillRect( x, y, swatchSize.width, swatchSize.height);
g.setColor(Color.black);
g.drawLine( x+swatchSize.width-1, y, x+swatchSize.width-1, y+swatchSize.height-1);
g.drawLine( x, y+swatchSize.height-1, x+swatchSize.width-1, y+swatchSize.height-1);
}
}
}
public Dimension getPreferredSize() {
int x = numSwatches.width * (swatchSize.width + gap.width) - 1;
int y = numSwatches.height * (swatchSize.height + gap.height) - 1;
return new Dimension( x, y );
}
protected void initColors() {
}
public String getToolTipText(MouseEvent e) {
Color color = getColorForLocation(e.getX(), e.getY());
return color.getRed()+", "+ color.getGreen() + ", " + color.getBlue();
}
public Color getColorForLocation( int x, int y ) {
int column;
if ((!this.getComponentOrientation().isLeftToRight()) &&
(this instanceof RecentSwatchPanel)) {
column = numSwatches.width - x / (swatchSize.width + gap.width) - 1;
} else {
column = x / (swatchSize.width + gap.width);
}
int row = y / (swatchSize.height + gap.height);
return getColorForCell(column, row);
}
private Color getColorForCell( int column, int row) {
return colors[ (row * numSwatches.width) + column ]; // (STEVE) - change data orientation here
}
}
class RecentSwatchPanel extends SwatchPanel {
protected void initValues() {
swatchSize = UIManager.getDimension("ColorChooser.swatchesRecentSwatchSize");
numSwatches = new Dimension( 5, 7 );
gap = new Dimension(1, 1);
}
protected void initColors() {
Color defaultRecentColor = UIManager.getColor("ColorChooser.swatchesDefaultRecentColor");
int numColors = numSwatches.width * numSwatches.height;
colors = new Color[numColors];
for (int i = 0; i < numColors ; i++) {
colors[i] = defaultRecentColor;
}
}
public void setMostRecentColor(Color c) {
System.arraycopy( colors, 0, colors, 1, colors.length-1);
colors[0] = c;
repaint();
}
}
class MainSwatchPanel extends SwatchPanel {
protected void initValues() {
swatchSize = UIManager.getDimension("ColorChooser.swatchesSwatchSize");
numSwatches = new Dimension( 31, 9 );
gap = new Dimension(1, 1);
}
protected void initColors() {
int[] rawValues = initRawValues();
int numColors = rawValues.length / 3;
colors = new Color[numColors];
for (int i = 0; i < numColors ; i++) {
colors[i] = new Color( rawValues[(i*3)], rawValues[(i*3)+1], rawValues[(i*3)+2] );
}
}
private int[] initRawValues() {
int[] rawValues = {
255, 255, 255, // first row.
204, 255, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
204, 204, 255,
255, 204, 255,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 204, 204,
255, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 255, 204,
204, 204, 204, // second row.
153, 255, 255,
153, 204, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
153, 153, 255,
204, 153, 255,
255, 153, 255,
255, 153, 204,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 153, 153,
255, 204, 153,
255, 255, 153,
204, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 153,
153, 255, 204,
204, 204, 204, // third row
102, 255, 255,
102, 204, 255,
102, 153, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
102, 102, 255,
153, 102, 255,
204, 102, 255,
255, 102, 255,
255, 102, 204,
255, 102, 153,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 102, 102,
255, 153, 102,
255, 204, 102,
255, 255, 102,
204, 255, 102,
153, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 102,
102, 255, 153,
102, 255, 204,
153, 153, 153, // fourth row
51, 255, 255,
51, 204, 255,
51, 153, 255,
51, 102, 255,
51, 51, 255,
51, 51, 255,
51, 51, 255,
102, 51, 255,
153, 51, 255,
204, 51, 255,
255, 51, 255,
255, 51, 204,
255, 51, 153,
255, 51, 102,
255, 51, 51,
255, 51, 51,
255, 51, 51,
255, 102, 51,
255, 153, 51,
255, 204, 51,
255, 255, 51,
204, 255, 51,
153, 255, 51,
102, 255, 51,
51, 255, 51,
51, 255, 51,
51, 255, 51,
51, 255, 102,
51, 255, 153,
51, 255, 204,
153, 153, 153, // Fifth row
0, 255, 255,
0, 204, 255,
0, 153, 255,
0, 102, 255,
0, 51, 255,
0, 0, 255,
51, 0, 255,
102, 0, 255,
153, 0, 255,
204, 0, 255,
255, 0, 255,
255, 0, 204,
255, 0, 153,
255, 0, 102,
255, 0, 51,
255, 0 , 0,
255, 51, 0,
255, 102, 0,
255, 153, 0,
255, 204, 0,
255, 255, 0,
204, 255, 0,
153, 255, 0,
102, 255, 0,
51, 255, 0,
0, 255, 0,
0, 255, 51,
0, 255, 102,
0, 255, 153,
0, 255, 204,
102, 102, 102, // sixth row
0, 204, 204,
0, 204, 204,
0, 153, 204,
0, 102, 204,
0, 51, 204,
0, 0, 204,
51, 0, 204,
102, 0, 204,
153, 0, 204,
204, 0, 204,
204, 0, 204,
204, 0, 204,
204, 0, 153,
204, 0, 102,
204, 0, 51,
204, 0, 0,
204, 51, 0,
204, 102, 0,
204, 153, 0,
204, 204, 0,
204, 204, 0,
204, 204, 0,
153, 204, 0,
102, 204, 0,
51, 204, 0,
0, 204, 0,
0, 204, 51,
0, 204, 102,
0, 204, 153,
0, 204, 204,
102, 102, 102, // seventh row
0, 153, 153,
0, 153, 153,
0, 153, 153,
0, 102, 153,
0, 51, 153,
0, 0, 153,
51, 0, 153,
102, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 153,
153, 0, 102,
153, 0, 51,
153, 0, 0,
153, 51, 0,
153, 102, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
153, 153, 0,
102, 153, 0,
51, 153, 0,
0, 153, 0,
0, 153, 51,
0, 153, 102,
0, 153, 153,
0, 153, 153,
51, 51, 51, // eigth row
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 51, 102,
0, 0, 102,
51, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 102,
102, 0, 51,
102, 0, 0,
102, 51, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
102, 102, 0,
51, 102, 0,
0, 102, 0,
0, 102, 51,
0, 102, 102,
0, 102, 102,
0, 102, 102,
0, 0, 0, // ninth row
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 51,
51, 0, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
51, 51, 0,
0, 51, 0,
0, 51, 51,
0, 51, 51,
0, 51, 51,
0, 51, 51,
51, 51, 51 };
return rawValues;
}
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
/** {@collect.stats}
* A <code>ComponentInputMap</code> is an <code>InputMap</code>
* associated with a particular <code>JComponent</code>.
* The component is automatically notified whenever
* the <code>ComponentInputMap</code> changes.
* <code>ComponentInputMap</code>s are used for
* <code>WHEN_IN_FOCUSED_WINDOW</code> bindings.
*
* @author Scott Violet
* @since 1.3
*/
public class ComponentInputMap extends InputMap {
/** {@collect.stats} Component binding is created for. */
private JComponent component;
/** {@collect.stats}
* Creates a <code>ComponentInputMap</code> associated with the
* specified component.
*
* @param component a non-null <code>JComponent</code>
* @throws IllegalArgumentException if <code>component</code> is null
*/
public ComponentInputMap(JComponent component) {
this.component = component;
if (component == null) {
throw new IllegalArgumentException("ComponentInputMaps must be associated with a non-null JComponent");
}
}
/** {@collect.stats}
* Sets the parent, which must be a <code>ComponentInputMap</code>
* associated with the same component as this
* <code>ComponentInputMap</code>.
*
* @param map a <code>ComponentInputMap</code>
*
* @throws IllegalArgumentException if <code>map</code>
* is not a <code>ComponentInputMap</code>
* or is not associated with the same component
*/
public void setParent(InputMap map) {
if (getParent() == map) {
return;
}
if (map != null && (!(map instanceof ComponentInputMap) ||
((ComponentInputMap)map).getComponent() != getComponent())) {
throw new IllegalArgumentException("ComponentInputMaps must have a parent ComponentInputMap associated with the same component");
}
super.setParent(map);
getComponent().componentInputMapChanged(this);
}
/** {@collect.stats}
* Returns the component the <code>InputMap</code> was created for.
*/
public JComponent getComponent() {
return component;
}
/** {@collect.stats}
* Adds a binding for <code>keyStroke</code> to <code>actionMapKey</code>.
* If <code>actionMapKey</code> is null, this removes the current binding
* for <code>keyStroke</code>.
*/
public void put(KeyStroke keyStroke, Object actionMapKey) {
super.put(keyStroke, actionMapKey);
if (getComponent() != null) {
getComponent().componentInputMapChanged(this);
}
}
/** {@collect.stats}
* Removes the binding for <code>key</code> from this object.
*/
public void remove(KeyStroke key) {
super.remove(key);
if (getComponent() != null) {
getComponent().componentInputMapChanged(this);
}
}
/** {@collect.stats}
* Removes all the mappings from this object.
*/
public void clear() {
int oldSize = size();
super.clear();
if (oldSize > 0 && getComponent() != null) {
getComponent().componentInputMapChanged(this);
}
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
import java.awt.Container;
/** {@collect.stats}
* This interface is implemented by components that have a single
* JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.
* The methods in this interface are just <i>covers</i> for the JRootPane
* properties, e.g. <code>getContentPane()</code> is generally implemented
* like this:<pre>
* public Container getContentPane() {
* return getRootPane().getContentPane();
* }
* </pre>
* This interface serves as a <i>marker</i> for Swing GUI builders
* that need to treat components like JFrame, that contain a
* single JRootPane, specially. For example in a GUI builder,
* dropping a component on a RootPaneContainer would be interpreted
* as <code>frame.getContentPane().add(child)</code>.
* <p>
* For conveniance
* <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code>,
* <code>JApplet</code> and <code>JInternalFrame</code>, by default,
* forward, by default, all calls to the <code>add</code>,
* <code>remove</code> and <code>setLayout</code> methods, to the
* <code>contentPane</code>. This means you can call:
* <pre>
* rootPaneContainer.add(component);
* </pre>
* instead of:
* <pre>
* rootPaneContainer.getContentPane().add(component);
* </pre>
* <p>
* The behavior of the <code>add</code> and
* <code>setLayout</code> methods for
* <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code>,
* <code>JApplet</code> and <code>JInternalFrame</code> is controlled by
* the <code>rootPaneCheckingEnabled</code> property. If this property is
* true (the default), then calls to these methods are
* forwarded to the <code>contentPane</code>; if false, these
* methods operate directly on the <code>RootPaneContainer</code>. This
* property is only intended for subclasses, and is therefore protected.
*
* @see JRootPane
* @see JFrame
* @see JDialog
* @see JWindow
* @see JApplet
* @see JInternalFrame
*
* @author Hans Muller
*/
public interface RootPaneContainer
{
/** {@collect.stats}
* Return this component's single JRootPane child. A conventional
* implementation of this interface will have all of the other
* methods indirect through this one. The rootPane has two
* children: the glassPane and the layeredPane.
*
* @return this components single JRootPane child.
* @see JRootPane
*/
JRootPane getRootPane();
/** {@collect.stats}
* The "contentPane" is the primary container for application
* specific components. Applications should add children to
* the contentPane, set its layout manager, and so on.
* <p>
* The contentPane may not be null.
* <p>
* Generally implemented with
* <code>getRootPane().setContentPane(contentPane);</code>
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the content pane parameter is null
* @param contentPane the Container to use for the contents of this
* JRootPane
* @see JRootPane#getContentPane
* @see #getContentPane
*/
void setContentPane(Container contentPane);
/** {@collect.stats}
* Returns the contentPane.
*
* @return the value of the contentPane property.
* @see #setContentPane
*/
Container getContentPane();
/** {@collect.stats}
* A Container that manages the contentPane and in some cases a menu bar.
* The layeredPane can be used by descendants that want to add a child
* to the RootPaneContainer that isn't layout managed. For example
* an internal dialog or a drag and drop effect component.
* <p>
* The layeredPane may not be null.
* <p>
* Generally implemented with<pre>
* getRootPane().setLayeredPane(layeredPane);</pre>
*
* @exception java.awt.IllegalComponentStateException (a runtime
* exception) if the layered pane parameter is null
* @see #getLayeredPane
* @see JRootPane#getLayeredPane
*/
void setLayeredPane(JLayeredPane layeredPane);
/** {@collect.stats}
* Returns the layeredPane.
*
* @return the value of the layeredPane property.
* @see #setLayeredPane
*/
JLayeredPane getLayeredPane();
/** {@collect.stats}
* The glassPane is always the first child of the rootPane
* and the rootPanes layout manager ensures that it's always
* as big as the rootPane. By default it's transparent and
* not visible. It can be used to temporarily grab all keyboard
* and mouse input by adding listeners and then making it visible.
* by default it's not visible.
* <p>
* The glassPane may not be null.
* <p>
* Generally implemented with
* <code>getRootPane().setGlassPane(glassPane);</code>
*
* @see #getGlassPane
* @see JRootPane#setGlassPane
*/
void setGlassPane(Component glassPane);
/** {@collect.stats}
* Returns the glassPane.
*
* @return the value of the glassPane property.
* @see #setGlassPane
*/
Component getGlassPane();
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
import java.util.EventObject;
import java.io.Serializable;
/** {@collect.stats}
*
* A base class for <code>CellEditors</code>, providing default
* implementations for the methods in the <code>CellEditor</code>
* interface except <code>getCellEditorValue()</code>.
* Like the other abstract implementations in Swing, also manages a list
* of listeners.
*
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Philip Milne
* @since 1.3
*/
public abstract class AbstractCellEditor implements CellEditor, Serializable {
protected EventListenerList listenerList = new EventListenerList();
transient protected ChangeEvent changeEvent = null;
// Force this to be implemented.
// public Object getCellEditorValue()
/** {@collect.stats}
* Returns true.
* @param e an event object
* @return true
*/
public boolean isCellEditable(EventObject e) {
return true;
}
/** {@collect.stats}
* Returns true.
* @param anEvent an event object
* @return true
*/
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
/** {@collect.stats}
* Calls <code>fireEditingStopped</code> and returns true.
* @return true
*/
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
/** {@collect.stats}
* Calls <code>fireEditingCanceled</code>.
*/
public void cancelCellEditing() {
fireEditingCanceled();
}
/** {@collect.stats}
* Adds a <code>CellEditorListener</code> to the listener list.
* @param l the new listener to be added
*/
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
}
/** {@collect.stats}
* Removes a <code>CellEditorListener</code> from the listener list.
* @param l the listener to be removed
*/
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
}
/** {@collect.stats}
* Returns an array of all the <code>CellEditorListener</code>s added
* to this AbstractCellEditor with addCellEditorListener().
*
* @return all of the <code>CellEditorListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public CellEditorListener[] getCellEditorListeners() {
return (CellEditorListener[])listenerList.getListeners(
CellEditorListener.class);
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @see EventListenerList
*/
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
}
}
}
/** {@collect.stats}
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is created lazily.
*
* @see EventListenerList
*/
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
}
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.border.*;
import java.awt.LayoutManager;
import java.awt.Component;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.Serializable;
/** {@collect.stats}
* The layout manager used by <code>JScrollPane</code>.
* <code>JScrollPaneLayout</code> is
* responsible for nine components: a viewport, two scrollbars,
* a row header, a column header, and four "corner" components.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JScrollPane
* @see JViewport
*
* @author Hans Muller
*/
public class ScrollPaneLayout
implements LayoutManager, ScrollPaneConstants, Serializable
{
/** {@collect.stats}
* The scrollpane's viewport child.
* Default is an empty <code>JViewport</code>.
* @see JScrollPane#setViewport
*/
protected JViewport viewport;
/** {@collect.stats}
* The scrollpane's vertical scrollbar child.
* Default is a <code>JScrollBar</code>.
* @see JScrollPane#setVerticalScrollBar
*/
protected JScrollBar vsb;
/** {@collect.stats}
* The scrollpane's horizontal scrollbar child.
* Default is a <code>JScrollBar</code>.
* @see JScrollPane#setHorizontalScrollBar
*/
protected JScrollBar hsb;
/** {@collect.stats}
* The row header child. Default is <code>null</code>.
* @see JScrollPane#setRowHeader
*/
protected JViewport rowHead;
/** {@collect.stats}
* The column header child. Default is <code>null</code>.
* @see JScrollPane#setColumnHeader
*/
protected JViewport colHead;
/** {@collect.stats}
* The component to display in the lower left corner.
* Default is <code>null</code>.
* @see JScrollPane#setCorner
*/
protected Component lowerLeft;
/** {@collect.stats}
* The component to display in the lower right corner.
* Default is <code>null</code>.
* @see JScrollPane#setCorner
*/
protected Component lowerRight;
/** {@collect.stats}
* The component to display in the upper left corner.
* Default is <code>null</code>.
* @see JScrollPane#setCorner
*/
protected Component upperLeft;
/** {@collect.stats}
* The component to display in the upper right corner.
* Default is <code>null</code>.
* @see JScrollPane#setCorner
*/
protected Component upperRight;
/** {@collect.stats}
* The display policy for the vertical scrollbar.
* The default is <code>ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED</code>.
* <p>
* This field is obsolete, please use the <code>JScrollPane</code> field instead.
*
* @see JScrollPane#setVerticalScrollBarPolicy
*/
protected int vsbPolicy = VERTICAL_SCROLLBAR_AS_NEEDED;
/** {@collect.stats}
* The display policy for the horizontal scrollbar.
* The default is <code>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED</code>.
* <p>
* This field is obsolete, please use the <code>JScrollPane</code> field instead.
*
* @see JScrollPane#setHorizontalScrollBarPolicy
*/
protected int hsbPolicy = HORIZONTAL_SCROLLBAR_AS_NEEDED;
/** {@collect.stats}
* This method is invoked after the ScrollPaneLayout is set as the
* LayoutManager of a <code>JScrollPane</code>.
* It initializes all of the internal fields that
* are ordinarily set by <code>addLayoutComponent</code>. For example:
* <pre>
* ScrollPaneLayout mySPLayout = new ScrollPanelLayout() {
* public void layoutContainer(Container p) {
* super.layoutContainer(p);
* // do some extra work here ...
* }
* };
* scrollpane.setLayout(mySPLayout):
* </pre>
*/
public void syncWithScrollPane(JScrollPane sp) {
viewport = sp.getViewport();
vsb = sp.getVerticalScrollBar();
hsb = sp.getHorizontalScrollBar();
rowHead = sp.getRowHeader();
colHead = sp.getColumnHeader();
lowerLeft = sp.getCorner(LOWER_LEFT_CORNER);
lowerRight = sp.getCorner(LOWER_RIGHT_CORNER);
upperLeft = sp.getCorner(UPPER_LEFT_CORNER);
upperRight = sp.getCorner(UPPER_RIGHT_CORNER);
vsbPolicy = sp.getVerticalScrollBarPolicy();
hsbPolicy = sp.getHorizontalScrollBarPolicy();
}
/** {@collect.stats}
* Removes an existing component. When a new component, such as
* the left corner, or vertical scrollbar, is added, the old one,
* if it exists, must be removed.
* <p>
* This method returns <code>newC</code>. If <code>oldC</code> is
* not equal to <code>newC</code> and is non-<code>null</code>,
* it will be removed from its parent.
*
* @param oldC the <code>Component</code> to replace
* @param newC the <code>Component</code> to add
* @return the <code>newC</code>
*/
protected Component addSingletonComponent(Component oldC, Component newC)
{
if ((oldC != null) && (oldC != newC)) {
oldC.getParent().remove(oldC);
}
return newC;
}
/** {@collect.stats}
* Adds the specified component to the layout. The layout is
* identified using one of:
* <ul>
* <li>ScrollPaneConstants.VIEWPORT
* <li>ScrollPaneConstants.VERTICAL_SCROLLBAR
* <li>ScrollPaneConstants.HORIZONTAL_SCROLLBAR
* <li>ScrollPaneConstants.ROW_HEADER
* <li>ScrollPaneConstants.COLUMN_HEADER
* <li>ScrollPaneConstants.LOWER_LEFT_CORNER
* <li>ScrollPaneConstants.LOWER_RIGHT_CORNER
* <li>ScrollPaneConstants.UPPER_LEFT_CORNER
* <li>ScrollPaneConstants.UPPER_RIGHT_CORNER
* </ul>
*
* @param s the component identifier
* @param c the the component to be added
* @exception IllegalArgumentException if <code>s</code> is an invalid key
*/
public void addLayoutComponent(String s, Component c)
{
if (s.equals(VIEWPORT)) {
viewport = (JViewport)addSingletonComponent(viewport, c);
}
else if (s.equals(VERTICAL_SCROLLBAR)) {
vsb = (JScrollBar)addSingletonComponent(vsb, c);
}
else if (s.equals(HORIZONTAL_SCROLLBAR)) {
hsb = (JScrollBar)addSingletonComponent(hsb, c);
}
else if (s.equals(ROW_HEADER)) {
rowHead = (JViewport)addSingletonComponent(rowHead, c);
}
else if (s.equals(COLUMN_HEADER)) {
colHead = (JViewport)addSingletonComponent(colHead, c);
}
else if (s.equals(LOWER_LEFT_CORNER)) {
lowerLeft = addSingletonComponent(lowerLeft, c);
}
else if (s.equals(LOWER_RIGHT_CORNER)) {
lowerRight = addSingletonComponent(lowerRight, c);
}
else if (s.equals(UPPER_LEFT_CORNER)) {
upperLeft = addSingletonComponent(upperLeft, c);
}
else if (s.equals(UPPER_RIGHT_CORNER)) {
upperRight = addSingletonComponent(upperRight, c);
}
else {
throw new IllegalArgumentException("invalid layout key " + s);
}
}
/** {@collect.stats}
* Removes the specified component from the layout.
*
* @param c the component to remove
*/
public void removeLayoutComponent(Component c)
{
if (c == viewport) {
viewport = null;
}
else if (c == vsb) {
vsb = null;
}
else if (c == hsb) {
hsb = null;
}
else if (c == rowHead) {
rowHead = null;
}
else if (c == colHead) {
colHead = null;
}
else if (c == lowerLeft) {
lowerLeft = null;
}
else if (c == lowerRight) {
lowerRight = null;
}
else if (c == upperLeft) {
upperLeft = null;
}
else if (c == upperRight) {
upperRight = null;
}
}
/** {@collect.stats}
* Returns the vertical scrollbar-display policy.
*
* @return an integer giving the display policy
* @see #setVerticalScrollBarPolicy
*/
public int getVerticalScrollBarPolicy() {
return vsbPolicy;
}
/** {@collect.stats}
* Sets the vertical scrollbar-display policy. The options
* are:
* <ul>
* <li>ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
* <li>ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
* <li>ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
* </ul>
* Note: Applications should use the <code>JScrollPane</code> version
* of this method. It only exists for backwards compatibility
* with the Swing 1.0.2 (and earlier) versions of this class.
*
* @param x an integer giving the display policy
* @exception IllegalArgumentException if <code>x</code> is an invalid
* vertical scroll bar policy, as listed above
*/
public void setVerticalScrollBarPolicy(int x) {
switch (x) {
case VERTICAL_SCROLLBAR_AS_NEEDED:
case VERTICAL_SCROLLBAR_NEVER:
case VERTICAL_SCROLLBAR_ALWAYS:
vsbPolicy = x;
break;
default:
throw new IllegalArgumentException("invalid verticalScrollBarPolicy");
}
}
/** {@collect.stats}
* Returns the horizontal scrollbar-display policy.
*
* @return an integer giving the display policy
* @see #setHorizontalScrollBarPolicy
*/
public int getHorizontalScrollBarPolicy() {
return hsbPolicy;
}
/** {@collect.stats}
* Sets the horizontal scrollbar-display policy.
* The options are:<ul>
* <li>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
* <li>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
* <li>ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
* </ul>
* Note: Applications should use the <code>JScrollPane</code> version
* of this method. It only exists for backwards compatibility
* with the Swing 1.0.2 (and earlier) versions of this class.
*
* @param x an int giving the display policy
* @exception IllegalArgumentException if <code>x</code> is not a valid
* horizontal scrollbar policy, as listed above
*/
public void setHorizontalScrollBarPolicy(int x) {
switch (x) {
case HORIZONTAL_SCROLLBAR_AS_NEEDED:
case HORIZONTAL_SCROLLBAR_NEVER:
case HORIZONTAL_SCROLLBAR_ALWAYS:
hsbPolicy = x;
break;
default:
throw new IllegalArgumentException("invalid horizontalScrollBarPolicy");
}
}
/** {@collect.stats}
* Returns the <code>JViewport</code> object that displays the
* scrollable contents.
* @return the <code>JViewport</code> object that displays the scrollable contents
* @see JScrollPane#getViewport
*/
public JViewport getViewport() {
return viewport;
}
/** {@collect.stats}
* Returns the <code>JScrollBar</code> object that handles horizontal scrolling.
* @return the <code>JScrollBar</code> object that handles horizontal scrolling
* @see JScrollPane#getHorizontalScrollBar
*/
public JScrollBar getHorizontalScrollBar() {
return hsb;
}
/** {@collect.stats}
* Returns the <code>JScrollBar</code> object that handles vertical scrolling.
* @return the <code>JScrollBar</code> object that handles vertical scrolling
* @see JScrollPane#getVerticalScrollBar
*/
public JScrollBar getVerticalScrollBar() {
return vsb;
}
/** {@collect.stats}
* Returns the <code>JViewport</code> object that is the row header.
* @return the <code>JViewport</code> object that is the row header
* @see JScrollPane#getRowHeader
*/
public JViewport getRowHeader() {
return rowHead;
}
/** {@collect.stats}
* Returns the <code>JViewport</code> object that is the column header.
* @return the <code>JViewport</code> object that is the column header
* @see JScrollPane#getColumnHeader
*/
public JViewport getColumnHeader() {
return colHead;
}
/** {@collect.stats}
* Returns the <code>Component</code> at the specified corner.
* @param key the <code>String</code> specifying the corner
* @return the <code>Component</code> at the specified corner, as defined in
* {@link ScrollPaneConstants}; if <code>key</code> is not one of the
* four corners, <code>null</code> is returned
* @see JScrollPane#getCorner
*/
public Component getCorner(String key) {
if (key.equals(LOWER_LEFT_CORNER)) {
return lowerLeft;
}
else if (key.equals(LOWER_RIGHT_CORNER)) {
return lowerRight;
}
else if (key.equals(UPPER_LEFT_CORNER)) {
return upperLeft;
}
else if (key.equals(UPPER_RIGHT_CORNER)) {
return upperRight;
}
else {
return null;
}
}
/** {@collect.stats}
* The preferred size of a <code>ScrollPane</code> is the size of the insets,
* plus the preferred size of the viewport, plus the preferred size of
* the visible headers, plus the preferred size of the scrollbars
* that will appear given the current view and the current
* scrollbar displayPolicies.
* <p>Note that the rowHeader is calculated as part of the preferred width
* and the colHeader is calculated as part of the preferred size.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the preferred size of the
* viewport and any scrollbars
* @see ViewportLayout
* @see LayoutManager
*/
public Dimension preferredLayoutSize(Container parent)
{
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
/* Note that viewport.getViewSize() is equivalent to
* viewport.getView().getPreferredSize() modulo a null
* view or a view whose size was explicitly set.
*/
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
view = viewport.getView();
if (view != null) {
viewSize = view.getPreferredSize();
}
}
/* If there's a viewport add its preferredSize.
*/
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* preferred size in.
*/
if ((rowHead != null) && rowHead.isVisible()) {
prefWidth += rowHead.getPreferredSize().width;
}
if ((colHead != null) && colHead.isVisible()) {
prefHeight += colHead.getPreferredSize().height;
}
/* If a scrollbar is going to appear, factor its preferred size in.
* If the scrollbars policy is AS_NEEDED, this can be a little
* tricky:
*
* - If the view is a Scrollable then scrollableTracksViewportWidth
* and scrollableTracksViewportHeight can be used to effectively
* disable scrolling (if they're true) in their respective dimensions.
*
* - Assuming that a scrollbar hasn't been disabled by the
* previous constraint, we need to decide if the scrollbar is going
* to appear to correctly compute the JScrollPanes preferred size.
* To do this we compare the preferredSize of the viewport (the
* extentSize) to the preferredSize of the view. Although we're
* not responsible for laying out the view we'll assume that the
* JViewport will always give it its preferredSize.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
return new Dimension(prefWidth, prefHeight);
}
/** {@collect.stats}
* The minimum size of a <code>ScrollPane</code> is the size of the insets
* plus minimum size of the viewport, plus the scrollpane's
* viewportBorder insets, plus the minimum size
* of the visible headers, plus the minimum size of the
* scrollbars whose displayPolicy isn't NEVER.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the minimum size
*/
public Dimension minimumLayoutSize(Container parent)
{
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int minWidth = insets.left + insets.right;
int minHeight = insets.top + insets.bottom;
/* If there's a viewport add its minimumSize.
*/
if (viewport != null) {
Dimension size = viewport.getMinimumSize();
minWidth += size.width;
minHeight += size.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
minWidth += vpbInsets.left + vpbInsets.right;
minHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* minimum size in.
*/
if ((rowHead != null) && rowHead.isVisible()) {
Dimension size = rowHead.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((colHead != null) && colHead.isVisible()) {
Dimension size = colHead.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
/* If a scrollbar might appear, factor its minimum
* size in.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
Dimension size = vsb.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
Dimension size = hsb.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
return new Dimension(minWidth, minHeight);
}
/** {@collect.stats}
* Lays out the scrollpane. The positioning of components depends on
* the following constraints:
* <ul>
* <li> The row header, if present and visible, gets its preferred
* width and the viewport's height.
*
* <li> The column header, if present and visible, gets its preferred
* height and the viewport's width.
*
* <li> If a vertical scrollbar is needed, i.e. if the viewport's extent
* height is smaller than its view height or if the <code>displayPolicy</code>
* is ALWAYS, it's treated like the row header with respect to its
* dimensions and is made visible.
*
* <li> If a horizontal scrollbar is needed, it is treated like the
* column header (see the paragraph above regarding the vertical scrollbar).
*
* <li> If the scrollpane has a non-<code>null</code>
* <code>viewportBorder</code>, then space is allocated for that.
*
* <li> The viewport gets the space available after accounting for
* the previous constraints.
*
* <li> The corner components, if provided, are aligned with the
* ends of the scrollbars and headers. If there is a vertical
* scrollbar, the right corners appear; if there is a horizontal
* scrollbar, the lower corners appear; a row header gets left
* corners, and a column header gets upper corners.
* </ul>
*
* @param parent the <code>Container</code> to lay out
*/
public void layoutContainer(Container parent)
{
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* Get the scrollPane's orientation.
*/
boolean leftToRight = SwingUtilities.isLeftToRight(scrollPane);
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height,
colHead.getPreferredSize().height);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = Math.min(availR.width,
rowHead.getPreferredSize().width);
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
if ( leftToRight ) {
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
} else {
rowHeadR.x = availR.x + availR.width;
}
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0,0,0,0);
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize =
(view != null) ? view.getPreferredSize()
: new Dimension(0,0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0,0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable)view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (isEmpty) {
vsbNeeded = false;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height);
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (isEmpty) {
hsbNeeded = false;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width);
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
if (viewport != null) {
viewport.setBounds(availR);
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.
getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.
getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight &&
(viewPrefSize.height > extentSize.height);
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets,
leftToRight);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy ==HORIZONTAL_SCROLLBAR_AS_NEEDED){
boolean newHSBbNeeded = !viewTracksViewportWidth &&
(viewPrefSize.width > extentSize.width);
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets,
leftToRight);
}
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(availR);
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(rowHeadR);
}
if (colHead != null) {
colHead.setBounds(colHeadR);
}
if (vsb != null) {
if (vsbNeeded) {
if (colHead != null &&
UIManager.getBoolean("ScrollPane.fillUpperCorner"))
{
if ((leftToRight && upperRight == null) ||
(!leftToRight && upperLeft == null))
{
// This is used primarily for GTK L&F, which needs to
// extend the vertical scrollbar to fill the upper
// corner near the column header. Note that we skip
// this step (and use the default behavior) if the
// user has set a custom corner component.
vsbR.y = colHeadR.y;
vsbR.height += colHeadR.height;
}
}
vsb.setVisible(true);
vsb.setBounds(vsbR);
}
else {
vsb.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
if (rowHead != null &&
UIManager.getBoolean("ScrollPane.fillLowerCorner"))
{
if ((leftToRight && lowerLeft == null) ||
(!leftToRight && lowerRight == null))
{
// This is used primarily for GTK L&F, which needs to
// extend the horizontal scrollbar to fill the lower
// corner near the row header. Note that we skip
// this step (and use the default behavior) if the
// user has set a custom corner component.
if (leftToRight) {
hsbR.x = rowHeadR.x;
}
hsbR.width += rowHeadR.width;
}
}
hsb.setVisible(true);
hsb.setBounds(hsbR);
}
else {
hsb.setVisible(false);
}
}
if (lowerLeft != null) {
lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
hsbR.y,
leftToRight ? rowHeadR.width : vsbR.width,
hsbR.height);
}
if (lowerRight != null) {
lowerRight.setBounds(leftToRight ? vsbR.x : rowHeadR.x,
hsbR.y,
leftToRight ? vsbR.width : rowHeadR.width,
hsbR.height);
}
if (upperLeft != null) {
upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colHeadR.y,
leftToRight ? rowHeadR.width : vsbR.width,
colHeadR.height);
}
if (upperRight != null) {
upperRight.setBounds(leftToRight ? vsbR.x : rowHeadR.x,
colHeadR.y,
leftToRight ? vsbR.width : rowHeadR.width,
colHeadR.height);
}
}
/** {@collect.stats}
* Adjusts the <code>Rectangle</code> <code>available</code> based on if
* the vertical scrollbar is needed (<code>wantsVSB</code>).
* The location of the vsb is updated in <code>vsbR</code>, and
* the viewport border insets (<code>vpbInsets</code>) are used to offset
* the vsb. This is only called when <code>wantsVSB</code> has
* changed, eg you shouldn't invoke adjustForVSB(true) twice.
*/
private void adjustForVSB(boolean wantsVSB, Rectangle available,
Rectangle vsbR, Insets vpbInsets,
boolean leftToRight) {
int oldWidth = vsbR.width;
if (wantsVSB) {
int vsbWidth = Math.max(0, Math.min(vsb.getPreferredSize().width,
available.width));
available.width -= vsbWidth;
vsbR.width = vsbWidth;
if( leftToRight ) {
vsbR.x = available.x + available.width + vpbInsets.right;
} else {
vsbR.x = available.x - vpbInsets.left;
available.x += vsbWidth;
}
}
else {
available.width += oldWidth;
}
}
/** {@collect.stats}
* Adjusts the <code>Rectangle</code> <code>available</code> based on if
* the horizontal scrollbar is needed (<code>wantsHSB</code>).
* The location of the hsb is updated in <code>hsbR</code>, and
* the viewport border insets (<code>vpbInsets</code>) are used to offset
* the hsb. This is only called when <code>wantsHSB</code> has
* changed, eg you shouldn't invoked adjustForHSB(true) twice.
*/
private void adjustForHSB(boolean wantsHSB, Rectangle available,
Rectangle hsbR, Insets vpbInsets) {
int oldHeight = hsbR.height;
if (wantsHSB) {
int hsbHeight = Math.max(0, Math.min(available.height,
hsb.getPreferredSize().height));
available.height -= hsbHeight;
hsbR.y = available.y + available.height + vpbInsets.bottom;
hsbR.height = hsbHeight;
}
else {
available.height += oldHeight;
}
}
/** {@collect.stats}
* Returns the bounds of the border around the specified scroll pane's
* viewport.
*
* @return the size and position of the viewport border
* @deprecated As of JDK version Swing1.1
* replaced by <code>JScrollPane.getViewportBorderBounds()</code>.
*/
@Deprecated
public Rectangle getViewportBorderBounds(JScrollPane scrollpane) {
return scrollpane.getViewportBorderBounds();
}
/** {@collect.stats}
* The UI resource version of <code>ScrollPaneLayout</code>.
*/
public static class UIResource extends ScrollPaneLayout implements javax.swing.plaf.UIResource {}
}
|
Java
|
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Component;
/** {@collect.stats}
* Identifies components that can be used as "rubber stamps" to paint
* the cells in a JList. For example, to use a JLabel as a
* ListCellRenderer, you would write something like this:
* <pre>
* class MyCellRenderer extends JLabel implements ListCellRenderer {
* public MyCellRenderer() {
* setOpaque(true);
* }
*
* public Component getListCellRendererComponent(JList list,
* Object value,
* int index,
* boolean isSelected,
* boolean cellHasFocus) {
*
* setText(value.toString());
*
* Color background;
* Color foreground;
*
* // check if this cell represents the current DnD drop location
* JList.DropLocation dropLocation = list.getDropLocation();
* if (dropLocation != null
* && !dropLocation.isInsert()
* && dropLocation.getIndex() == index) {
*
* background = Color.BLUE;
* foreground = Color.WHITE;
*
* // check if this cell is selected
* } else if (isSelected) {
* background = Color.RED;
* foreground = Color.WHITE;
*
* // unselected, and not the DnD drop location
* } else {
* background = Color.WHITE;
* foreground = Color.BLACK;
* };
*
* setBackground(background);
* setForeground(foreground);
*
* return this;
* }
* }
* </pre>
*
* @see JList
* @see DefaultListCellRenderer
*
* @author Hans Muller
*/
public interface ListCellRenderer
{
/** {@collect.stats}
* Return a component that has been configured to display the specified
* value. That component's <code>paint</code> method is then called to
* "render" the cell. If it is necessary to compute the dimensions
* of a list because the list cells do not have a fixed size, this method
* is called to generate a component on which <code>getPreferredSize</code>
* can be invoked.
*
* @param list The JList we're painting.
* @param value The value returned by list.getModel().getElementAt(index).
* @param index The cells index.
* @param isSelected True if the specified cell was selected.
* @param cellHasFocus True if the specified cell has the focus.
* @return A component whose paint() method will render the specified value.
*
* @see JList
* @see ListSelectionModel
* @see ListModel
*/
Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus);
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.x500;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.security.auth.Destroyable;
/** {@collect.stats}
* <p> This class represents an <code>X500PrivateCredential</code>.
* It associates an X.509 certificate, corresponding private key and the
* KeyStore alias used to reference that exact key pair in the KeyStore.
* This enables looking up the private credentials for an X.500 principal
* in a subject.
*
*/
public final class X500PrivateCredential implements Destroyable {
private X509Certificate cert;
private PrivateKey key;
private String alias;
/** {@collect.stats}
* Creates an X500PrivateCredential that associates an X.509 certificate,
* a private key and the KeyStore alias.
* <p>
* @param cert X509Certificate
* @param key PrivateKey for the certificate
* @exception IllegalArgumentException if either <code>cert</code> or
* <code>key</code> is null
*
*/
public X500PrivateCredential(X509Certificate cert, PrivateKey key) {
if (cert == null || key == null )
throw new IllegalArgumentException();
this.cert = cert;
this.key = key;
this.alias=null;
}
/** {@collect.stats}
* Creates an X500PrivateCredential that associates an X.509 certificate,
* a private key and the KeyStore alias.
* <p>
* @param cert X509Certificate
* @param key PrivateKey for the certificate
* @param alias KeyStore alias
* @exception IllegalArgumentException if either <code>cert</code>,
* <code>key</code> or <code>alias</code> is null
*
*/
public X500PrivateCredential(X509Certificate cert, PrivateKey key,
String alias) {
if (cert == null || key == null|| alias == null )
throw new IllegalArgumentException();
this.cert = cert;
this.key = key;
this.alias=alias;
}
/** {@collect.stats}
* Returns the X.509 certificate.
* <p>
* @return the X509Certificate
*/
public X509Certificate getCertificate() {
return cert;
}
/** {@collect.stats}
* Returns the PrivateKey.
* <p>
* @return the PrivateKey
*/
public PrivateKey getPrivateKey() {
return key;
}
/** {@collect.stats}
* Returns the KeyStore alias.
* <p>
* @return the KeyStore alias
*/
public String getAlias() {
return alias;
}
/** {@collect.stats}
* Clears the references to the X.509 certificate, private key and the
* KeyStore alias in this object.
*/
public void destroy() {
cert = null;
key = null;
alias =null;
}
/** {@collect.stats}
* Determines if the references to the X.509 certificate and private key
* in this object have been cleared.
* <p>
* @return true if X509Certificate and the PrivateKey are null
*/
public boolean isDestroyed() {
return cert == null && key == null && alias==null;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.x500;
import java.io.*;
import java.security.Principal;
import java.util.Collections;
import java.util.Map;
import sun.security.x509.X500Name;
import sun.security.util.*;
/** {@collect.stats}
* <p> This class represents an X.500 <code>Principal</code>.
* <code>X500Principal</code>s are represented by distinguished names such as
* "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US".
*
* <p> This class can be instantiated by using a string representation
* of the distinguished name, or by using the ASN.1 DER encoded byte
* representation of the distinguished name. The current specification
* for the string representation of a distinguished name is defined in
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253: Lightweight
* Directory Access Protocol (v3): UTF-8 String Representation of
* Distinguished Names</a>. This class, however, accepts string formats from
* both RFC 2253 and <a href="http://www.ietf.org/rfc/rfc1779.txt">RFC 1779:
* A String Representation of Distinguished Names</a>, and also recognizes
* attribute type keywords whose OIDs (Object Identifiers) are defined in
* <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
* Public Key Infrastructure Certificate and CRL Profile</a>.
*
* <p> The string representation for this <code>X500Principal</code>
* can be obtained by calling the <code>getName</code> methods.
*
* <p> Note that the <code>getSubjectX500Principal</code> and
* <code>getIssuerX500Principal</code> methods of
* <code>X509Certificate</code> return X500Principals representing the
* issuer and subject fields of the certificate.
*
* @see java.security.cert.X509Certificate
* @since 1.4
*/
public final class X500Principal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -500463348111345721L;
/** {@collect.stats}
* RFC 1779 String format of Distinguished Names.
*/
public static final String RFC1779 = "RFC1779";
/** {@collect.stats}
* RFC 2253 String format of Distinguished Names.
*/
public static final String RFC2253 = "RFC2253";
/** {@collect.stats}
* Canonical String format of Distinguished Names.
*/
public static final String CANONICAL = "CANONICAL";
/** {@collect.stats}
* The X500Name representing this principal.
*
* NOTE: this field is reflectively accessed from within X500Name.
*/
private transient X500Name thisX500Name;
/** {@collect.stats}
* Creates an X500Principal by wrapping an X500Name.
*
* NOTE: The constructor is package private. It is intended to be accessed
* using privileged reflection from classes in sun.security.*.
* Currently referenced from sun.security.x509.X500Name.asX500Principal().
*/
X500Principal(X500Name x500Name) {
thisX500Name = x500Name;
}
/** {@collect.stats}
* Creates an <code>X500Principal</code> from a string representation of
* an X.500 distinguished name (ex:
* "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
* The distinguished name must be specified using the grammar defined in
* RFC 1779 or RFC 2253 (either format is acceptable).
*
* <p>This constructor recognizes the attribute type keywords
* defined in RFC 1779 and RFC 2253
* (and listed in {@link #getName(String format) getName(String format)}),
* as well as the T, DNQ or DNQUALIFIER, SURNAME, GIVENNAME, INITIALS,
* GENERATION, EMAILADDRESS, and SERIALNUMBER keywords whose OIDs are
* defined in RFC 3280 and its successor.
* Any other attribute type must be specified as an OID.
*
* @param name an X.500 distinguished name in RFC 1779 or RFC 2253 format
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>
* @exception IllegalArgumentException if the <code>name</code>
* is improperly specified
*/
public X500Principal(String name) {
this(name, (Map<String, String>) Collections.EMPTY_MAP);
}
/** {@collect.stats}
* Creates an <code>X500Principal</code> from a string representation of
* an X.500 distinguished name (ex:
* "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
* The distinguished name must be specified using the grammar defined in
* RFC 1779 or RFC 2253 (either format is acceptable).
*
* <p> This constructor recognizes the attribute type keywords specified
* in {@link #X500Principal(String)} and also recognizes additional
* keywords that have entries in the <code>keywordMap</code> parameter.
* Keyword entries in the keywordMap take precedence over the default
* keywords recognized by <code>X500Principal(String)</code>. Keywords
* MUST be specified in all upper-case, otherwise they will be ignored.
* Improperly specified keywords are ignored; however if a keyword in the
* name maps to an improperly specified OID, an
* <code>IllegalArgumentException</code> is thrown. It is permissible to
* have 2 different keywords that map to the same OID.
*
* @param name an X.500 distinguished name in RFC 1779 or RFC 2253 format
* @param keywordMap an attribute type keyword map, where each key is a
* keyword String that maps to a corresponding object identifier in String
* form (a sequence of nonnegative integers separated by periods). The map
* may be empty but never <code>null</code>.
* @exception NullPointerException if <code>name</code> or
* <code>keywordMap</code> is <code>null</code>
* @exception IllegalArgumentException if the <code>name</code> is
* improperly specified or a keyword in the <code>name</code> maps to an
* OID that is not in the correct form
* @since 1.6
*/
public X500Principal(String name, Map<String, String> keywordMap) {
if (name == null) {
throw new NullPointerException
(sun.security.util.ResourcesMgr.getString
("provided null name"));
}
if (keywordMap == null) {
throw new NullPointerException
(sun.security.util.ResourcesMgr.getString
("provided null keyword map"));
}
try {
thisX500Name = new X500Name(name, keywordMap);
} catch (Exception e) {
IllegalArgumentException iae = new IllegalArgumentException
("improperly specified input name: " + name);
iae.initCause(e);
throw iae;
}
}
/** {@collect.stats}
* Creates an <code>X500Principal</code> from a distinguished name in
* ASN.1 DER encoded form. The ASN.1 notation for this structure is as
* follows.
* <pre><code>
* Name ::= CHOICE {
* RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::=
* SET SIZE (1 .. MAX) OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
* ....
* DirectoryString ::= CHOICE {
* teletexString TeletexString (SIZE (1..MAX)),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1.. MAX)),
* bmpString BMPString (SIZE (1..MAX)) }
* </code></pre>
*
* @param name a byte array containing the distinguished name in ASN.1
* DER encoded form
* @throws IllegalArgumentException if an encoding error occurs
* (incorrect form for DN)
*/
public X500Principal(byte[] name) {
try {
thisX500Name = new X500Name(name);
} catch (Exception e) {
IllegalArgumentException iae = new IllegalArgumentException
("improperly specified input name");
iae.initCause(e);
throw iae;
}
}
/** {@collect.stats}
* Creates an <code>X500Principal</code> from an <code>InputStream</code>
* containing the distinguished name in ASN.1 DER encoded form.
* The ASN.1 notation for this structure is supplied in the
* documentation for
* {@link #X500Principal(byte[] name) X500Principal(byte[] name)}.
*
* <p> The read position of the input stream is positioned
* to the next available byte after the encoded distinguished name.
*
* @param is an <code>InputStream</code> containing the distinguished
* name in ASN.1 DER encoded form
*
* @exception NullPointerException if the <code>InputStream</code>
* is <code>null</code>
* @exception IllegalArgumentException if an encoding error occurs
* (incorrect form for DN)
*/
public X500Principal(InputStream is) {
if (is == null) {
throw new NullPointerException("provided null input stream");
}
try {
if (is.markSupported())
is.mark(is.available() + 1);
DerValue der = new DerValue(is);
thisX500Name = new X500Name(der.data);
} catch (Exception e) {
if (is.markSupported()) {
try {
is.reset();
} catch (IOException ioe) {
IllegalArgumentException iae = new IllegalArgumentException
("improperly specified input stream " +
("and unable to reset input stream"));
iae.initCause(e);
throw iae;
}
}
IllegalArgumentException iae = new IllegalArgumentException
("improperly specified input stream");
iae.initCause(e);
throw iae;
}
}
/** {@collect.stats}
* Returns a string representation of the X.500 distinguished name using
* the format defined in RFC 2253.
*
* <p>This method is equivalent to calling
* <code>getName(X500Principal.RFC2253)</code>.
*
* @return the distinguished name of this <code>X500Principal</code>
*/
public String getName() {
return getName(X500Principal.RFC2253);
}
/** {@collect.stats}
* Returns a string representation of the X.500 distinguished name
* using the specified format. Valid values for the format are
* "RFC1779", "RFC2253", and "CANONICAL" (case insensitive).
*
* <p> If "RFC1779" is specified as the format,
* this method emits the attribute type keywords defined in
* RFC 1779 (CN, L, ST, O, OU, C, STREET).
* Any other attribute type is emitted as an OID.
*
* <p> If "RFC2253" is specified as the format,
* this method emits the attribute type keywords defined in
* RFC 2253 (CN, L, ST, O, OU, C, STREET, DC, UID).
* Any other attribute type is emitted as an OID.
* Under a strict reading, RFC 2253 only specifies a UTF-8 string
* representation. The String returned by this method is the
* Unicode string achieved by decoding this UTF-8 representation.
*
* <p> If "CANONICAL" is specified as the format,
* this method returns an RFC 2253 conformant string representation
* with the following additional canonicalizations:
*
* <p><ol>
* <li> Leading zeros are removed from attribute types
* that are encoded as dotted decimal OIDs
* <li> DirectoryString attribute values of type
* PrintableString and UTF8String are not
* output in hexadecimal format
* <li> DirectoryString attribute values of types
* other than PrintableString and UTF8String
* are output in hexadecimal format
* <li> Leading and trailing white space characters
* are removed from non-hexadecimal attribute values
* (unless the value consists entirely of white space characters)
* <li> Internal substrings of one or more white space characters are
* converted to a single space in non-hexadecimal
* attribute values
* <li> Relative Distinguished Names containing more than one
* Attribute Value Assertion (AVA) are output in the
* following order: an alphabetical ordering of AVAs
* containing standard keywords, followed by a numeric
* ordering of AVAs containing OID keywords.
* <li> The only characters in attribute values that are escaped are
* those which section 2.4 of RFC 2253 states must be escaped
* (they are escaped using a preceding backslash character)
* <li> The entire name is converted to upper case
* using <code>String.toUpperCase(Locale.US)</code>
* <li> The entire name is converted to lower case
* using <code>String.toLowerCase(Locale.US)</code>
* <li> The name is finally normalized using normalization form KD,
* as described in the Unicode Standard and UAX #15
* </ol>
*
* <p> Additional standard formats may be introduced in the future.
*
* @param format the format to use
*
* @return a string representation of this <code>X500Principal</code>
* using the specified format
* @throws IllegalArgumentException if the specified format is invalid
* or null
*/
public String getName(String format) {
if (format != null) {
if (format.equalsIgnoreCase(RFC1779)) {
return thisX500Name.getRFC1779Name();
} else if (format.equalsIgnoreCase(RFC2253)) {
return thisX500Name.getRFC2253Name();
} else if (format.equalsIgnoreCase(CANONICAL)) {
return thisX500Name.getRFC2253CanonicalName();
}
}
throw new IllegalArgumentException("invalid format specified");
}
/** {@collect.stats}
* Returns a string representation of the X.500 distinguished name
* using the specified format. Valid values for the format are
* "RFC1779" and "RFC2253" (case insensitive). "CANONICAL" is not
* permitted and an <code>IllegalArgumentException</code> will be thrown.
*
* <p>This method returns Strings in the format as specified in
* {@link #getName(String)} and also emits additional attribute type
* keywords for OIDs that have entries in the <code>oidMap</code>
* parameter. OID entries in the oidMap take precedence over the default
* OIDs recognized by <code>getName(String)</code>.
* Improperly specified OIDs are ignored; however if an OID
* in the name maps to an improperly specified keyword, an
* <code>IllegalArgumentException</code> is thrown.
*
* <p> Additional standard formats may be introduced in the future.
*
* <p> Warning: additional attribute type keywords may not be recognized
* by other implementations; therefore do not use this method if
* you are unsure if these keywords will be recognized by other
* implementations.
*
* @param format the format to use
* @param oidMap an OID map, where each key is an object identifier in
* String form (a sequence of nonnegative integers separated by periods)
* that maps to a corresponding attribute type keyword String.
* The map may be empty but never <code>null</code>.
* @return a string representation of this <code>X500Principal</code>
* using the specified format
* @throws IllegalArgumentException if the specified format is invalid,
* null, or an OID in the name maps to an improperly specified keyword
* @throws NullPointerException if <code>oidMap</code> is <code>null</code>
* @since 1.6
*/
public String getName(String format, Map<String, String> oidMap) {
if (oidMap == null) {
throw new NullPointerException
(sun.security.util.ResourcesMgr.getString
("provided null OID map"));
}
if (format != null) {
if (format.equalsIgnoreCase(RFC1779)) {
return thisX500Name.getRFC1779Name(oidMap);
} else if (format.equalsIgnoreCase(RFC2253)) {
return thisX500Name.getRFC2253Name(oidMap);
}
}
throw new IllegalArgumentException("invalid format specified");
}
/** {@collect.stats}
* Returns the distinguished name in ASN.1 DER encoded form. The ASN.1
* notation for this structure is supplied in the documentation for
* {@link #X500Principal(byte[] name) X500Principal(byte[] name)}.
*
* <p>Note that the byte array returned is cloned to protect against
* subsequent modifications.
*
* @return a byte array containing the distinguished name in ASN.1 DER
* encoded form
*/
public byte[] getEncoded() {
try {
return thisX500Name.getEncoded();
} catch (IOException e) {
throw new RuntimeException("unable to get encoding", e);
}
}
/** {@collect.stats}
* Return a user-friendly string representation of this
* <code>X500Principal</code>.
*
* @return a string representation of this <code>X500Principal</code>
*/
public String toString() {
return thisX500Name.toString();
}
/** {@collect.stats}
* Compares the specified <code>Object</code> with this
* <code>X500Principal</code> for equality.
*
* <p> Specifically, this method returns <code>true</code> if
* the <code>Object</code> <i>o</i> is an <code>X500Principal</code>
* and if the respective canonical string representations
* (obtained via the <code>getName(X500Principal.CANONICAL)</code> method)
* of this object and <i>o</i> are equal.
*
* <p> This implementation is compliant with the requirements of RFC 3280.
*
* @param o Object to be compared for equality with this
* <code>X500Principal</code>
*
* @return <code>true</code> if the specified <code>Object</code> is equal
* to this <code>X500Principal</code>, <code>false</code> otherwise
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof X500Principal == false) {
return false;
}
X500Principal other = (X500Principal)o;
return this.thisX500Name.equals(other.thisX500Name);
}
/** {@collect.stats}
* Return a hash code for this <code>X500Principal</code>.
*
* <p> The hash code is calculated via:
* <code>getName(X500Principal.CANONICAL).hashCode()</code>
*
* @return a hash code for this <code>X500Principal</code>
*/
public int hashCode() {
return thisX500Name.hashCode();
}
/** {@collect.stats}
* Save the X500Principal object to a stream.
*
* @serialData this <code>X500Principal</code> is serialized
* by writing out its DER-encoded form
* (the value of <code>getEncoded</code> is serialized).
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
s.writeObject(thisX500Name.getEncodedInternal());
}
/** {@collect.stats}
* Reads this object from a stream (i.e., deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException,
java.io.NotActiveException,
ClassNotFoundException {
// re-create thisX500Name
thisX500Name = new X500Name((byte[])s.readObject());
}
}
|
Java
|
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
/** {@collect.stats}
* Signals that a <code>destroy</code> operation failed.
*
* <p> This exception is thrown by credentials implementing
* the <code>Destroyable</code> interface when the <code>destroy</code>
* method fails.
*
*/
public class DestroyFailedException extends Exception {
private static final long serialVersionUID = -7790152857282749162L;
/** {@collect.stats}
* Constructs a DestroyFailedException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public DestroyFailedException() {
super();
}
/** {@collect.stats}
* Constructs a DestroyFailedException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public DestroyFailedException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.io.*;
import java.util.Date;
import java.util.Arrays;
import java.net.InetAddress;
import javax.crypto.SecretKey;
import javax.security.auth.Refreshable;
import javax.security.auth.Destroyable;
import javax.security.auth.RefreshFailedException;
import javax.security.auth.DestroyFailedException;
import sun.misc.HexDumpEncoder;
import sun.security.krb5.EncryptionKey;
import sun.security.krb5.Asn1Exception;
import sun.security.util.*;
/** {@collect.stats}
* This class encapsulates a Kerberos ticket and associated
* information as viewed from the client's point of view. It captures all
* information that the Key Distribution Center (KDC) sends to the client
* in the reply message KDC-REP defined in the Kerberos Protocol
* Specification (<a href=http://www.ietf.org/rfc/rfc4120.txt>RFC 4120</a>).
* <p>
* All Kerberos JAAS login modules that authenticate a user to a KDC should
* use this class. Where available, the login module might even read this
* information from a ticket cache in the operating system instead of
* directly communicating with the KDC. During the commit phase of the JAAS
* authentication process, the JAAS login module should instantiate this
* class and store the instance in the private credential set of a
* {@link javax.security.auth.Subject Subject}.<p>
*
* It might be necessary for the application to be granted a
* {@link javax.security.auth.PrivateCredentialPermission
* PrivateCredentialPermission} if it needs to access a KerberosTicket
* instance from a Subject. This permission is not needed when the
* application depends on the default JGSS Kerberos mechanism to access the
* KerberosTicket. In that case, however, the application will need an
* appropriate
* {@link javax.security.auth.kerberos.ServicePermission ServicePermission}.
* <p>
* Note that this class is applicable to both ticket granting tickets and
* other regular service tickets. A ticket granting ticket is just a
* special case of a more generalized service ticket.
*
* @see javax.security.auth.Subject
* @see javax.security.auth.PrivateCredentialPermission
* @see javax.security.auth.login.LoginContext
* @see org.ietf.jgss.GSSCredential
* @see org.ietf.jgss.GSSManager
*
* @author Mayank Upadhyay
* @since 1.4
*/
public class KerberosTicket implements Destroyable, Refreshable,
java.io.Serializable {
private static final long serialVersionUID = 7395334370157380539L;
// XXX Make these flag indices public
private static final int FORWARDABLE_TICKET_FLAG = 1;
private static final int FORWARDED_TICKET_FLAG = 2;
private static final int PROXIABLE_TICKET_FLAG = 3;
private static final int PROXY_TICKET_FLAG = 4;
private static final int POSTDATED_TICKET_FLAG = 6;
private static final int RENEWABLE_TICKET_FLAG = 8;
private static final int INITIAL_TICKET_FLAG = 9;
private static final int NUM_FLAGS = 32;
/** {@collect.stats}
*
* ASN.1 DER Encoding of the Ticket as defined in the
* Kerberos Protocol Specification RFC4120.
*
* @serial
*/
private byte[] asn1Encoding;
/** {@collect.stats}
*<code>KeyImpl</code> is serialized by writing out the ASN1 Encoded bytes
* of the encryption key. The ASN1 encoding is defined in RFC4120 and as
* follows:
* <pre>
* EncryptionKey ::= SEQUENCE {
* keytype [0] Int32 -- actually encryption type --,
* keyvalue [1] OCTET STRING
* }
* </pre>
*
* @serial
*/
private KeyImpl sessionKey;
/** {@collect.stats}
*
* Ticket Flags as defined in the Kerberos Protocol Specification RFC4120.
*
* @serial
*/
private boolean[] flags;
/** {@collect.stats}
*
* Time of initial authentication
*
* @serial
*/
private Date authTime;
/** {@collect.stats}
*
* Time after which the ticket is valid.
* @serial
*/
private Date startTime;
/** {@collect.stats}
*
* Time after which the ticket will not be honored. (its expiration time).
*
* @serial
*/
private Date endTime;
/** {@collect.stats}
*
* For renewable Tickets it indicates the maximum endtime that may be
* included in a renewal. It can be thought of as the absolute expiration
* time for the ticket, including all renewals. This field may be null
* for tickets that are not renewable.
*
* @serial
*/
private Date renewTill;
/** {@collect.stats}
*
* Client that owns the service ticket
*
* @serial
*/
private KerberosPrincipal client;
/** {@collect.stats}
*
* The service for which the ticket was issued.
*
* @serial
*/
private KerberosPrincipal server;
/** {@collect.stats}
*
* The addresses from where the ticket may be used by the client.
* This field may be null when the ticket is usable from any address.
*
* @serial
*/
private InetAddress[] clientAddresses;
private transient boolean destroyed = false;
/** {@collect.stats}
* Constructs a KerberosTicket using credentials information that a
* client either receives from a KDC or reads from a cache.
*
* @param asn1Encoding the ASN.1 encoding of the ticket as defined by
* the Kerberos protocol specification.
* @param client the client that owns this service
* ticket
* @param server the service that this ticket is for
* @param sessionKey the raw bytes for the session key that must be
* used to encrypt the authenticator that will be sent to the server
* @param keyType the key type for the session key as defined by the
* Kerberos protocol specification.
* @param flags the ticket flags. Each element in this array indicates
* the value for the corresponding bit in the ASN.1 BitString that
* represents the ticket flags. If the number of elements in this array
* is less than the number of flags used by the Kerberos protocol,
* then the missing flags will be filled in with false.
* @param authTime the time of initial authentication for the client
* @param startTime the time after which the ticket will be valid. This
* may be null in which case the value of authTime is treated as the
* startTime.
* @param endTime the time after which the ticket will no longer be
* valid
* @param renewTill an absolute expiration time for the ticket,
* including all renewal that might be possible. This field may be null
* for tickets that are not renewable.
* @param clientAddresses the addresses from where the ticket may be
* used by the client. This field may be null when the ticket is usable
* from any address.
*/
public KerberosTicket(byte[] asn1Encoding,
KerberosPrincipal client,
KerberosPrincipal server,
byte[] sessionKey,
int keyType,
boolean[] flags,
Date authTime,
Date startTime,
Date endTime,
Date renewTill,
InetAddress[] clientAddresses) {
init(asn1Encoding, client, server, sessionKey, keyType, flags,
authTime, startTime, endTime, renewTill, clientAddresses);
}
private void init(byte[] asn1Encoding,
KerberosPrincipal client,
KerberosPrincipal server,
byte[] sessionKey,
int keyType,
boolean[] flags,
Date authTime,
Date startTime,
Date endTime,
Date renewTill,
InetAddress[] clientAddresses) {
if (asn1Encoding == null)
throw new IllegalArgumentException("ASN.1 encoding of ticket"
+ " cannot be null");
this.asn1Encoding = asn1Encoding.clone();
if (client == null)
throw new IllegalArgumentException("Client name in ticket"
+ " cannot be null");
this.client = client;
if (server == null)
throw new IllegalArgumentException("Server name in ticket"
+ " cannot be null");
this.server = server;
if (sessionKey == null)
throw new IllegalArgumentException("Session key for ticket"
+ " cannot be null");
this.sessionKey = new KeyImpl(sessionKey, keyType);
if (flags != null) {
if (flags.length >= NUM_FLAGS)
this.flags = (boolean[]) flags.clone();
else {
this.flags = new boolean[NUM_FLAGS];
// Fill in whatever we have
for (int i = 0; i < flags.length; i++)
this.flags[i] = flags[i];
}
} else
this.flags = new boolean[NUM_FLAGS];
if (this.flags[RENEWABLE_TICKET_FLAG]) {
if (renewTill == null)
throw new IllegalArgumentException("The renewable period "
+ "end time cannot be null for renewable tickets.");
this.renewTill = renewTill;
}
this.authTime = authTime;
this.startTime = (startTime != null? startTime: authTime);
if (endTime == null)
throw new IllegalArgumentException("End time for ticket validity"
+ " cannot be null");
this.endTime = endTime;
if (clientAddresses != null)
this.clientAddresses = (InetAddress[]) clientAddresses.clone();
}
/** {@collect.stats}
* Returns the client principal associated with this ticket.
*
* @return the client principal.
*/
public final KerberosPrincipal getClient() {
return client;
}
/** {@collect.stats}
* Returns the service principal associated with this ticket.
*
* @return the service principal.
*/
public final KerberosPrincipal getServer() {
return server;
}
/** {@collect.stats}
* Returns the session key associated with this ticket.
*
* @return the session key.
*/
public final SecretKey getSessionKey() {
if (destroyed)
throw new IllegalStateException("This ticket is no longer valid");
return sessionKey;
}
/** {@collect.stats}
* Returns the key type of the session key associated with this
* ticket as defined by the Kerberos Protocol Specification.
*
* @return the key type of the session key associated with this
* ticket.
*
* @see #getSessionKey()
*/
public final int getSessionKeyType() {
if (destroyed)
throw new IllegalStateException("This ticket is no longer valid");
return sessionKey.getKeyType();
}
/** {@collect.stats}
* Determines if this ticket is forwardable.
*
* @return true if this ticket is forwardable, false if not.
*/
public final boolean isForwardable() {
return flags[FORWARDABLE_TICKET_FLAG];
}
/** {@collect.stats}
* Determines if this ticket had been forwarded or was issued based on
* authentication involving a forwarded ticket-granting ticket.
*
* @return true if this ticket had been forwarded or was issued based on
* authentication involving a forwarded ticket-granting ticket,
* false otherwise.
*/
public final boolean isForwarded() {
return flags[FORWARDED_TICKET_FLAG];
}
/** {@collect.stats}
* Determines if this ticket is proxiable.
*
* @return true if this ticket is proxiable, false if not.
*/
public final boolean isProxiable() {
return flags[PROXIABLE_TICKET_FLAG];
}
/** {@collect.stats}
* Determines is this ticket is a proxy-ticket.
*
* @return true if this ticket is a proxy-ticket, false if not.
*/
public final boolean isProxy() {
return flags[PROXY_TICKET_FLAG];
}
/** {@collect.stats}
* Determines is this ticket is post-dated.
*
* @return true if this ticket is post-dated, false if not.
*/
public final boolean isPostdated() {
return flags[POSTDATED_TICKET_FLAG];
}
/** {@collect.stats}
* Determines is this ticket is renewable. If so, the {@link #refresh()
* refresh} method can be called, assuming the validity period for
* renewing is not already over.
*
* @return true if this ticket is renewable, false if not.
*/
public final boolean isRenewable() {
return flags[RENEWABLE_TICKET_FLAG];
}
/** {@collect.stats}
* Determines if this ticket was issued using the Kerberos AS-Exchange
* protocol, and not issued based on some ticket-granting ticket.
*
* @return true if this ticket was issued using the Kerberos AS-Exchange
* protocol, false if not.
*/
public final boolean isInitial() {
return flags[INITIAL_TICKET_FLAG];
}
/** {@collect.stats}
* Returns the flags associated with this ticket. Each element in the
* returned array indicates the value for the corresponding bit in the
* ASN.1 BitString that represents the ticket flags.
*
* @return the flags associated with this ticket.
*/
public final boolean[] getFlags() {
return (flags == null? null: (boolean[]) flags.clone());
}
/** {@collect.stats}
* Returns the time that the client was authenticated.
*
* @return the time that the client was authenticated
* or null if not set.
*/
public final java.util.Date getAuthTime() {
return (authTime == null) ? null : new Date(authTime.getTime());
}
/** {@collect.stats}
* Returns the start time for this ticket's validity period.
*
* @return the start time for this ticket's validity period
* or null if not set.
*/
public final java.util.Date getStartTime() {
return (startTime == null) ? null : new Date(startTime.getTime());
}
/** {@collect.stats}
* Returns the expiration time for this ticket's validity period.
*
* @return the expiration time for this ticket's validity period.
*/
public final java.util.Date getEndTime() {
return endTime;
}
/** {@collect.stats}
* Returns the latest expiration time for this ticket, including all
* renewals. This will return a null value for non-renewable tickets.
*
* @return the latest expiration time for this ticket.
*/
public final java.util.Date getRenewTill() {
return (renewTill == null) ? null: new Date(renewTill.getTime());
}
/** {@collect.stats}
* Returns a list of addresses from where the ticket can be used.
*
* @return ths list of addresses or null, if the field was not
* provided.
*/
public final java.net.InetAddress[] getClientAddresses() {
return (clientAddresses == null?
null: (InetAddress[]) clientAddresses.clone());
}
/** {@collect.stats}
* Returns an ASN.1 encoding of the entire ticket.
*
* @return an ASN.1 encoding of the entire ticket.
*/
public final byte[] getEncoded() {
if (destroyed)
throw new IllegalStateException("This ticket is no longer valid");
return (byte[]) asn1Encoding.clone();
}
/** {@collect.stats} Determines if this ticket is still current. */
public boolean isCurrent() {
return (System.currentTimeMillis() <= getEndTime().getTime());
}
/** {@collect.stats}
* Extends the validity period of this ticket. The ticket will contain
* a new session key if the refresh operation succeeds. The refresh
* operation will fail if the ticket is not renewable or the latest
* allowable renew time has passed. Any other error returned by the
* KDC will also cause this method to fail.
*
* Note: This method is not synchronized with the the accessor
* methods of this object. Hence callers need to be aware of multiple
* threads that might access this and try to renew it at the same
* time.
*
* @throws RefreshFailedException if the ticket is not renewable, or
* the latest allowable renew time has passed, or the KDC returns some
* error.
*
* @see #isRenewable()
* @see #getRenewTill()
*/
public void refresh() throws RefreshFailedException {
if (destroyed)
throw new RefreshFailedException("A destroyed ticket "
+ "cannot be renewd.");
if (!isRenewable())
throw new RefreshFailedException("This ticket is not renewable");
if (System.currentTimeMillis() > getRenewTill().getTime())
throw new RefreshFailedException("This ticket is past "
+ "its last renewal time.");
Throwable e = null;
sun.security.krb5.Credentials krb5Creds = null;
try {
krb5Creds = new sun.security.krb5.Credentials(asn1Encoding,
client.toString(),
server.toString(),
sessionKey.getEncoded(),
sessionKey.getKeyType(),
flags,
authTime,
startTime,
endTime,
renewTill,
clientAddresses);
krb5Creds = krb5Creds.renew();
} catch (sun.security.krb5.KrbException krbException) {
e = krbException;
} catch (java.io.IOException ioException) {
e = ioException;
}
if (e != null) {
RefreshFailedException rfException
= new RefreshFailedException("Failed to renew Kerberos Ticket "
+ "for client " + client
+ " and server " + server
+ " - " + e.getMessage());
rfException.initCause(e);
throw rfException;
}
/*
* In case multiple threads try to refresh it at the same time.
*/
synchronized (this) {
try {
this.destroy();
} catch (DestroyFailedException dfException) {
// Squelch it since we don't care about the old ticket.
}
init(krb5Creds.getEncoded(),
new KerberosPrincipal(krb5Creds.getClient().getName()),
new KerberosPrincipal(krb5Creds.getServer().getName(),
KerberosPrincipal.KRB_NT_SRV_INST),
krb5Creds.getSessionKey().getBytes(),
krb5Creds.getSessionKey().getEType(),
krb5Creds.getFlags(),
krb5Creds.getAuthTime(),
krb5Creds.getStartTime(),
krb5Creds.getEndTime(),
krb5Creds.getRenewTill(),
krb5Creds.getClientAddresses());
destroyed = false;
}
}
/** {@collect.stats}
* Destroys the ticket and destroys any sensitive information stored in
* it.
*/
public void destroy() throws DestroyFailedException {
if (!destroyed) {
Arrays.fill(asn1Encoding, (byte) 0);
client = null;
server = null;
sessionKey.destroy();
flags = null;
authTime = null;
startTime = null;
endTime = null;
renewTill = null;
clientAddresses = null;
destroyed = true;
}
}
/** {@collect.stats}
* Determines if this ticket has been destroyed.
*/
public boolean isDestroyed() {
return destroyed;
}
public String toString() {
if (destroyed)
throw new IllegalStateException("This ticket is no longer valid");
StringBuffer caddrBuf = new StringBuffer();
if (clientAddresses != null) {
for (int i = 0; i < clientAddresses.length; i++) {
caddrBuf.append("clientAddresses[" + i + "] = " +
clientAddresses[i].toString());
}
}
return ("Ticket (hex) = " + "\n" +
(new HexDumpEncoder()).encodeBuffer(asn1Encoding) + "\n" +
"Client Principal = " + client.toString() + "\n" +
"Server Principal = " + server.toString() + "\n" +
"Session Key = " + sessionKey.toString() + "\n" +
"Forwardable Ticket " + flags[FORWARDABLE_TICKET_FLAG] + "\n" +
"Forwarded Ticket " + flags[FORWARDED_TICKET_FLAG] + "\n" +
"Proxiable Ticket " + flags[PROXIABLE_TICKET_FLAG] + "\n" +
"Proxy Ticket " + flags[PROXY_TICKET_FLAG] + "\n" +
"Postdated Ticket " + flags[POSTDATED_TICKET_FLAG] + "\n" +
"Renewable Ticket " + flags[RENEWABLE_TICKET_FLAG] + "\n" +
"Initial Ticket " + flags[RENEWABLE_TICKET_FLAG] + "\n" +
"Auth Time = " + String.valueOf(authTime) + "\n" +
"Start Time = " + String.valueOf(startTime) + "\n" +
"End Time = " + endTime.toString() + "\n" +
"Renew Till = " + String.valueOf(renewTill) + "\n" +
"Client Addresses " +
(clientAddresses == null ? " Null " : caddrBuf.toString() +
"\n"));
}
/** {@collect.stats}
* Returns a hashcode for this KerberosTicket.
*
* @return a hashCode() for the <code>KerberosTicket</code>
* @since 1.6
*/
public int hashCode() {
int result = 17;
if (isDestroyed()) {
return result;
}
result = result * 37 + Arrays.hashCode(getEncoded());
result = result * 37 + endTime.hashCode();
result = result * 37 + client.hashCode();
result = result * 37 + server.hashCode();
result = result * 37 + sessionKey.hashCode();
// authTime may be null
if (authTime != null) {
result = result * 37 + authTime.hashCode();
}
// startTime may be null
if (startTime != null) {
result = result * 37 + startTime.hashCode();
}
// renewTill may be null
if (renewTill != null) {
result = result * 37 + renewTill.hashCode();
}
// clientAddress may be null, the array's hashCode is 0
result = result * 37 + Arrays.hashCode(clientAddresses);
return result * 37 + Arrays.hashCode(flags);
}
/** {@collect.stats}
* Compares the specified Object with this KerberosTicket for equality.
* Returns true if the given object is also a
* <code>KerberosTicket</code> and the two
* <code>KerberosTicket</code> instances are equivalent.
*
* @param other the Object to compare to
* @return true if the specified object is equal to this KerberosTicket,
* false otherwise. NOTE: Returns false if either of the KerberosTicket
* objects has been destroyed.
* @since 1.6
*/
public boolean equals(Object other) {
if (other == this)
return true;
if (! (other instanceof KerberosTicket)) {
return false;
}
KerberosTicket otherTicket = ((KerberosTicket) other);
if (isDestroyed() || otherTicket.isDestroyed()) {
return false;
}
if (!Arrays.equals(getEncoded(), otherTicket.getEncoded()) ||
!endTime.equals(otherTicket.getEndTime()) ||
!server.equals(otherTicket.getServer()) ||
!client.equals(otherTicket.getClient()) ||
!sessionKey.equals(otherTicket.getSessionKey()) ||
!Arrays.equals(clientAddresses, otherTicket.getClientAddresses()) ||
!Arrays.equals(flags, otherTicket.getFlags())) {
return false;
}
// authTime may be null
if (authTime == null) {
if (otherTicket.getAuthTime() != null)
return false;
} else {
if (!authTime.equals(otherTicket.getAuthTime()))
return false;
}
// startTime may be null
if (startTime == null) {
if (otherTicket.getStartTime() != null)
return false;
} else {
if (!startTime.equals(otherTicket.getStartTime()))
return false;
}
if (renewTill == null) {
if (otherTicket.getRenewTill() != null)
return false;
} else {
if (!renewTill.equals(otherTicket.getRenewTill()))
return false;
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.util.*;
import java.security.Permission;
import java.security.BasicPermission;
import java.security.PermissionCollection;
import java.io.ObjectStreamField;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* This class is used to restrict the usage of the Kerberos
* delegation model, ie: forwardable and proxiable tickets.
* <p>
* The target name of this <code>Permission</code> specifies a pair of
* kerberos service principals. The first is the subordinate service principal
* being entrusted to use the TGT. The second service principal designates
* the target service the subordinate service principal is to
* interact with on behalf of the initiating KerberosPrincipal. This
* latter service principal is specified to restrict the use of a
* proxiable ticket.
* <p>
* For example, to specify the "host" service use of a forwardable TGT the
* target permission is specified as follows:
* <p>
* <pre>
* DelegationPermission("\"host/foo.example.com@EXAMPLE.COM\" \"krbtgt/EXAMPLE.COM@EXAMPLE.COM\"");
* </pre>
* <p>
* To give the "backup" service a proxiable nfs service ticket the target permission
* might be specified:
* <p>
* <pre>
* DelegationPermission("\"backup/bar.example.com@EXAMPLE.COM\" \"nfs/home.EXAMPLE.COM@EXAMPLE.COM\"");
* </pre>
*
* @since 1.4
*/
public final class DelegationPermission extends BasicPermission
implements java.io.Serializable {
private static final long serialVersionUID = 883133252142523922L;
private transient String subordinate, service;
/** {@collect.stats}
* Create a new <code>DelegationPermission</code>
* with the specified subordinate and target principals.
*
* <p>
*
* @param principals the name of the subordinate and target principals
*
* @throws NullPointerException if <code>principals</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>principals</code> is empty.
*/
public DelegationPermission(String principals) {
super(principals);
init(principals);
}
/** {@collect.stats}
* Create a new <code>DelegationPermission</code>
* with the specified subordinate and target principals.
* <p>
*
* @param principals the name of the subordinate and target principals
* <p>
* @param actions should be null.
*
* @throws NullPointerException if <code>principals</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>principals</code> is empty.
*/
public DelegationPermission(String principals, String actions) {
super(principals, actions);
init(principals);
}
/** {@collect.stats}
* Initialize the DelegationPermission object.
*/
private void init(String target) {
StringTokenizer t = null;
if (!target.startsWith("\"")) {
throw new IllegalArgumentException
("service principal [" + target +
"] syntax invalid: " +
"improperly quoted");
} else {
t = new StringTokenizer(target, "\"", false);
subordinate = t.nextToken();
if (t.countTokens() == 2) {
t.nextToken(); // bypass whitespace
service = t.nextToken();
} else if (t.countTokens() > 0) {
throw new IllegalArgumentException
("service principal [" + t.nextToken() +
"] syntax invalid: " +
"improperly quoted");
}
}
}
/** {@collect.stats}
* Checks if this Kerberos delegation permission object "implies" the
* specified permission.
* <P>
* If none of the above are true, <code>implies</code> returns false.
* @param p the permission to check against.
*
* @return true if the specified permission is implied by this object,
* false if not.
*/
public boolean implies(Permission p) {
if (!(p instanceof DelegationPermission))
return false;
DelegationPermission that = (DelegationPermission) p;
if (this.subordinate.equals(that.subordinate) &&
this.service.equals(that.service))
return true;
return false;
}
/** {@collect.stats}
* Checks two DelegationPermission objects for equality.
* <P>
* @param obj the object to test for equality with this object.
*
* @return true if <i>obj</i> is a DelegationPermission, and
* has the same subordinate and service principal as this.
* DelegationPermission object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof DelegationPermission))
return false;
DelegationPermission that = (DelegationPermission) obj;
return implies(that);
}
/** {@collect.stats}
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return getName().hashCode();
}
/** {@collect.stats}
* Returns a PermissionCollection object for storing
* DelegationPermission objects.
* <br>
* DelegationPermission objects must be stored in a manner that
* allows them to be inserted into the collection in any order, but
* that also enables the PermissionCollection implies method to
* be implemented in an efficient (and consistent) manner.
*
* @return a new PermissionCollection object suitable for storing
* DelegationPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new KrbDelegationPermissionCollection();
}
/** {@collect.stats}
* WriteObject is called to save the state of the DelegationPermission
* to a stream. The actions are serialized, and the superclass
* takes care of the name.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
}
/** {@collect.stats}
* readObject is called to restore the state of the
* DelegationPermission from a stream.
*/
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getName());
}
/*
public static void main(String args[]) throws Exception {
DelegationPermission this_ =
new DelegationPermission(args[0]);
DelegationPermission that_ =
new DelegationPermission(args[1]);
System.out.println("-----\n");
System.out.println("this.implies(that) = " + this_.implies(that_));
System.out.println("-----\n");
System.out.println("this = "+this_);
System.out.println("-----\n");
System.out.println("that = "+that_);
System.out.println("-----\n");
KrbDelegationPermissionCollection nps =
new KrbDelegationPermissionCollection();
nps.add(this_);
nps.add(new DelegationPermission("\"host/foo.example.com@EXAMPLE.COM\" \"CN=Gary Ellison/OU=JSN/O=SUNW/L=Palo Alto/ST=CA/C=US\""));
try {
nps.add(new DelegationPermission("host/foo.example.com@EXAMPLE.COM \"CN=Gary Ellison/OU=JSN/O=SUNW/L=Palo Alto/ST=CA/C=US\""));
} catch (Exception e) {
System.err.println(e);
}
System.out.println("nps.implies(that) = " + nps.implies(that_));
System.out.println("-----\n");
Enumeration e = nps.elements();
while (e.hasMoreElements()) {
DelegationPermission x =
(DelegationPermission) e.nextElement();
System.out.println("nps.e = " + x);
}
}
*/
}
final class KrbDelegationPermissionCollection extends PermissionCollection
implements java.io.Serializable {
// Not serialized; see serialization section at end of class.
private transient List<Permission> perms;
public KrbDelegationPermissionCollection() {
perms = new ArrayList<Permission>();
}
/** {@collect.stats}
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
public boolean implies(Permission permission) {
if (! (permission instanceof DelegationPermission))
return false;
synchronized (this) {
for (Permission x : perms) {
if (x.implies(permission))
return true;
}
}
return false;
}
/** {@collect.stats}
* Adds a permission to the DelegationPermissions. The key for
* the hash is the name.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* DelegationPermission
*
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof DelegationPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
synchronized (this) {
perms.add(0, permission);
}
}
/** {@collect.stats}
* Returns an enumeration of all the DelegationPermission objects
* in the container.
*
* @return an enumeration of all the DelegationPermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
return Collections.enumeration(perms);
}
}
private static final long serialVersionUID = -3383936936589966948L;
// Need to maintain serialization interoperability with earlier releases,
// which had the serializable field:
// private Vector permissions;
/** {@collect.stats}
* @serialField permissions java.util.Vector
* A list of DelegationPermission objects.
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("permissions", Vector.class),
};
/** {@collect.stats}
* @serialData "permissions" field (a Vector containing the DelegationPermissions).
*/
/*
* Writes the contents of the perms field out as a Vector for
* serialization compatibility with earlier releases.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Don't call out.defaultWriteObject()
// Write out Vector
Vector<Permission> permissions = new Vector<Permission>(perms.size());
synchronized (this) {
permissions.addAll(perms);
}
ObjectOutputStream.PutField pfields = out.putFields();
pfields.put("permissions", permissions);
out.writeFields();
}
/*
* Reads in a Vector of DelegationPermissions and saves them in the perms field.
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get the one we want
Vector<Permission> permissions =
(Vector<Permission>)gfields.get("permissions", null);
perms = new ArrayList<Permission>(permissions.size());
perms.addAll(permissions);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.io.*;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.security.auth.Destroyable;
import javax.security.auth.DestroyFailedException;
import sun.misc.HexDumpEncoder;
import sun.security.krb5.Asn1Exception;
import sun.security.krb5.PrincipalName;
import sun.security.krb5.EncryptionKey;
import sun.security.krb5.EncryptedData;
import sun.security.krb5.KrbException;
import sun.security.krb5.KrbCryptoException;
import sun.security.util.DerValue;
/** {@collect.stats}
* This class encapsulates a Kerberos encryption key. It is not associated
* with a principal and may represent an ephemeral session key.
*
* @author Mayank Upadhyay
* @since 1.4
*
* @serial include
*/
class KeyImpl implements SecretKey, Destroyable, Serializable {
private static final long serialVersionUID = -7889313790214321193L;
private transient byte[] keyBytes;
private transient int keyType;
private transient volatile boolean destroyed = false;
/** {@collect.stats}
* Constructs a KeyImpl from the given bytes.
*
* @param keyBytes the raw bytes for the secret key
* @param keyType the key type for the secret key as defined by the
* Kerberos protocol specification.
*/
public KeyImpl(byte[] keyBytes,
int keyType) {
this.keyBytes = (byte[]) keyBytes.clone();
this.keyType = keyType;
}
/** {@collect.stats}
* Constructs a KeyImpl from a password.
*
* @param principal the principal from which to derive the salt
* @param password the password that should be used to compute the
* key.
* @param algorithm the name for the algorithm that this key wil be
* used for. This parameter may be null in which case "DES" will be
* assumed.
*/
public KeyImpl(KerberosPrincipal principal,
char[] password,
String algorithm) {
try {
PrincipalName princ = new PrincipalName(principal.getName());
EncryptionKey key =
new EncryptionKey(password, princ.getSalt(), algorithm);
this.keyBytes = key.getBytes();
this.keyType = key.getEType();
} catch (KrbException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/** {@collect.stats}
* Returns the keyType for this key as defined in the Kerberos Spec.
*/
public final int getKeyType() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return keyType;
}
/*
* Methods from java.security.Key
*/
public final String getAlgorithm() {
return getAlgorithmName(keyType);
}
private String getAlgorithmName(int eType) {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
switch (eType) {
case EncryptedData.ETYPE_DES_CBC_CRC:
case EncryptedData.ETYPE_DES_CBC_MD5:
return "DES";
case EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD:
return "DESede";
case EncryptedData.ETYPE_ARCFOUR_HMAC:
return "ArcFourHmac";
case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
return "AES128";
case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
return "AES256";
case EncryptedData.ETYPE_NULL:
return "NULL";
default:
throw new IllegalArgumentException(
"Unsupported encryption type: " + eType);
}
}
public final String getFormat() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return "RAW";
}
public final byte[] getEncoded() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return (byte[])keyBytes.clone();
}
public void destroy() throws DestroyFailedException {
if (!destroyed) {
destroyed = true;
Arrays.fill(keyBytes, (byte) 0);
}
}
public boolean isDestroyed() {
return destroyed;
}
/** {@collect.stats}
* @serialData this <code>KeyImpl</code> is serialized by
* writing out the ASN1 Encoded bytes of the encryption key.
* The ASN1 encoding is defined in RFC4120 and as follows:
* EncryptionKey ::= SEQUENCE {
* keytype [0] Int32 -- actually encryption type --,
* keyvalue [1] OCTET STRING
* }
*/
private void writeObject(ObjectOutputStream ois)
throws IOException {
if (destroyed) {
throw new IOException("This key is no longer valid");
}
try {
ois.writeObject((new EncryptionKey(keyType, keyBytes)).asn1Encode());
} catch (Asn1Exception ae) {
throw new IOException(ae.getMessage());
}
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
try {
EncryptionKey encKey = new EncryptionKey(new
DerValue((byte[])ois.readObject()));
keyType = encKey.getEType();
keyBytes = encKey.getBytes();
} catch (Asn1Exception ae) {
throw new IOException(ae.getMessage());
}
}
public String toString() {
HexDumpEncoder hd = new HexDumpEncoder();
return "EncryptionKey: keyType=" + keyType
+ " keyBytes (hex dump)="
+ (keyBytes == null || keyBytes.length == 0 ?
" Empty Key" :
'\n' + hd.encode(keyBytes)
+ '\n');
}
public int hashCode() {
int result = 17;
if(isDestroyed()) {
return result;
}
result = 37 * result + Arrays.hashCode(keyBytes);
return 37 * result + keyType;
}
public boolean equals(Object other) {
if (other == this)
return true;
if (! (other instanceof KeyImpl)) {
return false;
}
KeyImpl otherKey = ((KeyImpl) other);
if (isDestroyed() || otherKey.isDestroyed()) {
return false;
}
if(keyType != otherKey.getKeyType() ||
!Arrays.equals(keyBytes, otherKey.getEncoded())) {
return false;
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.security.auth.Destroyable;
import javax.security.auth.DestroyFailedException;
/** {@collect.stats}
* This class encapsulates a long term secret key for a Kerberos
* principal.<p>
*
* All Kerberos JAAS login modules that obtain a principal's password and
* generate the secret key from it should use this class. Where available,
* the login module might even read this secret key directly from a
* Kerberos "keytab". Sometimes, such as when authenticating a server in
* the absence of user-to-user authentication, the login module will store
* an instance of this class in the private credential set of a
* {@link javax.security.auth.Subject Subject} during the commit phase of the
* authentication process.<p>
*
* It might be necessary for the application to be granted a
* {@link javax.security.auth.PrivateCredentialPermission
* PrivateCredentialPermission} if it needs to access the KerberosKey
* instance from a Subject. This permission is not needed when the
* application depends on the default JGSS Kerberos mechanism to access the
* KerberosKey. In that case, however, the application will need an
* appropriate
* {@link javax.security.auth.kerberos.ServicePermission ServicePermission}.
*
* @author Mayank Upadhyay
* @since 1.4
*/
public class KerberosKey implements SecretKey, Destroyable {
private static final long serialVersionUID = -4625402278148246993L;
/** {@collect.stats}
* The principal that this secret key belongs to.
*
* @serial
*/
private KerberosPrincipal principal;
/** {@collect.stats}
* the version number of this secret key
*
* @serial
*/
private int versionNum;
/** {@collect.stats}
* <code>KeyImpl</code> is serialized by writing out the ASN1 Encoded bytes
* of the encryption key.
* The ASN1 encoding is defined in RFC4120 and as follows:
* <pre>
* EncryptionKey ::= SEQUENCE {
* keytype [0] Int32 -- actually encryption type --,
* keyvalue [1] OCTET STRING
* }
* </pre>
*
* @serial
*/
private KeyImpl key;
private transient boolean destroyed = false;
/** {@collect.stats}
* Constructs a KerberosKey from the given bytes when the key type and
* key version number are known. This can be used when reading the secret
* key information from a Kerberos "keytab".
*
* @param principal the principal that this secret key belongs to
* @param keyBytes the raw bytes for the secret key
* @param keyType the key type for the secret key as defined by the
* Kerberos protocol specification.
* @param versionNum the version number of this secret key
*/
public KerberosKey(KerberosPrincipal principal,
byte[] keyBytes,
int keyType,
int versionNum) {
this.principal = principal;
this.versionNum = versionNum;
key = new KeyImpl(keyBytes, keyType);
}
/** {@collect.stats}
* Constructs a KerberosKey from a principal's password.
*
* @param principal the principal that this password belongs to
* @param password the password that should be used to compute the key
* @param algorithm the name for the algorithm that this key will be
* used for. This parameter may be null in which case the default
* algorithm "DES" will be assumed.
* @throws IllegalArgumentException if the name of the
* algorithm passed is unsupported.
*/
public KerberosKey(KerberosPrincipal principal,
char[] password,
String algorithm) {
this.principal = principal;
// Pass principal in for salt
key = new KeyImpl(principal, password, algorithm);
}
/** {@collect.stats}
* Returns the principal that this key belongs to.
*
* @return the principal this key belongs to.
*/
public final KerberosPrincipal getPrincipal() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return principal;
}
/** {@collect.stats}
* Returns the key version number.
*
* @return the key version number.
*/
public final int getVersionNumber() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return versionNum;
}
/** {@collect.stats}
* Returns the key type for this long-term key.
*
* @return the key type.
*/
public final int getKeyType() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return key.getKeyType();
}
/*
* Methods from java.security.Key
*/
/** {@collect.stats}
* Returns the standard algorithm name for this key. For
* example, "DES" would indicate that this key is a DES key.
* See Appendix A in the <a href=
* "../../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference
* </a>
* for information about standard algorithm names.
*
* @return the name of the algorithm associated with this key.
*/
public final String getAlgorithm() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return key.getAlgorithm();
}
/** {@collect.stats}
* Returns the name of the encoding format for this secret key.
*
* @return the String "RAW"
*/
public final String getFormat() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return key.getFormat();
}
/** {@collect.stats}
* Returns the key material of this secret key.
*
* @return the key material
*/
public final byte[] getEncoded() {
if (destroyed)
throw new IllegalStateException("This key is no longer valid");
return key.getEncoded();
}
/** {@collect.stats}
* Destroys this key. A call to any of its other methods after this
* will cause an IllegalStateException to be thrown.
*
* @throws DestroyFailedException if some error occurs while destorying
* this key.
*/
public void destroy() throws DestroyFailedException {
if (!destroyed) {
key.destroy();
principal = null;
destroyed = true;
}
}
/** {@collect.stats} Determines if this key has been destroyed.*/
public boolean isDestroyed() {
return destroyed;
}
public String toString() {
if (destroyed) {
return "Destroyed Principal";
}
return "Kerberos Principal " + principal.toString() +
"Key Version " + versionNum +
"key " + key.toString();
}
/** {@collect.stats}
* Returns a hashcode for this KerberosKey.
*
* @return a hashCode() for the <code>KerberosKey</code>
* @since 1.6
*/
public int hashCode() {
int result = 17;
if (isDestroyed()) {
return result;
}
result = 37 * result + Arrays.hashCode(getEncoded());
result = 37 * result + getKeyType();
if (principal != null) {
result = 37 * result + principal.hashCode();
}
return result * 37 + versionNum;
}
/** {@collect.stats}
* Compares the specified Object with this KerberosKey for equality.
* Returns true if the given object is also a
* <code>KerberosKey</code> and the two
* <code>KerberosKey</code> instances are equivalent.
*
* @param other the Object to compare to
* @return true if the specified object is equal to this KerberosKey,
* false otherwise. NOTE: Returns false if either of the KerberosKey
* objects has been destroyed.
* @since 1.6
*/
public boolean equals(Object other) {
if (other == this)
return true;
if (! (other instanceof KerberosKey)) {
return false;
}
KerberosKey otherKey = ((KerberosKey) other);
if (isDestroyed() || otherKey.isDestroyed()) {
return false;
}
if (versionNum != otherKey.getVersionNumber() ||
getKeyType() != otherKey.getKeyType() ||
!Arrays.equals(getEncoded(), otherKey.getEncoded())) {
return false;
}
if (principal == null) {
if (otherKey.getPrincipal() != null) {
return false;
}
} else {
if (!principal.equals(otherKey.getPrincipal())) {
return false;
}
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.io.*;
import sun.security.krb5.Asn1Exception;
import sun.security.krb5.KrbException;
import sun.security.krb5.PrincipalName;
import sun.security.krb5.Realm;
import sun.security.util.*;
/** {@collect.stats}
* This class encapsulates a Kerberos principal.
*
* @author Mayank Upadhyay
* @since 1.4
*/
public final class KerberosPrincipal
implements java.security.Principal, java.io.Serializable {
private static final long serialVersionUID = -7374788026156829911L;
//name types
/** {@collect.stats}
* unknown name type.
*/
public static final int KRB_NT_UNKNOWN = 0;
/** {@collect.stats}
* user principal name type.
*/
public static final int KRB_NT_PRINCIPAL = 1;
/** {@collect.stats}
* service and other unique instance (krbtgt) name type.
*/
public static final int KRB_NT_SRV_INST = 2;
/** {@collect.stats}
* service with host name as instance (telnet, rcommands) name type.
*/
public static final int KRB_NT_SRV_HST = 3;
/** {@collect.stats}
* service with host as remaining components name type.
*/
public static final int KRB_NT_SRV_XHST = 4;
/** {@collect.stats}
* unique ID name type.
*/
public static final int KRB_NT_UID = 5;
private transient String fullName;
private transient String realm;
private transient int nameType;
private static final char NAME_REALM_SEPARATOR = '@';
/** {@collect.stats}
* Constructs a KerberosPrincipal from the provided string input. The
* name type for this principal defaults to
* {@link #KRB_NT_PRINCIPAL KRB_NT_PRINCIPAL}
* This string is assumed to contain a name in the format
* that is specified in Section 2.1.1. (Kerberos Principal Name Form) of
* <a href=http://www.ietf.org/rfc/rfc1964.txt> RFC 1964 </a>
* (for example, <i>duke@FOO.COM</i>, where <i>duke</i>
* represents a principal, and <i>FOO.COM</i> represents a realm).
*
* <p>If the input name does not contain a realm, the default realm
* is used. The default realm can be specified either in a Kerberos
* configuration file or via the java.security.krb5.realm
* system property. For more information,
* <a href="../../../../../technotes/guides/security/jgss/tutorials/index.html">
* Kerberos Requirements </a>
*
* @param name the principal name
* @throws IllegalArgumentException if name is improperly
* formatted, if name is null, or if name does not contain
* the realm to use and the default realm is not specified
* in either a Kerberos configuration file or via the
* java.security.krb5.realm system property.
*/
public KerberosPrincipal(String name) {
PrincipalName krb5Principal = null;
try {
// Appends the default realm if it is missing
krb5Principal = new PrincipalName(name, KRB_NT_PRINCIPAL);
} catch (KrbException e) {
throw new IllegalArgumentException(e.getMessage());
}
nameType = KRB_NT_PRINCIPAL; // default name type
fullName = krb5Principal.toString();
realm = krb5Principal.getRealmString();
}
/** {@collect.stats}
* Constructs a KerberosPrincipal from the provided string and
* name type input. The string is assumed to contain a name in the
* format that is specified in Section 2.1 (Mandatory Name Forms) of
* <a href=http://www.ietf.org/rfc/rfc1964.txt>RFC 1964</a>.
* Valid name types are specified in Section 6.2 (Principal Names) of
* <a href=http://www.ietf.org/rfc/rfc4120.txt>RFC 4120</a>.
* The input name must be consistent with the provided name type.
* (for example, <i>duke@FOO.COM</i>, is a valid input string for the
* name type, KRB_NT_PRINCIPAL where <i>duke</i>
* represents a principal, and <i>FOO.COM</i> represents a realm).
* <p> If the input name does not contain a realm, the default realm
* is used. The default realm can be specified either in a Kerberos
* configuration file or via the java.security.krb5.realm
* system property. For more information, see
* <a href="../../../../../technotes/guides/security/jgss/tutorials/index.html">
* Kerberos Requirements</a>.
*
* @param name the principal name
* @param nameType the name type of the principal
* @throws IllegalArgumentException if name is improperly
* formatted, if name is null, if the nameType is not supported,
* or if name does not contain the realm to use and the default
* realm is not specified in either a Kerberos configuration
* file or via the java.security.krb5.realm system property.
*/
public KerberosPrincipal(String name, int nameType) {
PrincipalName krb5Principal = null;
try {
// Appends the default realm if it is missing
krb5Principal = new PrincipalName(name,nameType);
} catch (KrbException e) {
throw new IllegalArgumentException(e.getMessage());
}
this.nameType = nameType;
fullName = krb5Principal.toString();
realm = krb5Principal.getRealmString();
}
/** {@collect.stats}
* Returns the realm component of this Kerberos principal.
*
* @return the realm component of this Kerberos principal.
*/
public String getRealm() {
return realm;
}
/** {@collect.stats}
* Returns a hashcode for this principal. The hash code is defined to
* be the result of the following calculation:
* <pre><code>
* hashCode = getName().hashCode();
* </code></pre>
*
* @return a hashCode() for the <code>KerberosPrincipal</code>
*/
public int hashCode() {
return getName().hashCode();
}
/** {@collect.stats}
* Compares the specified Object with this Principal for equality.
* Returns true if the given object is also a
* <code>KerberosPrincipal</code> and the two
* <code>KerberosPrincipal</code> instances are equivalent.
* More formally two <code>KerberosPrincipal</code> instances are equal
* if the values returned by <code>getName()</code> are equal and the
* values returned by <code>getNameType()</code> are equal.
*
* @param other the Object to compare to
* @return true if the Object passed in represents the same principal
* as this one, false otherwise.
*/
public boolean equals(Object other) {
if (other == this)
return true;
if (! (other instanceof KerberosPrincipal)) {
return false;
} else {
String myFullName = getName();
String otherFullName = ((KerberosPrincipal) other).getName();
if (nameType == ((KerberosPrincipal)other).nameType &&
myFullName.equals(otherFullName)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Save the KerberosPrincipal object to a stream
*
* @serialData this <code>KerberosPrincipal</code> is serialized
* by writing out the PrincipalName and the
* realm in their DER-encoded form as specified in Section 5.2.2 of
* <a href=http://www.ietf.org/rfc/rfc4120.txt> RFC4120</a>.
*/
private void writeObject(ObjectOutputStream oos)
throws IOException {
PrincipalName krb5Principal = null;
try {
krb5Principal = new PrincipalName(fullName,nameType);
oos.writeObject(krb5Principal.asn1Encode());
oos.writeObject(krb5Principal.getRealm().asn1Encode());
} catch (Exception e) {
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
throw ioe;
}
}
/** {@collect.stats}
* Reads this object from a stream (i.e., deserializes it)
*/
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
byte[] asn1EncPrincipal = (byte [])ois.readObject();
byte[] encRealm = (byte [])ois.readObject();
try {
PrincipalName krb5Principal = new PrincipalName(new
DerValue(asn1EncPrincipal));
realm = (new Realm(new DerValue(encRealm))).toString();
fullName = krb5Principal.toString() + NAME_REALM_SEPARATOR +
realm.toString();
nameType = krb5Principal.getNameType();
} catch (Exception e) {
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
throw ioe;
}
}
/** {@collect.stats}
* The returned string corresponds to the single-string
* representation of a Kerberos Principal name as specified in
* Section 2.1 of <a href=http://www.ietf.org/rfc/rfc1964.txt>RFC 1964</a>.
*
* @return the principal name.
*/
public String getName() {
return fullName;
}
/** {@collect.stats}
* Returns the name type of the KerberosPrincipal. Valid name types
* are specified in Section 6.2 of
* <a href=http://www.ietf.org/rfc/rfc4120.txt> RFC4120</a>.
*
* @return the name type.
*
*/
public int getNameType() {
return nameType;
}
// Inherits javadocs from Object
public String toString() {
return getName();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.util.*;
import java.security.Permission;
import java.security.PermissionCollection;
import java.io.ObjectStreamField;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* This class is used to protect Kerberos services and the
* credentials necessary to access those services. There is a one to
* one mapping of a service principal and the credentials necessary
* to access the service. Therefore granting access to a service
* principal implicitly grants access to the credential necessary to
* establish a security context with the service principal. This
* applies regardless of whether the credentials are in a cache
* or acquired via an exchange with the KDC. The credential can
* be either a ticket granting ticket, a service ticket or a secret
* key from a key table.
* <p>
* A ServicePermission contains a service principal name and
* a list of actions which specify the context the credential can be
* used within.
* <p>
* The service principal name is the canonical name of the
* <code>KereberosPrincipal</code> supplying the service, that is
* the KerberosPrincipal represents a Kerberos service
* principal. This name is treated in a case sensitive manner.
* An asterisk may appear by itself, to signify any service principal.
* <p>
* Granting this permission implies that the caller can use a cached
* credential (TGT, service ticket or secret key) within the context
* designated by the action. In the case of the TGT, granting this
* permission also implies that the TGT can be obtained by an
* Authentication Service exchange.
* <p>
* The possible actions are:
* <p>
* <pre>
* initiate - allow the caller to use the credential to
* initiate a security context with a service
* principal.
*
* accept - allow the caller to use the credential to
* accept security context as a particular
* principal.
* </pre>
*
* For example, to specify the permission to access to the TGT to
* initiate a security context the permission is constructed as follows:
* <p>
* <pre>
* ServicePermission("krbtgt/EXAMPLE.COM@EXAMPLE.COM", "initiate");
* </pre>
* <p>
* To obtain a service ticket to initiate a context with the "host"
* service the permission is constructed as follows:
* <pre>
* ServicePermission("host/foo.example.com@EXAMPLE.COM", "initiate");
* </pre>
* <p>
* For a Kerberized server the action is "accept". For example, the permission
* necessary to access and use the secret key of the Kerberized "host"
* service (telnet and the likes) would be constructed as follows:
* <p>
* <pre>
* ServicePermission("host/foo.example.com@EXAMPLE.COM", "accept");
* </pre>
*
* @since 1.4
*/
public final class ServicePermission extends Permission
implements java.io.Serializable {
private static final long serialVersionUID = -1227585031618624935L;
/** {@collect.stats}
* Initiate a security context to the specified service
*/
private final static int INITIATE = 0x1;
/** {@collect.stats}
* Accept a security context
*/
private final static int ACCEPT = 0x2;
/** {@collect.stats}
* All actions
*/
private final static int ALL = INITIATE|ACCEPT;
/** {@collect.stats}
* No actions.
*/
private final static int NONE = 0x0;
// the actions mask
private transient int mask;
/** {@collect.stats}
* the actions string.
*
* @serial
*/
private String actions; // Left null as long as possible, then
// created and re-used in the getAction function.
/** {@collect.stats}
* Create a new <code>ServicePermission</code>
* with the specified <code>servicePrincipal</code>
* and <code>action</code>.
*
* @param servicePrincipal the name of the service principal.
* An asterisk may appear by itself, to signify any service principal.
* <p>
* @param action the action string
*/
public ServicePermission(String servicePrincipal, String action) {
super(servicePrincipal);
init(servicePrincipal, getMask(action));
}
/** {@collect.stats}
* Initialize the ServicePermission object.
*/
private void init(String servicePrincipal, int mask) {
if (servicePrincipal == null)
throw new NullPointerException("service principal can't be null");
if ((mask & ALL) != mask)
throw new IllegalArgumentException("invalid actions mask");
this.mask = mask;
}
/** {@collect.stats}
* Checks if this Kerberos service permission object "implies" the
* specified permission.
* <P>
* If none of the above are true, <code>implies</code> returns false.
* @param p the permission to check against.
*
* @return true if the specified permission is implied by this object,
* false if not.
*/
public boolean implies(Permission p) {
if (!(p instanceof ServicePermission))
return false;
ServicePermission that = (ServicePermission) p;
return ((this.mask & that.mask) == that.mask) &&
impliesIgnoreMask(that);
}
boolean impliesIgnoreMask(ServicePermission p) {
return ((this.getName().equals("*")) ||
this.getName().equals(p.getName()));
}
/** {@collect.stats}
* Checks two ServicePermission objects for equality.
* <P>
* @param obj the object to test for equality with this object.
*
* @return true if <i>obj</i> is a ServicePermission, and has the
* same service principal, and actions as this
* ServicePermission object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof ServicePermission))
return false;
ServicePermission that = (ServicePermission) obj;
return ((this.mask & that.mask) == that.mask) &&
this.getName().equals(that.getName());
}
/** {@collect.stats}
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return (getName().hashCode() ^ mask);
}
/** {@collect.stats}
* Returns the "canonical string representation" of the actions in the
* specified mask.
* Always returns present actions in the following order:
* initiate, accept.
*
* @param mask a specific integer action mask to translate into a string
* @return the canonical string representation of the actions
*/
private static String getActions(int mask)
{
StringBuilder sb = new StringBuilder();
boolean comma = false;
if ((mask & INITIATE) == INITIATE) {
if (comma) sb.append(',');
else comma = true;
sb.append("initiate");
}
if ((mask & ACCEPT) == ACCEPT) {
if (comma) sb.append(',');
else comma = true;
sb.append("accept");
}
return sb.toString();
}
/** {@collect.stats}
* Returns the canonical string representation of the actions.
* Always returns present actions in the following order:
* initiate, accept.
*/
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
return actions;
}
/** {@collect.stats}
* Returns a PermissionCollection object for storing
* ServicePermission objects.
* <br>
* ServicePermission objects must be stored in a manner that
* allows them to be inserted into the collection in any order, but
* that also enables the PermissionCollection implies method to
* be implemented in an efficient (and consistent) manner.
*
* @return a new PermissionCollection object suitable for storing
* ServicePermissions.
*/
public PermissionCollection newPermissionCollection() {
return new KrbServicePermissionCollection();
}
/** {@collect.stats}
* Return the current action mask.
*
* @return the actions mask.
*/
int getMask() {
return mask;
}
/** {@collect.stats}
* Convert an action string to an integer actions mask.
*
* @param action the action string
* @return the action mask
*/
private static int getMask(String action) {
if (action == null) {
throw new NullPointerException("action can't be null");
}
if (action.equals("")) {
throw new IllegalArgumentException("action can't be empty");
}
int mask = NONE;
char[] a = action.toCharArray();
int i = a.length - 1;
if (i < 0)
return mask;
while (i != -1) {
char c;
// skip whitespace
while ((i!=-1) && ((c = a[i]) == ' ' ||
c == '\r' ||
c == '\n' ||
c == '\f' ||
c == '\t'))
i--;
// check for the known strings
int matchlen;
if (i >= 7 && (a[i-7] == 'i' || a[i-7] == 'I') &&
(a[i-6] == 'n' || a[i-6] == 'N') &&
(a[i-5] == 'i' || a[i-5] == 'I') &&
(a[i-4] == 't' || a[i-4] == 'T') &&
(a[i-3] == 'i' || a[i-3] == 'I') &&
(a[i-2] == 'a' || a[i-2] == 'A') &&
(a[i-1] == 't' || a[i-1] == 'T') &&
(a[i] == 'e' || a[i] == 'E'))
{
matchlen = 8;
mask |= INITIATE;
} else if (i >= 5 && (a[i-5] == 'a' || a[i-5] == 'A') &&
(a[i-4] == 'c' || a[i-4] == 'C') &&
(a[i-3] == 'c' || a[i-3] == 'C') &&
(a[i-2] == 'e' || a[i-2] == 'E') &&
(a[i-1] == 'p' || a[i-1] == 'P') &&
(a[i] == 't' || a[i] == 'T'))
{
matchlen = 6;
mask |= ACCEPT;
} else {
// parse error
throw new IllegalArgumentException(
"invalid permission: " + action);
}
// make sure we didn't just match the tail of a word
// like "ackbarfaccept". Also, skip to the comma.
boolean seencomma = false;
while (i >= matchlen && !seencomma) {
switch(a[i-matchlen]) {
case ',':
seencomma = true;
/*FALLTHROUGH*/
case ' ': case '\r': case '\n':
case '\f': case '\t':
break;
default:
throw new IllegalArgumentException(
"invalid permission: " + action);
}
i--;
}
// point i at the location of the comma minus one (or -1).
i -= matchlen;
}
return mask;
}
/** {@collect.stats}
* WriteObject is called to save the state of the ServicePermission
* to a stream. The actions are serialized, and the superclass
* takes care of the name.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null)
getActions();
s.defaultWriteObject();
}
/** {@collect.stats}
* readObject is called to restore the state of the
* ServicePermission from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getName(),getMask(actions));
}
/*
public static void main(String args[]) throws Exception {
ServicePermission this_ =
new ServicePermission(args[0], "accept");
ServicePermission that_ =
new ServicePermission(args[1], "accept,initiate");
System.out.println("-----\n");
System.out.println("this.implies(that) = " + this_.implies(that_));
System.out.println("-----\n");
System.out.println("this = "+this_);
System.out.println("-----\n");
System.out.println("that = "+that_);
System.out.println("-----\n");
KrbServicePermissionCollection nps =
new KrbServicePermissionCollection();
nps.add(this_);
nps.add(new ServicePermission("nfs/example.com@EXAMPLE.COM",
"accept"));
nps.add(new ServicePermission("host/example.com@EXAMPLE.COM",
"initiate"));
System.out.println("nps.implies(that) = " + nps.implies(that_));
System.out.println("-----\n");
Enumeration e = nps.elements();
while (e.hasMoreElements()) {
ServicePermission x =
(ServicePermission) e.nextElement();
System.out.println("nps.e = " + x);
}
}
*/
}
final class KrbServicePermissionCollection extends PermissionCollection
implements java.io.Serializable {
// Not serialized; see serialization section at end of class
private transient List<Permission> perms;
public KrbServicePermissionCollection() {
perms = new ArrayList<Permission>();
}
/** {@collect.stats}
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
public boolean implies(Permission permission) {
if (! (permission instanceof ServicePermission))
return false;
ServicePermission np = (ServicePermission) permission;
int desired = np.getMask();
int effective = 0;
int needed = desired;
synchronized (this) {
int len = perms.size();
// need to deal with the case where the needed permission has
// more than one action and the collection has individual permissions
// that sum up to the needed.
for (int i = 0; i < len; i++) {
ServicePermission x = (ServicePermission) perms.get(i);
//System.out.println(" trying "+x);
if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(np)) {
effective |= x.getMask();
if ((effective & desired) == desired)
return true;
needed = (desired ^ effective);
}
}
}
return false;
}
/** {@collect.stats}
* Adds a permission to the ServicePermissions. The key for
* the hash is the name.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* ServicePermission
*
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof ServicePermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
synchronized (this) {
perms.add(0, permission);
}
}
/** {@collect.stats}
* Returns an enumeration of all the ServicePermission objects
* in the container.
*
* @return an enumeration of all the ServicePermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
return Collections.enumeration(perms);
}
}
private static final long serialVersionUID = -4118834211490102011L;
// Need to maintain serialization interoperability with earlier releases,
// which had the serializable field:
// private Vector permissions;
/** {@collect.stats}
* @serialField permissions java.util.Vector
* A list of ServicePermission objects.
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("permissions", Vector.class),
};
/** {@collect.stats}
* @serialData "permissions" field (a Vector containing the ServicePermissions).
*/
/*
* Writes the contents of the perms field out as a Vector for
* serialization compatibility with earlier releases.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Don't call out.defaultWriteObject()
// Write out Vector
Vector<Permission> permissions = new Vector<Permission>(perms.size());
synchronized (this) {
permissions.addAll(perms);
}
ObjectOutputStream.PutField pfields = out.putFields();
pfields.put("permissions", permissions);
out.writeFields();
}
/*
* Reads in a Vector of ServicePermissions and saves them in the perms field.
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get the one we want
Vector<Permission> permissions =
(Vector<Permission>)gfields.get("permissions", null);
perms = new ArrayList<Permission>(permissions.size());
perms.addAll(permissions);
}
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
/** {@collect.stats}
* <p> This is an abstract class for representing the system policy for
* Subject-based authorization. A subclass implementation
* of this class provides a means to specify a Subject-based
* access control <code>Policy</code>.
*
* <p> A <code>Policy</code> object can be queried for the set of
* Permissions granted to code running as a
* <code>Principal</code> in the following manner:
*
* <pre>
* policy = Policy.getPolicy();
* PermissionCollection perms = policy.getPermissions(subject,
* codeSource);
* </pre>
*
* The <code>Policy</code> object consults the local policy and returns
* and appropriate <code>Permissions</code> object with the
* Permissions granted to the Principals associated with the
* provided <i>subject</i>, and granted to the code specified
* by the provided <i>codeSource</i>.
*
* <p> A <code>Policy</code> contains the following information.
* Note that this example only represents the syntax for the default
* <code>Policy</code> implementation. Subclass implementations of this class
* may implement alternative syntaxes and may retrieve the
* <code>Policy</code> from any source such as files, databases,
* or servers.
*
* <p> Each entry in the <code>Policy</code> is represented as
* a <b><i>grant</i></b> entry. Each <b><i>grant</i></b> entry
* specifies a codebase, code signers, and Principals triplet,
* as well as the Permissions granted to that triplet.
*
* <pre>
* grant CodeBase ["URL"], Signedby ["signers"],
* Principal [Principal_Class] "Principal_Name" {
* Permission Permission_Class ["Target_Name"]
* [, "Permission_Actions"]
* [, signedBy "SignerName"];
* };
* </pre>
*
* The CodeBase and Signedby components of the triplet name/value pairs
* are optional. If they are not present, then any any codebase will match,
* and any signer (including unsigned code) will match.
* For Example,
*
* <pre>
* grant CodeBase "foo.com", Signedby "foo",
* Principal com.sun.security.auth.SolarisPrincipal "duke" {
* permission java.io.FilePermission "/home/duke", "read, write";
* };
* </pre>
*
* This <b><i>grant</i></b> entry specifies that code from "foo.com",
* signed by "foo', and running as a <code>SolarisPrincipal</code> with the
* name, duke, has one <code>Permission</code>. This <code>Permission</code>
* permits the executing code to read and write files in the directory,
* "/home/duke".
*
* <p> To "run" as a particular <code>Principal</code>,
* code invokes the <code>Subject.doAs(subject, ...)</code> method.
* After invoking that method, the code runs as all the Principals
* associated with the specified <code>Subject</code>.
* Note that this <code>Policy</code> (and the Permissions
* granted in this <code>Policy</code>) only become effective
* after the call to <code>Subject.doAs</code> has occurred.
*
* <p> Multiple Principals may be listed within one <b><i>grant</i></b> entry.
* All the Principals in the grant entry must be associated with
* the <code>Subject</code> provided to <code>Subject.doAs</code>
* for that <code>Subject</code> to be granted the specified Permissions.
*
* <pre>
* grant Principal com.sun.security.auth.SolarisPrincipal "duke",
* Principal com.sun.security.auth.SolarisNumericUserPrincipal "0" {
* permission java.io.FilePermission "/home/duke", "read, write";
* permission java.net.SocketPermission "duke.com", "connect";
* };
* </pre>
*
* This entry grants any code running as both "duke" and "0"
* permission to read and write files in duke's home directory,
* as well as permission to make socket connections to "duke.com".
*
* <p> Note that non Principal-based grant entries are not permitted
* in this <code>Policy</code>. Therefore, grant entries such as:
*
* <pre>
* grant CodeBase "foo.com", Signedby "foo" {
* permission java.io.FilePermission "/tmp/scratch", "read, write";
* };
* </pre>
*
* are rejected. Such permission must be listed in the
* <code>java.security.Policy</code>.
*
* <p> The default <code>Policy</code> implementation can be changed by
* setting the value of the "auth.policy.provider" security property
* (in the Java security properties file) to the fully qualified name of
* the desired <code>Policy</code> implementation class.
* The Java security properties file is located in the file named
* <JAVA_HOME>/lib/security/java.security.
* <JAVA_HOME> refers to the value of the java.home system property,
* and specifies the directory where the JRE is installed.
*
* @deprecated as of JDK version 1.4 -- Replaced by java.security.Policy.
* java.security.Policy has a method:
* <pre>
* public PermissionCollection getPermissions
* (java.security.ProtectionDomain pd)
*
* </pre>
* and ProtectionDomain has a constructor:
* <pre>
* public ProtectionDomain
* (CodeSource cs,
* PermissionCollection permissions,
* ClassLoader loader,
* Principal[] principals)
* </pre>
*
* These two APIs provide callers the means to query the
* Policy for Principal-based Permission entries.
*
*
*/
@Deprecated
public abstract class Policy {
private static Policy policy;
private static ClassLoader contextClassLoader;
static {
contextClassLoader = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
};
/** {@collect.stats}
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
protected Policy() { }
/** {@collect.stats}
* Returns the installed Policy object.
* This method first calls
* <code>SecurityManager.checkPermission</code> with the
* <code>AuthPermission("getPolicy")</code> permission
* to ensure the caller has permission to get the Policy object.
*
* <p>
*
* @return the installed Policy. The return value cannot be
* <code>null</code>.
*
* @exception java.lang.SecurityException if the current thread does not
* have permission to get the Policy object.
*
* @see #setPolicy
*/
public static Policy getPolicy() {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new AuthPermission("getPolicy"));
return getPolicyNoCheck();
}
/** {@collect.stats}
* Returns the installed Policy object, skipping the security check.
*
* @return the installed Policy.
*
*/
static Policy getPolicyNoCheck() {
if (policy == null) {
synchronized(Policy.class) {
if (policy == null) {
String policy_class = null;
policy_class = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<String>() {
public String run() {
return java.security.Security.getProperty
("auth.policy.provider");
}
});
if (policy_class == null) {
policy_class = "com.sun.security.auth.PolicyFile";
}
try {
final String finalClass = policy_class;
policy = java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<Policy>() {
public Policy run() throws ClassNotFoundException,
InstantiationException,
IllegalAccessException {
return (Policy) Class.forName
(finalClass,
true,
contextClassLoader).newInstance();
}
});
} catch (Exception e) {
throw new SecurityException
(sun.security.util.ResourcesMgr.getString
("unable to instantiate Subject-based policy"));
}
}
}
}
return policy;
}
/** {@collect.stats}
* Sets the system-wide Policy object. This method first calls
* <code>SecurityManager.checkPermission</code> with the
* <code>AuthPermission("setPolicy")</code>
* permission to ensure the caller has permission to set the Policy.
*
* <p>
*
* @param policy the new system Policy object.
*
* @exception java.lang.SecurityException if the current thread does not
* have permission to set the Policy.
*
* @see #getPolicy
*/
public static void setPolicy(Policy policy) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new AuthPermission("setPolicy"));
Policy.policy = policy;
}
/** {@collect.stats}
* Retrieve the Permissions granted to the Principals associated with
* the specified <code>CodeSource</code>.
*
* <p>
*
* @param subject the <code>Subject</code>
* whose associated Principals,
* in conjunction with the provided
* <code>CodeSource</code>, determines the Permissions
* returned by this method. This parameter
* may be <code>null</code>. <p>
*
* @param cs the code specified by its <code>CodeSource</code>
* that determines, in conjunction with the provided
* <code>Subject</code>, the Permissions
* returned by this method. This parameter may be
* <code>null</code>.
*
* @return the Collection of Permissions granted to all the
* <code>Subject</code> and code specified in
* the provided <i>subject</i> and <i>cs</i>
* parameters.
*/
public abstract java.security.PermissionCollection getPermissions
(Subject subject,
java.security.CodeSource cs);
/** {@collect.stats}
* Refresh and reload the Policy.
*
* <p>This method causes this object to refresh/reload its current
* Policy. This is implementation-dependent.
* For example, if the Policy object is stored in
* a file, calling <code>refresh</code> will cause the file to be re-read.
*
* <p>
*
* @exception SecurityException if the caller does not have permission
* to refresh the Policy.
*/
public abstract void refresh();
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
/** {@collect.stats}
* Objects such as credentials may optionally implement this interface
* to provide the capability to destroy its contents.
*
* @see javax.security.auth.Subject
*/
public interface Destroyable {
/** {@collect.stats}
* Destroy this <code>Object</code>.
*
* <p> Sensitive information associated with this <code>Object</code>
* is destroyed or cleared. Subsequent calls to certain methods
* on this <code>Object</code> will result in an
* <code>IllegalStateException</code> being thrown.
*
* <p>
*
* @exception DestroyFailedException if the destroy operation fails. <p>
*
* @exception SecurityException if the caller does not have permission
* to destroy this <code>Object</code>.
*/
void destroy() throws DestroyFailedException;
/** {@collect.stats}
* Determine if this <code>Object</code> has been destroyed.
*
* <p>
*
* @return true if this <code>Object</code> has been destroyed,
* false otherwise.
*/
boolean isDestroyed();
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.