Java Code Examples for javax.swing.text.ViewFactory

The following examples show how to use javax.swing.text.ViewFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads child views by tracking child elements of the element
 * this view was created for.
 * @param index index at which the views should be added/replaced.
 * @param removeLength number of removed children views. It is useful
 *  when rebuilding children for a portion of the view.
 * @param elementIndex index of the first child element for which
 *  the view should be created
 * @param elementCount number of elements for which the views should be created.
 */
protected void elementReloadChildren(int index, int removeLength,
int elementCount) {

    Element e = getElement();
    View[] added = null;

    ViewFactory f = getViewFactory();
    // Null view factory can mean that one of the grand parents is already disconnected
    // from the view hierarchy. No added children for null factory.
        
    if (f != null) {
        added = new View[elementCount];
        for (int i = 0; i < elementCount; i++) {
            added[i] = f.create(e.getElement(index + i));
        }

    }

    replace(index, removeLength, added);
}
 
Example 2
Source Project: pgptool   Source File: JXLabel.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static View createView(JXLabel c) {
	BasicEditorKit kit = getFactory();
	float rightIndent = 0;
	if (c.getIcon() != null && c.getHorizontalTextPosition() != SwingConstants.CENTER) {
		rightIndent = c.getIcon().getIconWidth() + c.getIconTextGap();
	}
	Document doc = kit.createDefaultDocument(c.getFont(), c.getForeground(), c.getTextAlignment(), rightIndent);
	Reader r = new StringReader(c.getText() == null ? "" : c.getText());
	try {
		kit.read(r, doc, 0);
	} catch (Throwable e) {
	}
	ViewFactory f = kit.getViewFactory();
	View hview = f.create(doc.getDefaultRootElement());
	View v = new Renderer(c, f, hview, true);
	return v;
}
 
Example 3
Source Project: pgptool   Source File: JXLabel.java    License: GNU General Public License v3.0 6 votes vote down vote up
Renderer(JXLabel c, ViewFactory f, View v, boolean wordWrap) {
	super(null, wordWrap);
	factory = f;
	view = v;
	view.setParent(this);
	host = c;
	// log.fine("vir: " + host.getVisibleRect());
	int w;
	if (host.getVisibleRect().width == 0) {
		invalidated = true;
		return;
	} else {
		w = host.getVisibleRect().width;
	}
	// log.fine("w:" + w);
	// initially layout to the preferred size
	// setSize(c.getMaxLineSpan() > -1 ? c.getMaxLineSpan() :
	// view.getPreferredSpan(X_AXIS), view.getPreferredSpan(Y_AXIS));
	setSize(c.getMaxLineSpan() > -1 ? c.getMaxLineSpan() : w, host.getVisibleRect().height);
}
 
Example 4
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
@Override public ViewFactory getViewFactory() {
  return new HTMLEditorKit.HTMLFactory() {
    @Override public View create(Element elem) {
      View view = super.create(elem);
      if (view instanceof LabelView) {
        System.out.println("debug: " + view.getAlignment(View.Y_AXIS));
      }
      AttributeSet attrs = elem.getAttributes();
      Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
      Object o = Objects.nonNull(elementName) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
      if (o instanceof HTML.Tag) {
        HTML.Tag kind = (HTML.Tag) o;
        if (kind == HTML.Tag.IMG) {
          return new ImageView(elem) {
            @Override public float getAlignment(int axis) {
              // .8125f magic number...
              return axis == View.Y_AXIS ? .8125f : super.getAlignment(axis);
            }
          };
        }
      }
      return view;
    }
  };
}
 
Example 5
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
@Override public ViewFactory getViewFactory() {
  return new HTMLFactory() {
    @Override public View create(Element elem) {
      AttributeSet attrs = elem.getAttributes();
      Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
      Object o = Objects.isNull(elementName) ? attrs.getAttribute(StyleConstants.NameAttribute) : null;
      if (o instanceof HTML.Tag) {
        HTML.Tag kind = (HTML.Tag) o;
        if (kind == HTML.Tag.DIV) {
          return new BlockView(elem, View.Y_AXIS) {
            @Override public String getToolTipText(float x, float y, Shape allocation) {
              String s = super.getToolTipText(x, y, allocation);
              if (Objects.isNull(s)) {
                s = Objects.toString(getElement().getAttributes().getAttribute(HTML.Attribute.TITLE));
              }
              return s;
            }
          };
        }
      }
      return super.create(elem);
    }
  };
}
 
Example 6
Source Project: SwingBox   Source File: DelegateView.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Sets the view parent.
 * 
 * @param parent
 *            the parent view
 */
@Override
public void setParent(View parent)
{

    if (parent == null && view != null) view.setParent(null);
    this.parent = parent;

    // if set new parent and has some element, try to load children
    // this element is a BranchElement ("collection"),
    // so we should have some LeafElements ("children")
    if ((parent != null) && (getElement() != null))
    {
        ViewFactory f = getViewFactory();
        loadChildren(f);
    }
}
 
Example 7
@Override
protected void forwardUpdate(DocumentEvent.ElementChange ec,
        DocumentEvent e, Shape a, ViewFactory f)
{
    boolean wasValid = isLayoutValid(majorAxis);
    super.forwardUpdate(ec, e, a, f);

    // determine if a repaint is needed
    if (wasValid && (!isLayoutValid(majorAxis)))
    {
        // Repaint is needed because one of the tiled children
        // have changed their span along the major axis. If there
        // is a hosting component and an allocated shape we repaint.
        Component c = getContainer();
        if ((a != null) && (c != null))
        {
            Rectangle alloc = getInsideAllocation(a);
            c.repaint(alloc.x, alloc.y, alloc.width, alloc.height);
        }
    }
}
 
Example 8
Source Project: SwingBox   Source File: BrowserPane.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Renders current content to given graphic context, which is updated and
 * returned. Context must have set the clip, otherwise NullPointerException
 * is thrown.
 * 
 * @param g
 *            the context to be rendered to.
 * @return the Graphics2D context
 * @see Graphics2D
 */
public Graphics2D renderContent(Graphics2D g)
{

    if (g.getClip() == null)
        throw new NullPointerException(
                "Clip is not set on graphics context");
    ViewFactory factory = getEditorKit().getViewFactory();
    if (factory instanceof SwingBoxViewFactory)
    {
        View view = ((SwingBoxViewFactory) factory).getViewport();
        if (view != null) view.paint(g, g.getClip());
    }

    return g;
}
 
Example 9
Source Project: SmartIM   Source File: IMChatConsole.java    License: Apache License 2.0 5 votes vote down vote up
protected void initHistoryWidget() {
    HTMLEditorKit kit = new HTMLEditorKit() {
        @Override
        public ViewFactory getViewFactory() {
            return new WrapHTMLFactory();
        }
    };
    final StyleSheet styleSheet = kit.getStyleSheet();
    styleSheet.addRule("body {text-align: left;}");
    styleSheet.addRule(".my {font-size: 1 em; font-style: italic; float: left;}");
    styleSheet.addRule("div.error {color: red;}");
    styleSheet.addRule("img {max-width: 100%; display: block;}");
    styleSheet.addRule(".sender {display: inline; float: left;}");
    styleSheet.addRule(".content {display: inline-block; white-space: pre-warp; padding-left: 4px;}");
    styleSheet.addRule(".br {height: 1px; line-height: 1px; min-height: 1px;}");
    RestUtils.loadStyleAsync(styleSheet);
    HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
    String initText = String.format("<html><head></head><body>%s</body></html>", imPanel.getWelcome());
    historyWidget.setContentType("text/html");
    historyWidget.setEditorKit(kit);
    historyWidget.setDocument(doc);
    historyWidget.setText(initText);
    historyWidget.setEditable(false);
    historyWidget.addHyperlinkListener(new HyperlinkListener() {

        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                String desc = e.getDescription();
                if (!StringUtils.isEmpty(desc)) {
                    hyperlinkActivated(desc);
                }
            }
        }
    });
}
 
Example 10
Source Project: netbeans   Source File: DrawEngineDocView.java    License: Apache License 2.0 5 votes vote down vote up
protected @Override View createCustomView(ViewFactory f,
int startOffset, int maxEndOffset, int elementIndex) {
    if (elementIndex == -1) {
        throw new IllegalStateException("Need underlying line element structure"); // NOI18N
    }
    
    View view = null;

    Element elem = getElement();
    Element lineElem = elem.getElement(elementIndex);
    view = f.create(lineElem);
    return view;
}
 
Example 11
Source Project: netbeans   Source File: FoldMultiLineView.java    License: Apache License 2.0 5 votes vote down vote up
protected @Override void reloadChildren(int index, int removeLength, int startOffset, int endOffset) {
    // TODO uncomment assert (index == 0 && removeLength == 0
        // && startOffset == getStartOffset() && endOffset == getEndOffset());

    // Rebuild all the present child views completely
    index = 0;
    removeLength = getViewCount();

    Element lineElem = getElement(); // starting line element
    View[] added = null;
    ViewFactory f = getViewFactory();
    if (f != null) {
        int lineElemEndOffset = lineElem.getEndOffset();
        // Ending offset of the previously created view - here start with
        //   begining of the first line
        int lastViewEndOffset = lineElem.getStartOffset();

        List childViews = new ArrayList();
        // Append ending fragment if necessary
        // asserted non-empty list => foldEndOffset populated
        if (lastViewEndOffset < lineElemEndOffset) { // need ending fragment
            View lineView = f.create(lineElem);
            View endingFrag = lineView.createFragment(lastViewEndOffset, lineElemEndOffset);
            childViews.add(endingFrag);
            // lastViewEndOffset = lineElemEndOffset;  <- can be ignored here
        }

        added = new View[childViews.size()];
        childViews.toArray(added);
    }

    
    replace(index, removeLength, added);
}
 
Example 12
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
public @Override void insertUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    // #38993 - until parent is set - do not do anything
    if (children == null && getParent() == null) {
        return;
    }

    if (useCustomReloadChildren()) {
        customInsertUpdate(evt, a, f);
    } else { // custom insert update
        super.insertUpdate(evt, a, f); // default element-based update
    }
}
 
Example 13
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
protected void customInsertUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    int[] offsetRange = getInsertUpdateRebuildOffsetRange(evt);
    if (offsetRange != null) {
        offsetRebuild(offsetRange[0], offsetRange[1]);
    } else {
        forwardUpdate(null, evt, a, f);
    }
}
 
Example 14
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
public @Override void removeUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    // #38993 - until parent is set - do not do anything
    if (children == null && getParent() == null) {
        return;
    }

    if (useCustomReloadChildren()) {
        customRemoveUpdate(evt, a, f);
    } else {
        super.removeUpdate(evt, a, f); // default element-based update
    }
}
 
Example 15
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
protected void customRemoveUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    int[] offsetRange = getRemoveUpdateRebuildOffsetRange(evt);
    if (offsetRange != null) {
        offsetRebuild(offsetRange[0], offsetRange[1]);
    } else {
        forwardUpdate(null, evt, a, f);
    }
}
 
Example 16
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
public @Override void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    // #38993 - until parent is set - do not do anything
    if (children == null && getParent() == null) {
        return;
    }
    
    super.changedUpdate(e, a, f);
}
 
Example 17
Source Project: netbeans   Source File: GapBoxView.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Create custom child view starting at <code>startOffset</code>.
     *
     * @param f view factory to be used.
     * @param startOffset offset at which the created view must start.
     * @param maxEndOffset maximum ending offset to which the created view
     *  may span.
     * @param elementIndex index of the child element that best represents
     *  the startOffset. The element is child of the element that this view
     *  is responsible for. If this view is not based by element then this
     *  parameter will be -1.
     */
    protected View createCustomView(ViewFactory f,
    int startOffset, int maxEndOffset, int elementIndex) {


/*
        // Default implementation delegating to view factory
        // is here just to show the possible functionality
        // and clarify the variables

        View v;
        if (parentElement != null) {
            Element elem = parentElement.getElement(elementIndex);
            if (elem.getStartOffset() != startOffset) {
                throw new IllegalStateException("Not element boundary");
            }

            if (elem.getEndOffset() > maxEndOffset) {
                throw new IllegalStateException("Beyond maximum ending offset");
            }

            v = f.create(elem);

        } else { // no element - need more information
            return null;
        }
 */
            
        return null;
    }
 
Example 18
Source Project: netbeans   Source File: GapDocumentView.java    License: Apache License 2.0 5 votes vote down vote up
public void insertUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    layoutLockDepth++;
    try {
        pendingUpdate = false; // Reset before so that child view do not estimate
        super.insertUpdate(evt, a, f);
    } finally {
        updateLayout();
        checkPendingDamageRange();
        layoutLockDepth--;
    }
}
 
Example 19
Source Project: netbeans   Source File: GapDocumentView.java    License: Apache License 2.0 5 votes vote down vote up
public void removeUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    layoutLockDepth++;
    try {
        pendingUpdate = false; // Reset before so that child view do not estimate
        super.removeUpdate(evt, a, f);
    } finally {
        updateLayout();
        checkPendingDamageRange();
        layoutLockDepth--;
    }
}
 
Example 20
Source Project: netbeans   Source File: GapDocumentView.java    License: Apache License 2.0 5 votes vote down vote up
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    layoutLockDepth++;
    try {
        // Do not check pendingUpdate since changedUpdate() is likely invoked by BaseDocument.repaintBlock()
        super.changedUpdate(e, a, f);
    } finally {
        updateLayout();
        layoutLockDepth--;
    }
}
 
Example 21
Source Project: netbeans   Source File: LockView.java    License: Apache License 2.0 5 votes vote down vote up
public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    lock();
    try {
        
        if (view != null) {
            view.insertUpdate(e, a, f);
        }

    } finally {
        unlock();
    }
}
 
Example 22
Source Project: netbeans   Source File: LockView.java    License: Apache License 2.0 5 votes vote down vote up
public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    lock();
    try {
        
        if (view != null) {
            view.removeUpdate(e, a, f);
        }

    } finally {
        unlock();
    }
}
 
Example 23
Source Project: netbeans   Source File: LockView.java    License: Apache License 2.0 5 votes vote down vote up
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    lock();
    try {
        
        if (view != null) {
            view.changedUpdate(e, a, f);
        }

    } finally {
        unlock();
    }
}
 
Example 24
Source Project: netbeans   Source File: LeafView.java    License: Apache License 2.0 5 votes vote down vote up
/** Gives notification that something was inserted into the document
* in a location that this view is responsible for.
*
* @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
*/
public @Override void insertUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    try {
        BaseDocumentEvent bevt = (BaseDocumentEvent)evt;
        EditorUI editorUI = getEditorUI();
        int y = getYFromPos(evt.getOffset());
        int lineHeight = editorUI.getLineHeight();
        if (bevt.getLFCount() > 0) { // one or more lines inserted
            int addHeight = bevt.getLFCount() * lineHeight;
            mainHeight += addHeight;
            editorUI.repaint(y);

        } else { // inserting on one line

            int syntaxY = getYFromPos(bevt.getSyntaxUpdateOffset());
            // !!! patch for case when DocMarksOp.eolMark is at the end of document
            if (bevt.getSyntaxUpdateOffset() == evt.getDocument().getLength()) {
                syntaxY += lineHeight;
            }

            if (getComponent().isShowing()) {
                editorUI.repaint(y, Math.max(lineHeight, syntaxY - y));
            }
        }

    } catch (BadLocationException ex) {
        Utilities.annotateLoggable(ex);
    }
}
 
Example 25
Source Project: netbeans   Source File: LeafView.java    License: Apache License 2.0 5 votes vote down vote up
/** Gives notification from the document that attributes were removed
* in a location that this view is responsible for.
*
* @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
*/
public @Override void removeUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    try {
        BaseDocumentEvent bevt = (BaseDocumentEvent)evt;
        EditorUI editorUI = getEditorUI();
        int y = getYFromPos(evt.getOffset());
        int lineHeight = editorUI.getLineHeight();
        if (bevt.getLFCount() > 0) { // one or more lines removed
            int removeHeight = bevt.getLFCount() * lineHeight;
            mainHeight -= removeHeight;
            editorUI.repaint(y);

        } else { // removing on one line
            int syntaxY = getYFromPos(bevt.getSyntaxUpdateOffset());
            // !!! patch for case when DocMarksOp.eolMark is at the end of document
            if (bevt.getSyntaxUpdateOffset() == evt.getDocument().getLength()) {
                syntaxY += lineHeight;
            }

            if (getComponent().isShowing()) {
                editorUI.repaint(y, Math.max(lineHeight, syntaxY - y));
            }
        }

    } catch (BadLocationException ex) {
        Utilities.annotateLoggable(ex);
    }
}
 
Example 26
Source Project: netbeans   Source File: LeafView.java    License: Apache License 2.0 5 votes vote down vote up
/** Attributes were changed in the are this view is responsible for.
* @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
*/
public @Override void changedUpdate(DocumentEvent evt, Shape a, ViewFactory f) {
    try {
        if (getComponent().isShowing()) {
            getEditorUI().repaintBlock(evt.getOffset(), evt.getOffset() + evt.getLength());
        }
    } catch (BadLocationException ex) {
        Utilities.annotateLoggable(ex);
    }
}
 
Example 27
Source Project: Bytecoder   Source File: ImageView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invoked when the Elements attributes have changed. Recreates the image.
 */
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    super.changedUpdate(e,a,f);

    synchronized(this) {
        state |= RELOAD_FLAG | RELOAD_IMAGE_FLAG;
    }

    // Assume the worst.
    preferenceChanged(null, true, true);
}
 
Example 28
Source Project: visualvm   Source File: SyntaxView.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void updateDamage(javax.swing.event.DocumentEvent changes,
        Shape a,
        ViewFactory f) {
    super.updateDamage(changes, a, f);
    java.awt.Component host = getContainer();
    host.repaint();
}
 
Example 29
@Override
public ViewFactory getViewFactory() {
	return new HTMLFactory() {

		@Override
		public View create(Element elem) {
			View view = super.create(elem);
			if (view instanceof ImageView) {
				((ImageView) view).setLoadsSynchronously(true);
			}
			return view;
		}
	};
}
 
Example 30
Source Project: jdk8u_jdk   Source File: ImageView.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invoked when the Elements attributes have changed. Recreates the image.
 */
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    super.changedUpdate(e,a,f);

    synchronized(this) {
        state |= RELOAD_FLAG | RELOAD_IMAGE_FLAG;
    }

    // Assume the worst.
    preferenceChanged(null, true, true);
}