joybee has asked for the wisdom of the Perl Monks concerning the following question:

Hello! My question is:

I used sprintf to format two fields into a two column string, in the stdout two columns aligned well but when I inserted string into a listbox which use specific fonts (eg. Times), then alignment got lost.

Any solutions? Thanks!

Example:

abc 123

stwd 4565

Replies are listed 'Best First'.
Re: string alignment
by BrowserUk (Patriarch) on Feb 17, 2012 at 22:12 UTC

    If the listbox is using a proportional font, then sprintf alignment (which is based on equal width characters) will not do the job.

    Three possibilities:

    1. Set the font in the listbox to a fixed pitch font.
    2. Investigate the font metrics tools available in the toolkit you are using.

      Eg. If you are using Tk, take a look at $widget->fontMeasure(font, text).

    3. Use a more sophisticated widget setup.

      Eg. use a Tk::Table (or equivalent for your toolkit).


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re: string alignment
by tobyink (Canon) on Feb 17, 2012 at 22:18 UTC

    Times Roman is a proportional font. Different letters are different widths. An "m" is about four times the width of an "i".

    sprintf can align strings in terms of number of characters, but if your font's characters are all different widths, then sprintf won't help you. sprintf neither knows or cares what font you are using.

Re: string alignment
by Riales (Hermit) on Feb 17, 2012 at 21:57 UTC

    I don't know what a listbox is, but here's a guess:

    The first thing I would point out is that not all fonts have characters that are all the same width. Based on your code sample, however, it looks like the listbox is condensing sequences of spaces into a single space. Have you tried using the   character?

      Based on your code sample ...

      What code sample?

        Whoops, not code sample, but just example. Sorry!