java.text.AttributedString Java Examples

The following examples show how to use java.text.AttributedString. 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 File: OracleText.java    From magarena with GNU General Public License v3.0 6 votes vote down vote up
static void drawTextToCard(
    BufferedImage cardImage,
    int xPos,
    int yPos,
    String oracleText,
    Rectangle textBoxBounds) {

    AttributedString realOracle = textIconReplace(oracleText);

    BufferedImage textBoxText = drawTextToBox(
        realOracle,
        cardTextFont,
        textBoxBounds,
        leftPadding,
        topPadding
    );

    Graphics2D g2d = cardImage.createGraphics();
    BufferedImage trimmedTextBox = trimTransparency(textBoxText);
    int heightPadding = (int)((textBoxBounds.getHeight() - trimmedTextBox.getHeight()) / 2);
    int widthPadding = (int)Math.min((textBoxBounds.getWidth() - trimmedTextBox.getWidth()) / 2, 3);
    g2d.drawImage(trimmedTextBox, xPos + widthPadding, yPos + heightPadding, null);
    g2d.dispose();
}
 
Example #2
Source File: TextLayout.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> from a <code>String</code>
 * and an attribute set.
 * <p>
 * All the text is styled using the provided attributes.
 * <p>
 * <code>string</code> must specify a single paragraph of text because an
 * entire paragraph is required for the bidirectional algorithm.
 * @param string the text to display
 * @param attributes the attributes used to style the text
 * @param frc contains information about a graphics device which is needed
 *       to measure the text correctly.
 *       Text measurements can vary slightly depending on the
 *       device resolution, and attributes such as antialiasing.  This
 *       parameter does not specify a translation between the
 *       <code>TextLayout</code> and user space.
 */
public TextLayout(String string, Map<? extends Attribute,?> attributes,
                  FontRenderContext frc)
{
    if (string == null) {
        throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
    }

    if (string.length() == 0) {
        throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
    }

    char[] text = string.toCharArray();
    Font font = singleFont(text, 0, text.length, attributes);
    if (font != null) {
        fastInit(text, font, attributes, frc);
    } else {
        AttributedString as = new AttributedString(string, attributes);
        standardInit(as.getIterator(), text, frc);
    }
}
 
Example #3
Source File: TestAttributedStringCtor.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {

        // Create a new AttributedString with one attribute.
        Hashtable attributes = new Hashtable();
        attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
        AttributedString origString = new AttributedString("Hello world.", attributes);

        // Create an iterator over part of the AttributedString.
        AttributedCharacterIterator iter = origString.getIterator(null, 4, 6);

        // Attempt to create a new AttributedString from the iterator.
        // This will throw IllegalArgumentException.
        AttributedString newString = new AttributedString(iter);

        // Without the exception this would get executed.
        System.out.println("DONE");
    }
 
Example #4
Source File: X11InputMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches committed text from XIM to the awt event queue. This
 * method is invoked from the event handler in canvas.c in the
 * AWT Toolkit thread context and thus inside the AWT Lock.
 * @param   str     committed text
 * @param   long    when
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void dispatchCommittedText(String str, long when) {
    if (str == null)
        return;

    if (composedText == null) {
        AttributedString attrstr = new AttributedString(str);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             str.length(),
                             null,
                             null,
                             when);
    } else {
        // if there is composed text, wait until the preedit
        // callback is invoked.
        committedText = str;
    }
}
 
Example #5
Source File: TextLayout.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> from a <code>String</code>
 * and an attribute set.
 * <p>
 * All the text is styled using the provided attributes.
 * <p>
 * <code>string</code> must specify a single paragraph of text because an
 * entire paragraph is required for the bidirectional algorithm.
 * @param string the text to display
 * @param attributes the attributes used to style the text
 * @param frc contains information about a graphics device which is needed
 *       to measure the text correctly.
 *       Text measurements can vary slightly depending on the
 *       device resolution, and attributes such as antialiasing.  This
 *       parameter does not specify a translation between the
 *       <code>TextLayout</code> and user space.
 */
public TextLayout(String string, Map<? extends Attribute,?> attributes,
                  FontRenderContext frc)
{
    if (string == null) {
        throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
    }

    if (string.length() == 0) {
        throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
    }

    char[] text = string.toCharArray();
    Font font = singleFont(text, 0, text.length, attributes);
    if (font != null) {
        fastInit(text, font, attributes, frc);
    } else {
        AttributedString as = new AttributedString(string, attributes);
        standardInit(as.getIterator(), text, frc);
    }
}
 
Example #6
Source File: LogAxis.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a tick label for the specified value based on the current
 * tick unit (used for formatting the exponent).
 *
 * @param value  the value.
 *
 * @return The label.
 *
 * @since 1.0.18
 */
protected AttributedString createTickLabel(double value) {
    if (this.numberFormatOverride != null) {
        return new AttributedString(
                this.numberFormatOverride.format(value));
    } else {
        String baseStr = this.baseSymbol;
        if (baseStr == null) {
            baseStr = this.baseFormatter.format(this.base);
        }
        double logy = calculateLog(value);
        String exponentStr = getTickUnit().valueToString(logy);
        AttributedString as = new AttributedString(baseStr + exponentStr);
        as.addAttributes(getTickLabelFont().getAttributes(), 0, (baseStr 
                + exponentStr).length());
        as.addAttribute(TextAttribute.SUPERSCRIPT, 
                TextAttribute.SUPERSCRIPT_SUPER, baseStr.length(), 
                baseStr.length() + exponentStr.length());
        return as;
    }
}
 
Example #7
Source File: X11InputMethod.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches committed text from XIM to the awt event queue. This
 * method is invoked from the event handler in canvas.c in the
 * AWT Toolkit thread context and thus inside the AWT Lock.
 * @param   str     committed text
 * @param   when    when
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void dispatchCommittedText(String str, long when) {
    if (str == null)
        return;

    if (composedText == null) {
        AttributedString attrstr = new AttributedString(str);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             str.length(),
                             null,
                             null,
                             when);
    } else {
        // if there is composed text, wait until the preedit
        // callback is invoked.
        committedText = str;
    }
}
 
Example #8
Source File: X11InputMethod.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches committed text from XIM to the awt event queue. This
 * method is invoked from the event handler in canvas.c in the
 * AWT Toolkit thread context and thus inside the AWT Lock.
 * @param   str     committed text
 * @param   long    when
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void dispatchCommittedText(String str, long when) {
    if (str == null)
        return;

    if (composedText == null) {
        AttributedString attrstr = new AttributedString(str);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             str.length(),
                             null,
                             null,
                             when);
    } else {
        // if there is composed text, wait until the preedit
        // callback is invoked.
        committedText = str;
    }
}
 
Example #9
Source File: TextLayout.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> from a <code>String</code>
 * and an attribute set.
 * <p>
 * All the text is styled using the provided attributes.
 * <p>
 * <code>string</code> must specify a single paragraph of text because an
 * entire paragraph is required for the bidirectional algorithm.
 * @param string the text to display
 * @param attributes the attributes used to style the text
 * @param frc contains information about a graphics device which is needed
 *       to measure the text correctly.
 *       Text measurements can vary slightly depending on the
 *       device resolution, and attributes such as antialiasing.  This
 *       parameter does not specify a translation between the
 *       <code>TextLayout</code> and user space.
 */
public TextLayout(String string, Map<? extends Attribute,?> attributes,
                  FontRenderContext frc)
{
    if (string == null) {
        throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Null map passed to TextLayout constructor.");
    }

    if (string.length() == 0) {
        throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
    }

    char[] text = string.toCharArray();
    Font font = singleFont(text, 0, text.length, attributes);
    if (font != null) {
        fastInit(text, font, attributes, frc);
    } else {
        AttributedString as = new AttributedString(string, attributes);
        standardInit(as.getIterator(), text, frc);
    }
}
 
Example #10
Source File: SwingUtilities2.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator
        (AttributedCharacterIterator iterator) {
    int curIdx = iterator.getIndex();

    char c = iterator.last();
    while(c != CharacterIterator.DONE && Character.isWhitespace(c)) {
        c = iterator.previous();
    }

    if (c != CharacterIterator.DONE) {
        int endIdx = iterator.getIndex();

        if (endIdx == iterator.getEndIndex() - 1) {
            iterator.setIndex(curIdx);
            return iterator;
        } else {
            AttributedString trimmedText = new AttributedString(iterator,
                    iterator.getBeginIndex(), endIdx + 1);
            return trimmedText.getIterator();
        }
    } else {
        return null;
    }
}
 
Example #11
Source File: CodePointInputMethod.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the composed text to the client.
 */
private void sendComposedText() {
    AttributedString as = new AttributedString(buffer.toString());
    as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
            InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), 0,
            TextHitInfo.leading(insertionPoint), null);
}
 
Example #12
Source File: GivenMembersDeclaredInClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void haveSimpleNameNotEndingWith() {
    List<JavaMember> members = filterResultOf(members().that().areDeclaredInClassesThat().haveSimpleNameNotEndingWith("String"))
            .on(String.class, AttributedString.class, StringBuilder.class);

    assertThatMembers(members).matchInAnyOrderMembersOf(StringBuilder.class);
}
 
Example #13
Source File: CodePointInputMethod.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the committed text to the client.
 */
private void sendCommittedText() {
    AttributedString as = new AttributedString(buffer.toString());
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), buffer.length(),
            TextHitInfo.leading(insertionPoint), null);

    buffer.setLength(0);
    insertionPoint = 0;
    format = UNSET;
}
 
Example #14
Source File: TimeZoneFormat.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
    StringBuffer toAppendTo = new StringBuffer();
    FieldPosition pos = new FieldPosition(0);
    toAppendTo = format(obj, toAppendTo, pos);

    // supporting only DateFormat.Field.TIME_ZONE
    AttributedString as = new AttributedString(toAppendTo.toString());
    as.addAttribute(DateFormat.Field.TIME_ZONE, DateFormat.Field.TIME_ZONE);

    return as.getIterator();
}
 
Example #15
Source File: LegendItem.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a legend item using a line.
 * 
 * @param label  the label (<code>null</code> not permitted).
 * @param description  the description (<code>null</code> permitted).
 * @param toolTipText  the tool tip text (<code>null</code> permitted).
 * @param urlText  the URL text (<code>null</code> permitted).
 * @param line  the line (<code>null</code> not permitted).
 * @param lineStroke  the line stroke (<code>null</code> not permitted).
 * @param linePaint  the line paint (<code>null</code> not permitted).
 */
public LegendItem(AttributedString label, String description, 
                  String toolTipText, String urlText, 
                  Shape line, Stroke lineStroke, Paint linePaint) {
    
    this(label, description, toolTipText, urlText,
            /* shape visible = */ false, UNUSED_SHAPE,
            /* shape filled = */ false, Color.black,
            /* shape outlined = */ false, Color.black, UNUSED_STROKE,
            /* line visible = */ true, line, lineStroke, linePaint
    );
}
 
Example #16
Source File: VectorImageTest.java    From pumpernickel with MIT License 5 votes vote down vote up
private AttributedString createAttributedString() {
	AttributedString attrStr = new AttributedString("¿was it a rat I saw?");
	attrStr.addAttribute(TextAttribute.FONT, new Font("Georgia", 0, 15), 1,
			4);
	attrStr.addAttribute(TextAttribute.BACKGROUND, Color.cyan, 5, 7);
	attrStr.addAttribute(TextAttribute.FOREGROUND, Color.orange, 0, 1);
	Paint gradient = new GradientPaint(0, 0, Color.red, 0, 3, Color.yellow,
			true);
	attrStr.addAttribute(TextAttribute.FOREGROUND, gradient, 19, 20);
	attrStr.addAttribute(TextAttribute.UNDERLINE, 4, 10, 13);
	return attrStr;
}
 
Example #17
Source File: LumenUtils.java    From radiance with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int paintMultilineText(Graphics2D g2d, String text,
        int textX, int textWidth, int textY, int maxTextLineCount) {
    NeonCortex.installDesktopHints(g2d, g2d.getFont());
    FontRenderContext frc = new FontRenderContext(new AffineTransform(),
            true, false);
    int fa = g2d.getFontMetrics().getAscent();

    if (text.length() == 0)
        return textY;

    int currOffset = 0;
    AttributedString attributedDescription = new AttributedString(text);
    attributedDescription.addAttribute(TextAttribute.FONT, g2d.getFont());
    LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(
            attributedDescription.getIterator(), frc);
    int lineCount = 0;
    while (true) {
        TextLayout tl = lineBreakMeasurer.nextLayout(textWidth);
        if (tl == null)
            break;

        int charCount = tl.getCharacterCount();
        String line = text.substring(currOffset, currOffset + charCount);

        g2d.drawString(line, textX, textY);

        textY += fa;
        currOffset += charCount;

        lineCount++;
        if ((maxTextLineCount > 0) && (lineCount == maxTextLineCount))
            break;
    }

    // textY += fh;

    return textY;
}
 
Example #18
Source File: LegendItemTest.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
@Test
public void testSerialization2() {
    AttributedString as = new AttributedString("Test String");
    as.addAttribute(TextAttribute.FONT, new Font("Dialog", Font.PLAIN, 12));
    LegendItem item1 = new LegendItem(as, "Description", "ToolTip", "URL",
            new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0), Color.red);
    LegendItem item2 = (LegendItem) TestUtilities.serialised(item1);
    assertEquals(item1, item2);
}
 
Example #19
Source File: AxisTest.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks that serialization works, particularly with the attributed label.
 */
@Test
public void testSerialization() {
    Axis a1 = new CategoryAxis("Test");
    AttributedString label = new AttributedString("Axis Label");
    label.addAttribute(TextAttribute.SUPERSCRIPT, 
            TextAttribute.SUPERSCRIPT_SUB, 1, 4);
    a1.setAttributedLabel(label);
    Axis a2 = (Axis) TestUtilities.serialised(a1);
    assertEquals(a1, a2);
}
 
Example #20
Source File: CodePointInputMethod.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the composed text to the client.
 */
private void sendComposedText() {
    AttributedString as = new AttributedString(buffer.toString());
    as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
            InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), 0,
            TextHitInfo.leading(insertionPoint), null);
}
 
Example #21
Source File: CodePointInputMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the committed text to the client.
 */
private void sendCommittedText() {
    AttributedString as = new AttributedString(buffer.toString());
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), buffer.length(),
            TextHitInfo.leading(insertionPoint), null);

    buffer.setLength(0);
    insertionPoint = 0;
    format = UNSET;
}
 
Example #22
Source File: DefaultProcessDiagramCanvas.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void drawLabel(String text, GraphicInfo graphicInfo, boolean centered) {
    float interline = 1.0f;

    // text
    if (text != null && text.length() > 0) {
        Paint originalPaint = g.getPaint();
        Font originalFont = g.getFont();

        g.setPaint(LABEL_COLOR);
        g.setFont(LABEL_FONT);

        int wrapWidth = 100;
        double textY = graphicInfo.getY();

        // TODO: use drawMultilineText()
        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FOREGROUND, g.getPaint());
        as.addAttribute(TextAttribute.FONT, g.getFont());
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = new FontRenderContext(null, true, false);
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);

        while (lbm.getPosition() < text.length()) {
            TextLayout tl = lbm.nextLayout(wrapWidth);
            textY += tl.getAscent();
            Rectangle2D bb = tl.getBounds();
            double tX = graphicInfo.getX();
            if (centered) {
                tX += (int) (graphicInfo.getWidth() / 2 - bb.getWidth() / 2);
            }
            tl.draw(g, (float) tX, (float) textY);
            textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
        }

        // restore originals
        g.setFont(originalFont);
        g.setPaint(originalPaint);
    }
}
 
Example #23
Source File: BidiEmbeddingTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void test2() {
    String target = "BACK WARDS";
    String str = "If this text is >" + target + "< the test passed.";
    int length = str.length();
    int start = str.indexOf(target);
    int limit = start + target.length();

    System.out.println("start: " + start + " limit: " + limit);

    AttributedString astr = new AttributedString(str);
    astr.addAttribute(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL);

    astr.addAttribute(TextAttribute.BIDI_EMBEDDING,
                     new Integer(-3),
                     start,
                     limit);

    Bidi bidi = new Bidi(astr.getIterator());

    for (int i = 0; i < bidi.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi.getRunStart(i) +
                           " to " + bidi.getRunLimit(i) +
                           " at level " + bidi.getRunLevel(i));
    }

    System.out.println(bidi + "\n");

    if (bidi.getRunCount() != 6) { // runs of spaces and angles at embedding bound,s and final period, each get level 1
        throw new Error("Bidi embedding processing failed");
    } else {
        System.out.println("test2() passed.\n");
    }
}
 
Example #24
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void haveSimpleNameStartingWith() {
    List<JavaClass> classes = filterResultOf(classes().that().haveSimpleNameStartingWith("String"))
            .on(AttributedString.class, String.class, StringBuilder.class, Iterable.class);

    assertThatClasses(classes).matchInAnyOrder(String.class, StringBuilder.class);
}
 
Example #25
Source File: LegendItem.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a legend item with a filled shape.  The shape is not outlined,
 * and no line is visible.
 * 
 * @param label  the label (<code>null</code> not permitted).
 * @param description  the description (<code>null</code> permitted).
 * @param toolTipText  the tool tip text (<code>null</code> permitted).
 * @param urlText  the URL text (<code>null</code> permitted).
 * @param shape  the shape (<code>null</code> not permitted).
 * @param fillPaint  the paint used to fill the shape (<code>null</code>
 *                   not permitted).
 */
public LegendItem(AttributedString label, String description, 
                  String toolTipText, String urlText, 
                  Shape shape, Paint fillPaint) {
    
    this(label, description, toolTipText, urlText, 
            /* shape visible = */ true, shape,
            /* shape filled = */ true, fillPaint,
            /* shape outlined = */ false, Color.black, UNUSED_STROKE,
            /* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,
            Color.black);
    
}
 
Example #26
Source File: Axis.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the attributed label for the axis and sends an 
 * {@link AxisChangeEvent} to all registered listeners.
 * 
 * @param label  the label ({@code null} permitted).
 * 
 * @since 1.0.16
 */
public void setAttributedLabel(AttributedString label) {
    if (label != null) {
        this.attributedLabel = new AttributedString(label.getIterator());
    } else {
        this.attributedLabel = null;
    }
    fireChangeEvent();
}
 
Example #27
Source File: LogAxis.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 *
 * @since 1.0.7
 */
protected double estimateMaximumTickLabelWidth(Graphics2D g2, 
        TickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the
        // font)...
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        Range range = getRange();
        double lower = range.getLowerBound();
        double upper = range.getUpperBound();
        AttributedString lowerStr = createTickLabel(lower);
        AttributedString upperStr = createTickLabel(upper);
        double w1 = AttrStringUtils.getTextBounds(lowerStr, g2).getWidth();
        double w2 = AttrStringUtils.getTextBounds(upperStr, g2).getWidth();
        result += Math.max(w1, w2);
    }
    return result;
}
 
Example #28
Source File: AttributedStringUtilities.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests two attributed strings for equality.
 * 
 * @param s1  string 1 (<code>null</code> permitted).
 * @param s2  string 2 (<code>null</code> permitted).
 * 
 * @return <code>true</code> if <code>s1</code> and <code>s2</code> are
 *         equal or both <code>null</code>, and <code>false</code> 
 *         otherwise.
 */
public static boolean equal(AttributedString s1, AttributedString s2) {
    if (s1 == null) {
        return (s2 == null);
    }
    if (s2 == null) {
        return false;
    }
    AttributedCharacterIterator it1 = s1.getIterator();
    AttributedCharacterIterator it2 = s2.getIterator();
    char c1 = it1.first();
    char c2 = it2.first();
    int start = 0;
    while (c1 != CharacterIterator.DONE) {
        int limit1 = it1.getRunLimit();
        int limit2 = it2.getRunLimit();
        if (limit1 != limit2) {
            return false;
        }
        // if maps aren't equivalent, return false
        Map m1 = it1.getAttributes();
        Map m2 = it2.getAttributes();
        if (!m1.equals(m2)) {
            return false;
        }
        // now check characters in the run are the same
        for (int i = start; i < limit1; i++) {
            if (c1 != c2) {
                return false;
            }
            c1 = it1.next();
            c2 = it2.next();
        }
        start = limit1;
    }
    return c2 == CharacterIterator.DONE;
}
 
Example #29
Source File: CodePointInputMethod.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the composed text to the client.
 */
private void sendComposedText() {
    AttributedString as = new AttributedString(buffer.toString());
    as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
            InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), 0,
            TextHitInfo.leading(insertionPoint), null);
}
 
Example #30
Source File: AttributedCharacterIteratorSerializationWrapper.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public AttributedCharacterIterator create() {
	int index = ((Number) map.get(KEY_INDEX)).intValue();
	AttributedStringSerializationWrapper w = (AttributedStringSerializationWrapper) map
			.get(KEY_ATTRIBUTED_STRING);
	AttributedString as = w.create();
	AttributedCharacterIterator iter = as.getIterator();
	iter.setIndex(index);
	return iter;
}