下面列出了怎么用javax.swing.text.Element的API类实例代码及写法,或者点击链接到github查看源代码。
private String getCurrentText() {
Document doc = this.getDocument();
int dot = this.getCaretPosition();
Element root = doc.getDefaultRootElement();
int index = root.getElementIndex(dot);
Element elem = root.getElement(index);
int start = elem.getStartOffset();
int len = dot - start;
try {
doc.getText(start, len, seg);
} catch (BadLocationException ble) {
ble.printStackTrace();
return "";
}
return seg.toString();
}
/**
* Get the offset area in which the views should be rebuilt
* in reaction to insert update in the underlying document.
*
* @param evt document event for the document modification.
* @return two-item integer array containing starting and ending offset
* of the area to be rebuilt or <code>null</code> in case
* no views should be rebuilt.
*/
protected int[] getRemoveUpdateRebuildOffsetRange(DocumentEvent evt) {
DocumentEvent.ElementChange lineChange = evt.getChange(evt.getDocument().getDefaultRootElement());
if (lineChange == null) {
return null;
}
int startOffset = evt.getOffset();
int endOffset = startOffset;
int[] offsetRange = new int[] {startOffset, endOffset};
Element[] addedLines = lineChange.getChildrenAdded();
ElementUtilities.updateOffsetRange(addedLines, offsetRange);
Element[] removedLines = lineChange.getChildrenRemoved();
ElementUtilities.updateOffsetRange(removedLines, offsetRange);
return offsetRange;
}
@Override public View create(Element elem) {
switch (elem.getName()) {
// case AbstractDocument.ContentElementName:
// return new LabelView(elem);
case AbstractDocument.ParagraphElementName:
return new ParagraphWithEndMarkView(elem);
case AbstractDocument.SectionElementName:
return new BoxView(elem, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(elem);
case StyleConstants.IconElementName:
return new IconView(elem);
default:
return new LabelView(elem);
}
}
public InlineReplacedBoxView(Element elem)
{
super(elem);
content = ((InlineReplacedBox) box).getContentObj();
if (content instanceof ReplacedImage)
{
repImage = (ReplacedImage) content;
}
else
{
repImage = null;
}
loadElementAttributes();
}
private static void checkImages() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
HTMLEditorKit c = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
try {
c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
} catch (Exception e) {
throw new RuntimeException("The test failed", e);
}
Element elem = doc.getElement("test");
ImageView iv = new ImageView(elem);
if (iv.getLoadingImageIcon() == null) {
throw new RuntimeException("getLoadingImageIcon returns null");
}
if (iv.getNoImageIcon() == null) {
throw new RuntimeException("getNoImageIcon returns null");
}
}
});
}
/**
* Called whenever the value of the selection changes.
* @param e the event that characterizes the change.
*/
public void valueChanged(TreeSelectionEvent e) {
if (!updatingSelection && tree.getSelectionCount() == 1) {
TreePath selPath = tree.getSelectionPath();
Object lastPathComponent = selPath.getLastPathComponent();
if (!(lastPathComponent instanceof DefaultMutableTreeNode)) {
Element selElement = (Element) lastPathComponent;
updatingSelection = true;
try {
getEditor().select(selElement.getStartOffset(),
selElement.getEndOffset());
} finally {
updatingSelection = false;
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
try {
if (SwingUtilities.isLeftMouseButton(e)) {
JTextPane pane = (JTextPane)e.getSource();
StyledDocument doc = pane.getStyledDocument();
Element elem = doc.getCharacterElement(pane.viewToModel(e.getPoint()));
AttributeSet as = elem.getAttributes();
Link link = (Link)as.getAttribute(LINK_ATTRIBUTE);
if (link != null) {
link.onClick(elem.getDocument().getText(elem.getStartOffset(), elem.getEndOffset() - elem.getStartOffset()));
}
}
} catch(Exception ex) {
Support.LOG.log(Level.SEVERE, null, ex);
}
}
@Override
public View create(final Element element) {
final String kind = element.getName();
if (kind != null) {
switch (kind) {
case AbstractDocument.ContentElementName:
return new WrapLabelView(element);
case AbstractDocument.ParagraphElementName:
return new ParagraphView(element);
case AbstractDocument.SectionElementName:
return new BoxView(element, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(element);
case StyleConstants.IconElementName:
return new IconView(element);
}
}
// Default to text display.
return new LabelView(element);
}
@Override
public View create(Element elem) {
String kind = elem.getName();
// System.out.println("Kind: " + kind);
if (kind != null) {
if (AbstractDocument.ContentElementName.equals(kind)) {
return new LabelView(elem);
} else if (AbstractDocument.ParagraphElementName.equals(kind)) {
return new NumberedParagraphView(elem, highlight);
} else if (AbstractDocument.SectionElementName.equals(kind)) {
return new NoWrapBoxView(elem, View.Y_AXIS);
} else if (StyleConstants.ComponentElementName.equals(kind)) {
return new ComponentView(elem);
} else if (StyleConstants.IconElementName.equals(kind)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
private int lineToOffset(int line) throws BadLocationException {
Document d = getDocument();
try {
Element element = d.getDefaultRootElement().getElement(line - 1);
if (element == null) {
throw new BadLocationException("line " + line + " does not exist", -line);
}
return element.getStartOffset();
} catch (ArrayIndexOutOfBoundsException aioobe) {
BadLocationException ble = new BadLocationException("line " + line + " does not exist", -line);
ble.initCause(aioobe);
throw ble;
}
}
/**
* Updates the tree based on the event type. This will invoke either
* updateTree with the root element, or handleChange.
*/
protected void updateTree(DocumentEvent event) {
updatingSelection = true;
try {
TreeModel model = getTreeModel();
Object root = model.getRoot();
for (int counter = model.getChildCount(root) - 1; counter >= 0;
counter--) {
updateTree(event, (Element) model.getChild(root, counter));
}
} finally {
updatingSelection = false;
}
}
@Override
public Element[] getRootElements() {
Element[] elements = this.document.getRootElements();
Element[] wrappers = new Element[elements.length];
for (int i = 0; i < elements.length; i++) {
wrappers[i] = new MyElement(elements[i]);
}
return wrappers;
}
private Optional<String> getSpanTitleAttribute(HTMLDocument doc, int pos) {
// HTMLDocument doc = (HTMLDocument) editor.getDocument();
Element elem = doc.getCharacterElement(pos);
// if (!doesElementContainLocation(editor, elem, pos, e.getX(), e.getY())) {
// elem = null;
// }
// if (elem != null) {
AttributeSet a = elem.getAttributes();
AttributeSet span = (AttributeSet) a.getAttribute(HTML.Tag.SPAN);
return Optional.ofNullable(span).map(s -> Objects.toString(s.getAttribute(HTML.Attribute.TITLE)));
}
public static int getWordStart(JTextComponent c, int offs) throws BadLocationException {
Element line = Optional.ofNullable(Utilities.getParagraphElement(c, offs))
.orElseThrow(() -> new BadLocationException("No word at " + offs, offs));
Document doc = c.getDocument();
int lineStart = line.getStartOffset();
int lineEnd = Math.min(line.getEndOffset(), doc.getLength());
int offs2 = offs;
Segment seg = SegmentCache.getSharedSegment();
doc.getText(lineStart, lineEnd - lineStart, seg);
if (seg.count > 0) {
BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
words.setText(seg);
int wordPosition = seg.offset + offs - lineStart;
if (wordPosition >= words.last()) {
wordPosition = words.last() - 1;
words.following(wordPosition);
offs2 = lineStart + words.previous() - seg.offset;
} else {
words.following(wordPosition);
offs2 = lineStart + words.previous() - seg.offset;
for (int i = offs; i > offs2; i--) {
char ch = seg.charAt(i - seg.offset);
if (ch == '_' || ch == '-') {
offs2 = i + 1;
break;
}
}
}
}
SegmentCache.releaseSharedSegment(seg);
return offs2;
}
@Override
public Element[] getRootElements() {
Element[] elements = this.document.getRootElements();
Element[] wrappers = new Element[elements.length];
for (int i = 0; i < elements.length; i++) {
wrappers[i] = new MyElement(elements[i]);
}
return wrappers;
}
public Element getElement() {
if (view != null) {
return view.getElement();
}
Document doc = getDocument();
return (doc != null) ? doc.getDefaultRootElement() : null;
}
/**
* Construct a composite box view over the given element.
*
* @param elem the element of the model to represent.
* @param majorAxis the axis to tile along. This can be
* either X_AXIS or Y_AXIS.
*/
public GapBoxView(Element elem, int majorAxis) {
super(elem);
if (majorAxis == View.X_AXIS) {
setStatusBits(X_MAJOR_AXIS_BIT);
} // by default there should be no bits set
}
static void createAndShowGUI(Test test) {
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (Exception e) {
throw new RuntimeException(e);
}
frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
String text = "AAAAAAA";
textField = test.isPasswordField()
? new JPasswordField(text)
: new JTextField(text);
textField.setUI(new MetalTextFieldUI() {
@Override
public View create(Element elem) {
return test.createView(elem);
}
});
panel.add(textField);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
private static Element findFirstElement(Element e, String name) {
String elementName = e.getName();
if (elementName != null && elementName.equalsIgnoreCase(name)) {
return e;
}
for (int i = 0; i < e.getElementCount(); i++) {
Element result = findFirstElement(e.getElement(i), name);
if (result != null) {
return result;
}
}
return null;
}
public void appendBatchLineFeed(AttributeSet a) {
batch.add(new ElementSpec(
a, ElementSpec.ContentType, EOL_ARRAY, 0, 1));
Element paragraph = getParagraphElement(0);
AttributeSet pattern = paragraph.getAttributes();
batch.add(new ElementSpec(null, ElementSpec.EndTagType));
batch.add(new ElementSpec(pattern, ElementSpec.StartTagType));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
document.insertAfterEnd(document.getElement("ab"), textToInsert);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Element parent = document.getElement("ab").getParentElement();
int count = parent.getElementCount();
if (count != 2) {
throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
}
Element insertedElement = parent.getElement(count - 1);
if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
document.insertAfterEnd(document.getElement("ab"), textToInsert);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Element parent = document.getElement("ab").getParentElement();
int count = parent.getElementCount();
if (count != 2) {
throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
}
Element insertedElement = parent.getElement(count - 1);
if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
}
}
});
}
/**
* Returns a TreePath to the element at <code>position</code>.
*/
protected TreePath getPathForIndex(int position, Object root,
Element rootElement) {
TreePath path = new TreePath(root);
Element child = rootElement.getElement(rootElement.getElementIndex(
position));
path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
while (!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
return path;
}
/**
* Gets the line at given position. The line returned will NOT include the
* line terminator '\n'
*
* @param pos Position (usually from text.getCaretPosition()
* @return the STring of text at given position
* @throws BadLocationException
*/
public String getLineAt(int pos) throws BadLocationException {
Element e = getParagraphElement(pos);
Segment seg = new Segment();
getText(e.getStartOffset(), e.getEndOffset() - e.getStartOffset(), seg);
char last = seg.last();
if (last == '\n' || last == '\r') {
seg.count--;
}
return seg.toString();
}
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return null;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
final Element line = root.getElement(lineIndex);
if (line == null) return null;
return new int[] { line.getStartOffset(), line.getEndOffset() };
}
/**
* Updates the tree based on the event type. This will invoke either
* updateTree with the root element, or handleChange.
*/
protected void updateTree(DocumentEvent event) {
updatingSelection = true;
try {
TreeModel model = getTreeModel();
Object root = model.getRoot();
for (int counter = model.getChildCount(root) - 1; counter >= 0;
counter--) {
updateTree(event, (Element) model.getChild(root, counter));
}
} finally {
updatingSelection = false;
}
}
bug6857057() {
Element elem = new StubBranchElement(" G L Y P H V");
GlyphView view = new GlyphView(elem);
float pos = elem.getStartOffset();
float len = elem.getEndOffset() - pos;
int res = view.getBreakWeight(View.X_AXIS, pos, len);
if (res != View.ExcellentBreakWeight) {
throw new RuntimeException("breakWeight != ExcellentBreakWeight");
}
}
private static Element findFirstElement(Element e, String name) {
String elementName = e.getName();
if (elementName != null && elementName.equalsIgnoreCase(name)) {
return e;
}
for (int i = 0; i < e.getElementCount(); i++) {
Element result = findFirstElement(e.getElement(i), name);
if (result != null) {
return result;
}
}
return null;
}
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return null;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
final Element line = root.getElement(lineIndex);
if (line == null) return null;
return new int[] { line.getStartOffset(), line.getEndOffset() };
}
static int getLineNumberForIndex(final Accessible a, int index) {
final Accessible sa = CAccessible.getSwingAccessible(a);
if (!(sa instanceof JTextComponent)) return -1;
final JTextComponent jc = (JTextComponent) sa;
final Element root = jc.getDocument().getDefaultRootElement();
// treat -1 special, returns the current caret position
if (index == -1) index = jc.getCaretPosition();
// Determine line number (can be -1)
return root.getElementIndex(index);
}