Question

Computing size of a text area.

Asked by: jpmcgrath

I would like to create a dialog that displays text that will be loaded from an external source.  I do not know exactly what the text will be, but under normal circumstances it will be able to fit comfortably in the dialog.

Assuming the text is not too long, I would like it to appear wrapped in the dialog without scroll bars.  But I do not want extra white space if the text is short.

In order to accomplish this, I think I need a method that will determine the height of a JTextArea or JTextPane when wrapped to a specified width.  But I have not found any such method.

Is anyone aware of such a method, or of any other way to accomplish this?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2000-08-27 at 04:50:41ID11118365
Tags

determine

,

jtextarea

,

jtextpane

,

size

Topic

Java Programming Language

Participating Experts
3
Points
200
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. JTextPane with HTML printing!
    How can I print the content of a JTextPane? Exist somewhere an example? Thank you sey.
  2. JTextArea Fonts
    How can i put different font style & size of the text in a single Jtextarea ?
  3. JTextArea
    Hi i am using JTextArea and i am appending certain values to it. For example i want to add a string to it which has certain background and foreground , i don't want to change the whole JtextArea just that string to be appended to it with these colors. Can this be done ?
  4. resize JTextArea
    I use BorderLayout to put 2 scrollPane in a JFrame, one to the center, and the other to the SOUTH. In the 2nd scrollPane, I put a JTextArea(5,25). Now if I resize the frame, everything but the textArea changes size. How do I make the scrollPane with the JTextArea resize ac...
  5. JTextArea Size
    Hello all, How can I control the size of a JTextArea. When I'm changing the size of the font in the text area the textarea's size changes as well. I've tried using the methods setMaximumSize and setPreferredSize without success. Thanks, g

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Sasha_MapaPosted on 2000-08-27 at 05:36:14ID: 4087028

Use the java.awt.FontMetrics class to determine the size of the string at a given font...

Sasha.

 

by: jpmcgrathPosted on 2000-08-27 at 05:47:11ID: 4087128

That does not tell you the height of the text area.  That tells you the width.

 

by: Sasha_MapaPosted on 2000-08-27 at 06:06:46ID: 4087235

From the documentation on FontMetrics.getHeight():

public int getHeight()

Determines the standard height of a line of text in the font described by this font metric. This standard height is the distance between the baseline of adjacent lines of text. It is computed as the sum
getLeading() + getAscent() + getDescent()

There is no guarantee that lines of text spaced at this distance must be disjoint; such lines may overlap if some characters overshoot either the standard ascent or the standard descent.

Returns: the standard height of the font.

Sasha.

 

by: fontainePosted on 2000-08-27 at 07:50:30ID: 4087931

You can inspire from the following example.

Cheers,

Bertrand
------------------------------------------------------------------------------------------------

import java.awt.*;
import java.util.*;

import javax.swing.*;

public class MyDialog extends JDialog {

    private JTextArea area = null;

    public MyDialog(Frame frame) {
        super(frame, "Test", false);
       
        // create the text area, and make it wrap lines
        area = new JTextArea();
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
       
        // add the text area to the dialog
        getContentPane().add(area);
    }
   
    public void setText(String text) {
        // display the text in the JTextArea
        area.setText(text);
       
        // set the size of the area to the appropriate
        // width and an arbitrary height
        area.setSize(new Dimension(getSize().width, Integer.MAX_VALUE));

        // now, pack the dialog
        pack();    
        return;
    }
         
   
    public static void main(String args[]) {
        MyDialog myDialog = new MyDialog(new JFrame());
        myDialog.setSize(new Dimension(50,Integer.MAX_VALUE));
        myDialog.setText("Replace this text with the appropriate one!");        
        myDialog.setVisible(true);        
        return;
    }
}

 

by: jpmcgrathPosted on 2000-08-27 at 09:53:43ID: 4088694

I do not think you really read the question, Sasha.  The various FontMetrics methods such as getHeight() return the metrics of a single line of text, not the height of a JTextArea or JTextPane.  The text area will likely contain multiple lines of text, and without running through the line wrapping algorithms that the text component performs, you do not know how many lines.  Then there are the borders and margins that can contribute to the height of the component.

Fontaine's response looks promising.  I will check it out and post the results.

 

by: Sasha_MapaPosted on 2000-08-27 at 10:20:04ID: 4088839

Umm, yes, you're right, sorry, I got confused (I always get confused between textfields and textareas...). Anyway, I think what fontaine suggested will work (I would have suggested that myself :-) )

Sasha.

 

by: Sasha_MapaPosted on 2000-08-27 at 10:31:24ID: 4088888

Btw, I think if you put your string into whatever component you are using and then call preferredSize() on that component, what you will get is exactly what you want... (but I think that this is exactly what pack() takes into account...)

Sasha.

 

by: steletPosted on 2000-08-27 at 14:38:17ID: 4089948

In general you can't control the size of your components by yourself. This is done by means of a LayoutManager. Even query the size of your JTextArea will be difficult because this size is set by the LayoutManager and may be valid only about the time your dialog is made visible.
So what I suggest is to set our text in your JTextArea, wrap this JTextArea in a JScrollPane and put it on the JDialog using a proper LayoutManager.

If the size of the JTextPane is large enough, no scroll bars will be drawed. The preferred size of your JTextArea will depend on the text and fonts choosen. If you choose a LayoutManager dealing with preferred sizes (as FlowLayout) the size of your JTextArea will not larger than needed.

In general the size of your dialog will depend on the LayoutManager, but it will not be larger than needed. You can setup a maximum size. If now there is too much text, scrollbars will appear !

 

by: Sasha_MapaPosted on 2000-08-27 at 15:35:53ID: 4090217

Dear stelet,
May I friendly lead your attention to an important issue? Here in Experts-Exchange it is common practice to lock questions with an answer only if you are the first expert in the thread, or if all other comments are
evidently wrong. Otherwise it is usual to post a *comment* only. This way the questioner can later easily choose which expert helped most. Additionally, using comments only is more polite because:
               
- the question can easily be deleted if necessary
- it cannot happen that an answer is accidentally accepted
- you show that you acknowledge the work already done
- you give other experts a chance to post a better answer
                       
Please, be so kind and use the option "withdraw answer" to convert your answer to a normal comment.
                       
Thank you for listening...   (-:

Sasha.

 

by: jpmcgrathPosted on 2000-08-27 at 17:00:01ID: 4090680

First, read Sasha's comments.

Second, your comments about not being able to control the size of a component are not accurate.  You can always set the layout to null, and then size things as you would like.  Or better yet, just write a custom LayoutManager, since this will allow client code to modify this behavior if they so wish.

Third, your "solution" does not address the problem.  Rather it explains the basics of layout managers, which is pretty obvious.

Finally, your answer says that I can't do what I want to do, after others have posted suggestions on how to do it.  If you had addressed their solutions, and said why they will not work, that may have been reasonable, but you did not.

 

by: jpmcgrathPosted on 2000-08-27 at 17:11:35ID: 4090736

Well, fontaine's answer is on the right track, but something is not quite right.  

Here is the version of his code that I am working with.  It is pretty much the same, except:

1) I made the dialog modal so I can exit after the dialog is closed.  No zombie processes that way.

2) I changed the text for the text pane.

3) I added a setLocation() so the dialog does not open up under my task bar.

4) I added a show() method to dump out some information at different spots.

None of these changes should have had an effect on the sizing of the text area.  But what is interesting is that the debug code makes it work.

Here is the program:
===========================================================================
import java.awt.*;
import java.util.*;
import javax.swing.*;

public class MyDialog extends JDialog {

    public JTextArea area = null;

    public MyDialog(Frame frame) {
        super( frame, "Test", true );

        // create the text area, and make it wrap lines
        area = new JTextArea();
        area.setLineWrap(true);
        area.setWrapStyleWord(true);

        // add the text area to the dialog
        getContentPane().add(area);
    }

    public void setText(String text) {
        // display the text in the JTextArea
        area.setText(text);

        show( this, "After area.setText()" );

        // set the size of the area to the appropriate
        // width and an arbitrary height
        area.setSize(new Dimension(getSize().width, Integer.MAX_VALUE));
        show( this, "After area.setSize()" );

        // now, pack the dialog
        pack();      
        show( this, "After pack()" );

        return;
    }


    public static void main(String args[]) {
        MyDialog myDialog = new MyDialog(new JFrame());
        show( myDialog, "After constructor" );
   
        myDialog.setSize( new Dimension( 400, Integer.MAX_VALUE ) );
        show( myDialog, "After setSize()" );
       
        myDialog.setText(
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.\n\n" +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  "
        );

        myDialog.setLocation( 200, 200 );
        myDialog.setVisible(true);        
        System.exit( 0 );
    }

    static void show( MyDialog myDialog, String desc ) {
/**/
        System.out.println( "\n" + desc + ":" );
        System.out.println( "    size = " + myDialog.getSize() );
        System.out.println( "    preferredSize = " + myDialog.getPreferredSize() );
        System.out.println( "    rows = " + myDialog.area.getRows() );
        System.out.println( "    columns = " + myDialog.area.getColumns() );
/**/
    }
}
===========================================================================
If you comment out the body of the show() method (change "/**/" to "/**  /"), the program does not work.

Curiouser and curiouser.

I will let you know what I find out.

 

by: jpmcgrathPosted on 2000-08-27 at 18:01:04ID: 4090968

Here is a restructured program:

==================================================
import javax.swing.*;

public class TextViewer
    extends JTextArea
{
    public TextViewer() {
        setLineWrap( true );
        setWrapStyleWord( true );
        setColumns( 35 );
        setSize( getPreferredSize().width, Integer.MAX_VALUE );

        // Without this, it does not work.
        getPreferredSize();
    }

    public static void main(String args[]) {
        JDialog dialog = new JDialog( new JFrame(), "Text Viewer", true );
        TextViewer textViewer = new TextViewer();
        textViewer.setText(
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.\n\n" +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  " +
            "This is a test of sizing a text area to fit.  "
        );
        dialog.getContentPane().add( textViewer );
        dialog.pack();
        dialog.setLocation( 200, 200 );
        dialog.setVisible( true );
        System.exit( 0 );
    }
}
==================================================

Any idea what is going on?  In particular, is this behavior a fluke, or is this supposed to work this way?

 

by: jpmcgrathPosted on 2000-08-28 at 10:13:02ID: 4100571

Thanks.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...