Font metrics of an attributed string

The Graphics.drawString(AttributedCharacterIterator, int, int) can paint a rich text, but how could I get its width without the TextLayout?

In PP 1.0 you can't even draw it! The only class which uses it is AttributedString, and nothing uses that.
Short answer: yes, it's a design failure.
Long answer: in theory, you should be able to get the attributes and work it out yourself.

Similar Messages

  • How to add attributed string to JTextPane

    Hi all,
    Could you tell me how to add an attributed string into a Textpane.
    Textpane only takes a styledDocument. Is there any way to convert attributed string into a styled document.
    Are there any components , which we can include attributed string , instead of simple string. Becoz i want my text to have variable fonts.

    Hello,
    check this short course about [url http://developer.java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html#JFCStyled]JTextPane and StyledDocument.
    Heres a small example:import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.*;
    public class AttributedStringTest extends JFrame
         public static void main(String[] args)
              new AttributedStringTest();
         private JTextPane textPane = null;
         private StyledDocument doc = null;
         AttributedStringTest()
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initMenuBar();
              initTextPane();
              setSize(500, 300);
              setLocationRelativeTo(null);
              setVisible(true);
         private void initMenuBar()
              JMenuBar mbar = new JMenuBar();
              JMenu menu = new JMenu("StyleConstants");
              JMenuItem item = new JMenuItem("Color");
              item.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Color color =
                             JColorChooser.showDialog(
                                  AttributedStringTest.this,
                                  "Color Chooser",
                                  Color.cyan);
                        if (color != null)
                             MutableAttributeSet attr = new SimpleAttributeSet();
                             StyleConstants.setForeground(attr, color);
                             textPane.setCharacterAttributes(attr, false);
              menu.add(item);
              JMenu font = new JMenu("Font");
              font.add(item = new JMenuItem("12"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-12", 12));
              font.add(item = new JMenuItem("24"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-24", 24));
              font.add(item = new JMenuItem("36"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-36", 36));
              font.addSeparator();
              font.add(item = new JMenuItem("Serif"));
              item.setFont(new Font("Serif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Serif", "Serif"));
              font.add(item = new JMenuItem("SansSerif"));
              item.setFont(new Font("SansSerif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-SansSerif", "SansSerif"));
              font.add(item = new JMenuItem("Monospaced"));
              item.setFont(new Font("Monospaced", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Monospaced", "Monospaced"));
              font.addSeparator();
              menu.add(font);
              mbar.add(menu);
              setJMenuBar(mbar);
         private void initTextPane()
              doc = new DefaultStyledDocument();
              textPane = new JTextPane(doc);
              JScrollPane scroll = new JScrollPane(textPane);
              getContentPane().add(scroll);
              final JTextField text = new JTextField();
              text.setToolTipText("Please enter something");
              text.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             doc.insertString(doc.getLength(), text.getText(), textPane.getInputAttributes());
                        } catch (BadLocationException bad)
              getContentPane().add(text, BorderLayout.SOUTH);
    //not formatted version:import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.*;
    public class AttributedStringTest extends JFrame
         public static void main(String[] args)
              new AttributedStringTest();
         private JTextPane textPane = null;
         private StyledDocument doc = null;
         AttributedStringTest()
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initMenuBar();
              initTextPane();
              setSize(500, 300);
              setLocationRelativeTo(null);
              setVisible(true);
         private void initMenuBar()
              JMenuBar mbar = new JMenuBar();
              JMenu menu = new JMenu("StyleConstants");
              JMenuItem item = new JMenuItem("Color");
              item.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Color color =
                             JColorChooser.showDialog(
                                  AttributedStringTest.this,
                                  "Color Chooser",
                                  Color.cyan);
                        if (color != null)
                             MutableAttributeSet attr = new SimpleAttributeSet();
                             StyleConstants.setForeground(attr, color);
                             textPane.setCharacterAttributes(attr, false);
              menu.add(item);
              JMenu font = new JMenu("Font");
              font.add(item = new JMenuItem("12"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-12", 12));
              font.add(item = new JMenuItem("24"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-24", 24));
              font.add(item = new JMenuItem("36"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-36", 36));
              font.addSeparator();
              font.add(item = new JMenuItem("Serif"));
              item.setFont(new Font("Serif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Serif", "Serif"));
              font.add(item = new JMenuItem("SansSerif"));
              item.setFont(new Font("SansSerif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-SansSerif", "SansSerif"));
              font.add(item = new JMenuItem("Monospaced"));
              item.setFont(new Font("Monospaced", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Monospaced", "Monospaced"));
              font.addSeparator();
              menu.add(font);
              mbar.add(menu);
              setJMenuBar(mbar);
         private void initTextPane()
              doc = new DefaultStyledDocument();
              textPane = new JTextPane(doc);
              JScrollPane scroll = new JScrollPane(textPane);
              getContentPane().add(scroll);
              final JTextField text = new JTextField();
              text.setToolTipText("Please enter something");
              text.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             doc.insertString(doc.getLength(), text.getText(), textPane.getInputAttributes());
                        } catch (BadLocationException bad)
              getContentPane().add(text, BorderLayout.SOUTH);
    regards
    Tim

  • Font metrics info

    Hi,
    I'm trying to develop a VI to format text for a report generator (trying
    to be better, than the one with LV5.1), for this VI, I need to get
    information (at run-time) about the size of the fonts (font metrics, I
    think) in order to be able to perform text formating.
    Does anybody know a way I can ask this information to Windows 9x, at
    run-time from Labview.
    Thanks,
    Leopoldo
    Sent via Deja.com http://www.deja.com/
    Before you buy.

    Here's some code based on jsalonen's suggestion. It prints the font if M and i are the same width.
       public static void main(String[] args) {
          GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
          Font[] s=ge.getAllFonts();
          Canvas comp=new Canvas();
          for(int i=0;i<s.length;i++) {
             int f1=comp.getFontMetrics(s).charWidth('i');
    int f2=comp.getFontMetrics(s[i]).charWidth('M');
    if(f1==f2) System.out.println(s[i].getName());

  • Sapscript font metrics generate AFM file howto

    Hi scripters,
    I'm creating an 11pt font for HPLJ5SI.
    In SE73, I created new system fonts HELVE 110 normal, bold and so on.
    Then SE73 printer fonts for ZHPLJ5SI, same as system fonts. All other HELVE and TIMES fonts have AFM set for cpi. The fontmetrics are displayed as (i.e.( "sapLinkToAFM HPLJ5SI HELVE 100 false false".
    I created (also in SE73) new print controls; I derived the correct value comparing the respective HEX strings for 10 point and 12 point HELVE.
    I tried "sapLinkToAFM HPLJ5SI HELVE 110 false false" but this does not generate.
    Now I used the same definition as for 10 points. The output looks fine but I have doubts about the character spacing: It looks different from what I print from MS Word ARIAL.
    I remember there is a (DOS) program to generate font metrics but I forgot the details; Note 12462 does not really help.
    I would appreciate a step-by-step guide or a link to a good description.
    Best Regards,
    Clemens Li

    Hi,
    Are you trying to generate a PDF file or print to a printer. It is not a good idea to try adding HELVECYR to device type PDF1. You should create the PDF via a device type that supports Cyrillic characters like SAPWIN or SAPWIN5. Also you need to upload true type fonts that support the cyrillic charcters as described in SAP note 322998.
    Alternatively if you have a unicode system, you can use unicode device type PDFUC. It is still necessary to upload true type fonts that support the cyrillic charcters. See SAP note 999712.
    regards,
    Aidan

  • Inconsistent font metrics

    I am printing a report. For each page, I go through all the text that I want to print on that page using FontMetrics.stringWidth to determine how much space the string will take, and using this information to make decisions about spacing and layout. Then I make a second pass through all the Strings where I actually print them. I do a stringWidth on each String again in this second pass to make final decisions about placement.
    And here's the strange part: When I do the second stringWidth, I sometimes get a different value than I did from the first stringWidth! Even though the difference is just one or two percent, this messes up my calculations, because I had this silly idea that the width of the String would be the same no matter how many times I ask.
    Slightly subtracting from the strangeness: When I begin the page, I create all the Fonts I will need, and then I do a Graphics.getFontMetrics(font) to get a FontMetrics object for each, which I use in the first round of calculations. When I get to the second round of calculations, I have now done a setFont() of the appropriate font, and then I do a getFontMetrics with no parameter to get the font metrics for that font. So it's a different FontMetrics object, but its for the same Font on the same Graphics. Shouldn't they be identical? (I am quite sure that the Font is the same in both cases.)
    I can work around the problem by saving the FontMetrics object I get the first time and just using it again the second time. (I suppose it would be better still to save the size and thus save the redundant calculation, but that would be a pain.) But I would like to understand what is going on. Any words of wisdom?

    I've never been working much with font metrics however i'm aware drawing in java has some incoherencies, like if you draw a hollow circle and a filled circle with the same coords they won't have the same size, etc. you should keep the same values or access the font metrics the same way twice. otherwise, i can't see... you can just keep an array ndicating the size of each line, etc.

  • Cannot Read Font Metrics Issue on Save As PDF

    Hi All
    On saving a document as PDF, the FrameMaker Console displays the message:
    The font file may be damaged.
    maker: Cannot read font metrics from font file named Tahoma-Bold.
    The PDF is created but it contains squares in place of letters.
    This only happens for one document within my book.
    I have removed and reinstalled Tahoma, with no effect.
    What has happened and what do I need to do to enable save to PDF for this document.
    I am using FrameMaker 9.0 installed as part of Technical Suite 2 and running on Windows 7 professional.
    Thank you for your help.
    Claire

    I'm on FrameMaker 10, installed about a month ago, and suddenly, yesterday, I started getting this exact error on PDFing a book I'd previously had no trouble with. Nothing apparently changed in my setup between everything working fine and getting these "the font file may be damaged" console errors. Interestingly, it's on exactly the same font as reported by Claire and MichaelH; Tahoma and Tahoma-Bold are listed as the troublesome fonts. These are not the commonplace Frame console "missing font" errors -- they totally mess up the PDF.
    Both these fonts work perfectly in Word. We tried reinstalling, with no change, and I was about to call Adobe support, as recommended by our IT desk, but checked this forum first.  A million thanks, Michael Müller-Hillebrand, for posting the exact solution to the problem. I cleared the Convert CMYK to RGB box and everything is fine now. Thank you SO much.
    Adobe, could you please fix this? First message on this thread was almost a year ago and my copy of Frame was purchased last month. The issue should have been fixed by now. This has cost me about three hours, plus the time of the IT desk reinstalling FrameMaker.

  • What is font metric ?? (HELP)

    hi, i am currently doing my project using java... 1 of the features in my system is the changing of font type and size of selected text... however my teacher wants me to make use of font metric (hope i never spelled wrongly)...
    can someone tells me wat is font metric ? and any examples to show??
    i appreciate all helps....

    The following code should get get the height and ascent of the font of any componant or object that inherits from componant. (I haven't compiled or run this code so it may contain errors)Componant yourComponant = new Componant();
    Font yourFont = yourComponant.getFont();
    FontMetrics yourFontMetrics = getFontMetrics(yourFont);
    int fontHeight = yourFontMetrics.getHeight();
    int fontAscent = yourFontMetrics.getAscent();fontHeight contains the height of a line of text in this font.
    fontAscent contains the the ascent of this font (from baseline to the top of most characters).
    Follow the link in the last post to see all the methods and what they do.

  • Font Metrics, Completely Wrong Values

    So what's the deal with font metrics?
    The values it gives are completely wrong.
    For example with a monospaced font i printed out every single
    character on screen (upper, lower, 0-9, symbols).
    The font metrics were:
    ascent: 17
    descent: 5
    height: 22
    leading: 0
    Im trying to find the correct ascent. The REAL ascent is only 10.
    The font metrics value is off by 70% and it usually is off by a lot for
    all the fonts ive tried. The descent is off by 2 which isnt bad i guess.
    Anyone know how to get the ACTUAL size?
    in this picture the ascent is high but in my experience it is much higher:
    http://www.devx.com/Java/Article/7932/1954?pf=true

    The Line and Font Metric units are pixels not points.
    That applet doesnt work.
    Any attempt to use the "patch" results in:
    Exception in thread "AWT-EventQueue-2" java.lang.NoSuchMethodError: gui.PatchFontMetrics.patch(Ljava/awt/FontMetrics;)Lgui/PatchFontMetrics;
         at test.FontInfo.describeFont(FontInfo.java:56)
         at test.FontInfo.handleEvent(FontInfo.java:77)

  • Attributed String

    I have a attributed string in unicode character which i have to print in JTextArea using SetText() method.
    It doesnt accept attributed string.
    Please help solve the query.

    If you mean the class AttributedString,then it can only be displayed in JTextPane.
    So use JTextPane instead of JTextArea.

  • How to obtain font metric?

    Hi all,
    I want to obtain a font metric of each character in font (i.e. detph, height and width). Does anybody know how?
    thanks

    Hi Lukas,
    I think what you are looking for may be found in IFontInstance. Have a look at the SingleLineComposer sample in the SDK. Particularly SLCTextGlyphNode.cpp could have something that will suit your needs. While it's not as easy as something like GetFontHeight() would be, it should get you what you need after you have the right glyph ID.
    Best regards,
    Art

  • Obtaining/Exporting Font Metrics through a Script

    I have a Text Layer consisting of characters with varying font metrics (say Font Height, Typeface, Kerning, Leading etc). Am unable to export out the Font metrics through an AE script.
    I was able to get the Font Name, Height, Fill and Stroke properties of the first character from the Text Document.
    var textDoc = layer("sourceText") ;
    var textDef = textDoc.valueAtTime(0, false) ;
    I was able to get the Font Name, height, justification, fill and stroke properties from textDef.
    But, I have no clue about getting the other properties like Kerning,  Leading, Tracking etc.
    It will be ideal if I can get all the concerned font metrics of each character in the Text Layer (separately).
    Thanks in advance.

    Unity used to have this wonderful voting system for feature requests.  So users could simply spend votes on those things that they ageed were needed/desirable in future versions.
    This process is GREAT for end users, as we can all see what everyone else is thinking about... and have others see what we're thinking about in terms of features.
    If we're all similarly frustrated by something, we can publicly draw the attention of other users, and the developers, to that issue/desire/need.  And it gets done faster, more transparently, and everyone is happy.
    Adobe, being Adobe, doesn't want anyone to know what anyone else finds as limited, missing, necessary, desirable, etc... because they don't want to be held accountable for their products by their users.
    But I agree, access to text's metrics/properties is an essential next and incredibly logical step for AE. 
    However blindly hoping others will know where to look (in scripting) for the ability to look at text metrics to do something like create styles is really pulling the wool over the eyes of users.
    And... let's be honest... why does it matter what users want... they're already using AE.  The real voice is new potential users, someone that Adobe spends all their time telling that Illustrator and Indesign are optimised, rather than figuring out how to add common sense functionality to AE.
    Never mind...
    The world still turns.

  • Need help with attributed string in NSMenuItem

    I'm trying to implement a contextual menu for a view in one of my applications. I want it to be dynamic, based on where you click in the view. It works fine if I don't try to mess with the font size of the menu. If I try to make the menu font smaller, the menu will appear blank, and its action won't get triggered, but only if there's only one menu item. If there are two or more, they'll all show up.
    I've done a bunch of searching, and found some code examples where they put in a dummy item, then remove it later, but so far, that hasn't helped me, either. I've posted an example project (~44KB) on my web site that illustrates this, if you'd like to see it in action (the example doesn't include the "dummy fix", by the way, but it's easy enough to add).
    Here's the code where I customize the menu:
    <pre class="command">-(NSMenu *)menuForEvent:(NSEvent *)theEvent
    NSPoint mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
    NSLog(@"Raw Mouse Location: %2.1f, %2.1f", mouseLoc.x, mouseLoc.y);
    // Get my blank menu:
    NSMenu *tzMenu = [self defaultMenu];
    // Set up my string attributes:
    NSMutableDictionary *menuAttributes = [[NSMutableDictionary alloc] init];
    [menuAttributes setObject:[NSFont fontWithName:@"Lucida Grande" size:11] forKey:NSFontAttributeName];
    if (mouseLoc.x < 220) // Make just one menu item.
    int i;
    for (i=0; i<1; i++)
    [tzMenu addItemWithTitle:@"Item" action:@selector(changeMapDot:) keyEquivalent:@""];
    NSMenuItem *lastItem = [tzMenu itemAtIndex:[tzMenu numberOfItems] - 1];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Item" attributes:menuAttributes];
    // Comment out this next line and the menu item appears in the default font:
    [lastItem setAttributedTitle:attrString];
    [attrString release];
    else
    int i;
    for (i=0; i<3; i++) //Make three items. These always appear.
    [tzMenu addItemWithTitle:@"Item" action:@selector(changeMapDot:) keyEquivalent:@""];
    NSMenuItem *lastItem = [tzMenu itemAtIndex:[tzMenu numberOfItems] - 1];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Item" attributes:menuAttributes];
    [lastItem setAttributedTitle:attrString];
    [attrString release];
    [menuAttributes release];
    return tzMenu;
    }</pre>Any tips that anyone has would be most apprecitated.
    I'm not unalterably opposed to the regular system menu font if there's no way around this (the menus are pretty short: usually less then a dozen items), but aesthetically it looks nicer with a smaller font.
    charlie

    Hi,
    You can use SUBSTR and INSTR
    This should work in Oracle 9:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    ,     got_pos          AS
         SELECT     x.txt
         ,     c.n
         ,     INSTR (x.txt, '[', 1, c.n)     AS l_pos
         ,     INSTR (x.txt, ']', 1, c.n)     AS r_pos
         FROM           table_x  x
         CROSS JOIN    cntr     c
    SELECT        txt
    ,        n
    ,        SUBSTR ( txt
                   , l_pos + 1
                , r_pos - (l_pos + 1)
                   )     AS sub_txt
    FROM        got_pos
    ORDER BY   txt
    ,             n
    ;Sorry, I don't have an Oracle 9 database available now; I had to test this in Oracle 10.
    jimmy437 wrote:
    ... I have tried the "REGEXP_SUBSTR" but my database version is 9i, and it is available only from 10g.That's true. Regular expressions are very useful, but they're not available in Oracle 9 (or earlier).
    Oracle 9 does have an Oracle-supplied package, OWA_PATTERN, that provides some regular expression functionality:
    http://docs.oracle.com/cd/B12037_01/appdev.101/b10802/w_patt.htm
    I know that's the Oracle 10, documentation, but it exists in Oracle 9, too.
    Oracle 9 is very old. You should consider upgrading.

  • Picky DN attribute strings

    Just installed 5.0 SP1 and searches with filters that are user defined
    attributes of type DN are treated strangely.
    Server defined attributes of type DN work fine.
    Spaces in the DN somtimes cause problems.........
    This is difficult to relay, so bear with me:
    Search with filter.....
    1)
    owner=bankid=12345, ou=traders, o=bank of chicago
    OK - get expected return
    2)
    owner=bankid=12345, ou=traders, o =bank of chicago
    OK - get expected return
    We have similar cases with uniquemember...both strings return what we
    expect.
    However
    3)
    company=vendorid=12345, ou=externalcompany, o=bank of chicago
    OK - get expected return
    4)
    company=vendorid=12345, ou=externalcompany, o =bank of chicago
    BAD - no returns
    Same situation with other user defined attributes of type DN in a filter.
    Hope this problem is clear. Any help?
    TIA,
    Joe

    Hi Joe,
    I don't think that you can put a space between the attribute type and the equality sign. So, if the search returns nothing in that case, that should be normal.
    Bertold

  • More than one attribute in Attributed String

    I want to write a text in an applet with a specific font and making some characters of the text be written in superscript
    If I don't specify the font, the superscript appears right. If I specify the font, it also appears accordingly
    But if I specify both, only the font is used and there is no superscript in the lay out
    This is the code I'm using
         AttributedString as1 = new AttributedString(info);
         as1.addAttribute(TextAttribute.FONT,ff);
         as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, posbase+igual.length(), posbase+igual.length()+sp.length());
         g.drawString(as1.getIterator(), x+d[0], y+d[1]);
    If I comment out any of the addAttribute calls, it gets rendered as expected
    Any idea?
    Thanks in advance

    I thought it might, as I vaguely recall having a similar problem with Font that was solved by using the form of deriveFont that takes a Map.
    db

  • Font metrics

    I am having a dialog font with size 12. I want to change the ascent,height and width for the font.But using fontmetrics we can get the ascent,height,width etc..
    But there is no API to set the same .Is it possible by any workaround

    package library;
    public class Library {
      public static Font getCommonFont() {
        return new Font( // whatever you like here
    }Then in applets:
    import library.*;
    Font myFont = Library.getCommonFont();

Maybe you are looking for