Calculating line length in Java

Hi all;
I've been using LineBreakMeasurer & AttributedString to measure line lengths. However, I now need to take into account:
Small Caps
Scaling (making each character thinner/wider).
Spacing (adding/subtracting space after each character).
Hyphenation, where line breaks can occur at specific places within words.
Is there a way to do this using Java? The two fundamental things I need to get is:
How long is a passed in string.
For a passed in string and length, how many characters of the string fits in that length.
I can do this using LineBreakMeasurer & AttributedString and calling it character by character. But is there a better way?
thanks - dave

Hi, Have you had a look at the FontMetrics class? That might be an option.

Similar Messages

  • How can i plot a histogram with using the results of Line Length

    PLS HELP.How can i prepare a histogram with using the results of line length code(It is somewhere in the middle).
    This is a final exam take-home question. I would appreciate if you can help?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.text.*;
    import java.io.File;
    public class WordAnalyser extends JFrame implements ActionListener
    private JMenuItem jmiAc, jmiSil, jmiCikis, jmiAnaliz, jmiHakkinda, jmiKullanim;
    private JTextArea jta1, jta2;
    private JFileChooser jFileChooser = new JFileChooser();
    File hafizada;
    File aktarilan = new File("Sonuc.txt");
    // Main method
    public static void main(String[] args)
    WordAnalyser frame = new WordAnalyser(); /* Ana ekran olusturulur */
    frame.setSize(400, 300); /* Degerleri belirlenir */
    frame.setVisible(true); /* Gorunebilirligi ayarlanir */
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public WordAnalyser()
    setTitle("Serkan Ozgen Dosya Inceleme Programina Hos Geldiniz");
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    JMenu fileMenu = new JMenu("Dosya");
    fileMenu.setMnemonic('F');
    mb.add(fileMenu);
    JMenu helpMenu = new JMenu("Degerlendirme");
    helpMenu.setMnemonic('H');
    mb.add(helpMenu);
    JMenu kullanimMenu = new JMenu("Kullanim Kilavuzu");
    mb.add(kullanimMenu);     
    fileMenu.add(jmiAc = new JMenuItem("Ac", 'A'));
    fileMenu.add(jmiSil = new JMenuItem("Sil", 'S'));
    fileMenu.add(jmiCikis = new JMenuItem("Cikis", 'C'));
    helpMenu.add(jmiAnaliz = new JMenuItem("Analiz", 'D'));
    helpMenu.add(jmiHakkinda = new JMenuItem("Hakkinda", 'H'));
    kullanimMenu.add(jmiKullanim = new JMenuItem("Kullanim"));     
    getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER);
    getContentPane().add(jta2 = new JTextArea(), BorderLayout.SOUTH);
    jmiAc.addActionListener(this);
    jmiSil.addActionListener(this);
    jmiCikis.addActionListener(this);
    jmiAnaliz.addActionListener(this);
    jmiHakkinda.addActionListener(this);
    jmiKullanim.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem)
    if ("Ac".equals(actionCommand))
    Ac();
    else if ("Sil".equals(actionCommand))
    Sil();
    else if ("Cikis".equals(actionCommand))
    System.exit(0);
    else if ("Analiz".equals(actionCommand))
    sayim();
    else if ("Hakkinda".equals(actionCommand))
    JOptionPane.showMessageDialog(this,
    "!!!! Bu program text analizi gerceklestirir. Her hakki saklidir SERKAN OZGEN!!!!",
    "Bu program hakkinda",
    JOptionPane.INFORMATION_MESSAGE);
    else if ("Kullanim".equals(actionCommand))
         JOptionPane.showMessageDialog(this,
         " Ilk once dosya menusunden Ac i tiklayarak analiz etmek istediginiz Dosyayi seciniz (Lutfen uzantisi *.txt \nveya *.log olsun). Daha sonra Degerlendirme menusunden analizi tiklarsaniz dosyanizda kac adet rakam, harf, \ncumle ve kelime oldugunu gorebilirsiniz. Simdiden kolay gelsin",
         "Programin kullanim detaylari",
         JOptionPane.INFORMATION_MESSAGE);
    private void Ac()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    hafizada = jFileChooser.getSelectedFile();
    Ac(hafizada);
    // Acilan Dosyayi ana ekranda gostermeye yariyan bir method
    private void Ac(File file)
    try
    // Acilan dosyayi okuma ve ana ekranda gosterme
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta1.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    // Temizle tusunun hangi ekranlara etki edecegini secme
    private void Sil()
    jta1.setText("");
    jta2.setText("");
    private void sayim()
    int buff;
    int sayac = 0;
    int Cumleler = 0;
    int Kelimeler = 0;
    int Karakterler = 0;
    int Satirlar = 0;
    int Rakamlar = 0;     
    boolean start = true;
    int linenum = 0;     
    try
    FileInputStream instream = new FileInputStream(hafizada);
    FileOutputStream outstream = new FileOutputStream(aktarilan);
         BufferedReader infile = new BufferedReader(new InputStreamReader(new FileInputStream(hafizada)));
    PrintStream out = new PrintStream(outstream);
         out.println("---Kelime Avcisinin Sonuclari---");
         String line = infile.readLine();
         while (line != null){
         int len = line.length();
         linenum++;
         line = infile.readLine();
         out.println("Line Length :"     + linenum + "\t" +len);
    while ((buff=instream.read()) != -1)
    switch((char)buff)
    case '?': case '.': case '!': /* Eger "?", "." veya "!" gorurse program cumleleri ve kelimeleri arttirir*/
    if (start == false)
    Cumleler++;
    Kelimeler++;
    start = true;
    break;
    case ' ': case '\t': case ',': case ';': case ':': case'\"': case'\'': /* Eger /t,;:\ ve \" bu isarteleri goruruse program kelimeleri arttirir */
    if (start == false)
    Kelimeler++;
    start = true;
    break;
              case 'n': case '\n': /* Eger \n gorurse satirlari arttirir */
              if (start == false)
                   Satirlar++;
                   Kelimeler++;
                   start = true;
              break;
    default:
    if (((char)buff >= 'a' && (char)buff<='z')|| /*a-z, A-Z veya - degerlerini gorurse karakterler arttirilir */
    ((char)buff >= 'A' && (char)buff<='Z')||
    ((char)buff == '-'))
    Karakterler++;
    if ((Kelimeler % 50) == 49)
    if (start == true)
                   out.println();     
    out.print((Kelimeler+1) + " ");
    out.print((char)buff);
    start = false;
              if ((char)buff >='0' && (char)buff <='9') {  /* 0-9 gorurse rakamlari arttiri */
                   Rakamlar++; }
    }// switch
         }//while
    instream.close();
    out.println();
    out.println();
    out.println("Karakter sayisi: " + Karakterler);
         out.println("Kelime sayisi: " + Kelimeler);
    out.println("Cumle sayisi: " + Cumleler);
         out.println("Satir sayisi: "+ Satirlar);
         out.println("Rakam sayisi: "+ Rakamlar);
    outstream.close();
    try
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(aktarilan));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta2.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    catch (Exception e)
    System.out.println(e);
    }

    Why is it that you're not interested in IOExceptions?
    catch (IOException ex)
    } Empty catch blocks is a hallmark of foolish Java code. At least print out the stack trace.
    %

  • Finding the key according to string length in java.util.Properties

    Finding the key according to string length in java.util.Properties.
    I know only String length only.

    i need to retrieve the values from the java.util.properties.
    we know that we need to give the key value in order to retrieve the datas.
    but my problem is i will give the length of the key instead of giving the key value but i need to retrieve the datas according to the length of the key.

  • Custom fields and line length in Address Book

    Hi everyone. Does anyone know how to alter the permitted line length of a label in Address Book? If I create a custom label the label will be truncated if it is too long. This does not seem necessary as there can be loads of blank space to the right of the card window. In other words the label will not resize dynamically to accommodate a long custom label. I have a feeling that you may be able to edit a .plist file in the Package to adjust the default number of characters the label can have, but I'm a bit nervous about poking about when I'm not too knowledgeable. Any ideas?

    In other words the label will not resize dynamically to accommodate a long custom label.
    Of course not. You've chosen a specific label style/size, so if it were to resize dynamically, that would cause text to print where there is no label stock.
    You cannot edit any file to change the number of characters per label; at best, you could creae your own label size and define the margins, but that's it.
    Mulder

  • Line wrapping in Java??

    Hi,
    Can anyone tell me if there is a class to handle line wrapping in Java?
    I'm working on a Java Mail application that deals with fairly lengthy email message bodies. The problem is in the actual email, the message body appears in a lengthy horizontal single line which is rather inconvenient to read.
    I'd like to break the message body into convenient 80 character lines that takes word boundries into account so that there are no broken words at the end of a line.
    Thanks,
    Veena

    Well the easiest way would be to put line breaks when you want them.
    "\n" is the line break character.
    So String("aaaaa\naaaaa");
    Should appear as
    aaaaa
    aaaaa

  • URGENT:  vertical lines length in the Mainwindow in smartforms

    hI,
            In main window 4 vertical lines are there like.. below
    item | material no.er | mat.desc |  quantity |  total price
           |                      |                |              |
    Now the problem is:  these vertical lines entered into the next below window.. Now I want to reduce the length of these vertical lines.
      Please explain where can I reduce  to these vertical lines length.
    Thanks and Regards,
    Surya

    Hi,
    in the beginning of the report program:
    report  <program_name> line-size <give the length say eg:150>.
    <b>reward points if useful.</b>
    regards,
    Vinod Samuel.

  • How can I establish a line length (72 chars) and get TB to wordwrap at that length?

    I would like to establish a line length for email that I compose or receive. How can I do that? How can I get TB to wordwrap at that length and not some shorter length?

    I did that - and found several items for wrap.
    All except the one noted - mailnews.wraplength - have a status of default, type boolean and value false.
    mail.compose.wrap_to_window_width
    mail.wrap_long_lines
    plain_text.wrap_long_lines
    view_source.wrap_long_lines
    mailnews.wraplength
    status: default
    type: integer
    value: 72
    I promised to be careful, so a last check here - can I change that value to 80 or 50 or something other than 72 without messing up Thunderbird?
    Thanks,
    Terry_S

  • Set line length

    I belong to a travel discussion group and they request that all e-mails are received in plain text and with a 60 character per line limit. How do I set the line length to a maximum of 60 characters?

    Dear Diana,
    This seems really antiquated. I can't think of any discussion groups I belong to that ask you to set the line length of my contributions.
    Whatever. Since no one has replied to you, I offer a completely clunky way of doing this. I can't see where Mail has this capability/preference setting.
    Anyway, go to barebones software's web site and download the free application TextWrangler. It's just a text editing program. BBedit will do the job too but I'm assuming you don't have that.
    In TextWrangler, set up a document with a 60 character width (open a new document, go to Edit-->Text Options... and check "Soft Wrap Text" and under the "to character width" option put "60" in the box).
    You can save this document with a silly name so you don't have to create it every time you want to format a mail.
    Next, either compose a mail in the document or paste your text into it.
    It will be 60 characters wide at this point, but the breaks will be "soft"; you need to go to Text-->Add Line Breaks. Now you can copy your text and paste it into an email.
    This sounds like a lot of steps but it is easy. You could probably Applescript it.
    Anyway, there is probably a much better answer to your question, but I didn't want to leave you hanging longer. Once your problem leaves the front page it gets less and less attention.
    Also, note that in Mail preferences you can find the option to compose and send mails as plain text rather than rich text.
    G4 933 mhz Quicksilver   Mac OS X (10.4.8)   Wacom Intuos 2 tablet; Epson 2400 Photo; HP Deskjet 6840; LaCie 80gb D2 FWDV

  • Line length limit

    Hi,
    I'm having a problem with a large group (about 2500 members). I first thougt this is a Directory Server Problem, but the Server Log is identical for small and large groups and does not show any problems. Additionally even if i put the group (with all members) into /etc/group, I still cant see the group!
    When using vi to edit /etc/group it sais: line too long.
    I figured out this to be a problem with the maximum line length defined in /usr/include/limits.h (LINE_MAX). The value set here is 2048, but my line is about 13K.
    Could my explanation be correct? If so, how can I change the line limit to a bigger value?
    thanks,
    David

    Hi Martin,
    I might not have explaned enough the issue. I dont want to edit the file with vi, this was just what I experienced on the side. My real problem is, that Solaris doesnt know this group, even though it is in /etc/group!
    id just shows the gid number, but not the group name:
    bash-2.05$ id
    uid=21345(ab123) gid=10000
    bash-2.05$ groups
    10000
    getent doesnt know the group too:
    bash-2.05$ getent group gp_everyone
    [No output]
    And this is constrained by the Solaris system as I think. Because of the limited line length. Do you know how to reconfigure Solaris 9 and 10 for a longer line length?
    big thanks
    --David                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Maximum line length in JTextAreas/Documents ?

    Hi there,
    apparently JTextAreas may not hold text with lines more than 32776 characters
    (with line length I mean distance between line breaks :-). Is this a documented limitation or did I trap into a bug?
    (Happened with 1.3.x and 1.4.x, Linux and Windows).
    Kind Regards,
    --Holger Klwitter                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    See: [http://kenhamady.com/cru/archives/1240|http://kenhamady.com/cru/archives/1240]

  • Line graphs in java

    I am looking for a free class that will allow me to graph a line graph in java. I was going to write my own but figured there must already be some out there... There doesn't happen to be a JGraph object that sun is working is there?

    Look at JFreeChart, it contains tools to draw many different charts and graphs.
    DB

  • What is the maximal line length of type any internal table

    Dear all,
    who can tell me what is the maximal line length of type any internal table.
    Thanks!

    There is no limit to the record length of an internal table.
    There is overall memory limit for every program (as setup by your basis). So, depending on the width of the ITAB, the number of records in ITAB is limited by the assigned memory.

  • Question: why default line length as 72 ?

    hello everyone,
    i was just adviced to stick to default line length in abap editor as 72 [which ABAP recommends too] or else in complex and lengthy programs it will generate core dump !!
    is it true ?
    and why it is adviced to stick to 72 length  and not greater than that and why it will give core dump ??
    thanks in advance

    @Rohan,
    ABAP is not new language. It old language and intiallly it support the 72 character per row. Which is the non graphical display support maximum 80 column per row and each row has begin some previlage space around the 8 characters. 
    But after each release and graphical display come to exist, It support more then 72 character per line, it is not mandatory but in case of dynamic program(program generate runtime). it has internal check  character per rows should not be 72 character/line. For dynamic program you should have to restict the line size which should not go beyond the 72 character.
    Kind Regards
    Ravishankar Lanjewar
    Moderator Message: Please check the date of the original post before replying. Thread locked.
    Message was edited by: Suhas Saha

  • Line continuation in java

    What is the syntax for line coninuation in java.Suppose i am defining a string and it goes to the next line.Without using '+' for appending how do i define this single string.

    use concat(String yourString). This will append yourString to the end of your first String.

  • Max line and Max line length restriction in FTP

    Hi all,
    We are using a FTP adapter in our BPEL service to read the input files from a FTP server location.
    Our service fails when the input file has more than 99 lines or if the length of the line exceeds 9 characters.
    i.e:
    Max allowed characters in a line (Max line length) is 9
    Max allowed lines in the file is 99
    If the above limit is exceeded we get the error saying that the FTP authentication failed or permission denied error.
    Do we need to set the Max line length and Max line parameters anywhere in weblogic console or in JCA properties.
    Kindly help us resolve the issue. Thanks in advance.
    Regards,
    Balaji R

    We do not have any schema for the file data since we are reading the file content as attachment.

Maybe you are looking for

  • SQLLDR - how to set a default value for an empty string

    I'm using SQLLDR to load data from a flat file on Oracle 10g 10.2.0.4 EE, Linux RHEL 4 update 6. Seems like my question is simple, but darned if I can't find the solution. My source file (comma delimited extracted form a different RDBMS) has some (no

  • How to get these lines/effect

    Hi guys. Please, could you help me a little? I am on this simple project where I have to make something similar to this: http://www.video.terramedia.lt/downloads/lines.jpg the thing is - I need to animate the center of these lines (anchor point), and

  • Issue with past purchase

    Quite a while ago (a few years, most likely), I got a few i-tunes vouchers for my birthday, and bought a few films, and also bought a few more films with my debit card. These films included Johnny English: Reborn. I watched it several times, the most

  • How do I create a Bootalbe HD

    Hi, I don't have CD RW, but I got external HD, how can I create bootable external HD from all Oracle Linux ISO? I mean which software should I use ( on Windows XP) to create bootable hd and install linux? Thanks,

  • F4 Help in Variable Screen during Query Execution

    Hi All, We are executing queries through WAD. The F4 help in the variable screen during query execution is taking a lot of time. SAP note 661251 suggests changing the F4 mode to M. We need to change the booked value parameter. I looked into the stand