JTextArea: size dynamic with text

I''m trying to size a JTextArea according to the text that is occupy it.
The width I have from another JPanel, but the height I can't get right.
I need to get the number of lines that the text will occupy and then set the size accordingly.
As it is, I've hard-coded the number of lines, even so, that doesn't work. e.g. if i set # of lines = 5, it still shows only 2, though the dlg box can be resized by hand to show them all.
Any suggestions?
public class TextPanel extends JPanel {
    private final Insets insets =  new Insets(10,20,10,20); // top, left, bottom, right
    private JTextArea textArea;
    private FontMetrics metrics;
    private double widthButtonPanel;
     * @param message
     * @param dimension dimensions of button panel
    public TextPanel(String message, Dimension dimension) {
      // get bg color of panel so we can set bg of text area to same color
         Color color = getBackground();
       TextArea = new JTextArea (message);
     textArea.setLineWrap(true);
     textArea.setWrapStyleWord(true);
     textArea.setBackground(color);
       TextArea.setMargin(insets);
     // this will be width of the text area
     // height can't be set until painting it because we need to get the text size
       widthButtonPanel = dimension.getWidth();
     add(textArea);
     * override default insets
    public Insets getInsets()
         return insets;
    @Override
     * override in order to set height of text area
     * @param g Graphics
    public void paintComponent(Graphics g)
         // automatically called when repaint
         super.paintComponent(g);
     Font font = this.getFont();
         Graphics graphics = this.getGraphics();
         // get metrics from the graphics
         metrics = graphics.getFontMetrics(font);
     // get the height of a line of text in this font and render context
       // line height must be that of text only, not space above and below
         final int HEIGHT_SPACE = 7; // empirically derived
     int heightTextAreaLine = metrics.getHeight() + HEIGHT_SPACE;
     // set height
     final int numberOfLines = 5;
        // truncate double, doesn't matter because it is *.0 anyway
     Dimension newDimension = new Dimension((int)widthButtonPanel, heightTextAreaLine * numberOfLines);
        TextArea.setPreferredSize(newDimension);
        //textArea.setMaximumSize(newDimension);
        TextArea.setMinimumSize(newDimension);
}Edited by: allelopath on Jan 19, 2009 2:33 PM

You can get the size following the steps.
1. create dummy textarea and set your text to it.
2. dummyarea.setSize(new Dimension(desiredWidth, Short.MAX_VALUE));
3. Dimension pref=dummyarea.getPreferredSize();
pref.height is the height textarea need to be.
Regards,
Stas

Similar Messages

  • Dynamic Standard text - Appending text with variable

    Dear All,
    We have a dynamic standard text. The text is being created based on sales order (I don't know how this has been created). Now I want to add text inside the standard text. That text will also contain variable.
    Example: "This is a valid sales order 100010000". This is a standard text where the sales order value is fed dynamically, I don't know how?
    Now the objective is to add another field "abcd" in the standard text with some other fixed texts. Eg. "I want to add my name sy-uname". So the entire text should be as:-
    "This is a valid sales order 100010000. I want to add my name sy-uname."
    1.  I am not sure how to identify the original standard text. I would like to add second line there.
    2.  I would like to pass variable value dynamically in the standard text.
    Please can you help me out in solving the issues.
    Best wishes,
    Atanu

    Hi
    Could you please be clear with your question so that some one can provide you with best solution quickly.
    I am assuming that when your sales order is being created at the same time ,your dynamic standard text is generated .So now you want to amend this standard text just after the sales order is saved.If so then
    Just go to the sales order text tab in change mode and click on the text eidtor window ,it will take to you sapscript editor ,Then from menu Goto-Header .From here you get the details of
    Text Name      
    Language       
    Text ID        
    Text Object  
    Now Find the userexit after save and their use a read_text function module and read the standard text which is alreday created and take down in it_lines table and modify the text by appending your sy-uname line as second line or you can concetante on the same line. Now then use the save_text function module and save the standard text.
    You can use the exit MV45AFZZ In that routine FORM userexit_save_document..
    Hope this help you to resolve the issue.
    Cheers
    Joginder

  • Dynamic Linking with text

    Can text created in Pr Titler be sent from a Pr Timeline
    to an Ae comp via Dynamic Link in the upcoming version?
    http://forums.adobe.com/message/5274695#5274695

    I'll file a feature request here:
    http://www.adobe.com/go/wish
    Feature Request:
    Brief title for your desired feature:
    Dynamic Linking with text
    How would you like the feature to work?
    The ability for text created in Premiere Titler
    to be sent from a Premiere Timeline to an
    After Effects Composition via Dynamic Link.
    Why is this feature important to you?
    I do all of my finished titling in Ae, and would like to
    be able to transfer rough-cut text from Pr for compositing
    Filed.

  • Problems with displaying dynamic Arabic text

    We have a problem with a navigation system we are building
    which has to be able to display dynamic Arabic text. We are pulling
    in the Arabic text using XML. The problem we are having is that the
    character are not displaying joined up where they should be (for
    instance in the middle of words). Arabic characters have different
    shaping according to the position they take up within a word. What
    we are producing is apparently unreadable. Has anyone come accross
    this problem before? Is it solveable?

    Hi:
    Is there any possible chance that Adobe would do something to asist us Fl8 users with international character support.
    Everyone has some work-around, except Abode, and they are all usually related to XML.
    My setup is PHP (CMS supporting many languages) -> MySQL -> PHP -> Flash8 (Dynamic Text Fields) and the olpart that does not work is when I inject an extended character into the string - Flash stops displaying anything from that character on.
    If Adobe has or did have some component / solution or anything other than the usual System.useCodePage = true (which never seems to actually work), please let me know.
    Best Regards,

  • Do you see problems with text size when importing from Photoshop?

    Hi all -
    We're working on improving some things in the Photoshop-to-Reflow workflow, and right
    now specifically investigating trouble with imported text.
    Aside from the desire to have support for local fonts, are there any problems you run into
    when importing text from Photoshop into Reflow? We've heard some issues with text size and position,
    but want to make sure we understand all of the cases.
    If you have problems in this area, please share them in this thread, and I'd also love to get some
    sample PSDs that demonstrate the problems. (You can send them directly to me; vmitnick at adobe dot com .)
    thanks,
    Vic

    I'm using CS4.. and I'm using the standard "Save As" .pdf features....
    and I'm reading it with adobe acrobat pro 9.1...
    i think it has something to do with compression. but i can't figure out how to solve it. converting the text to symbols maybe?

  • How to make Dynamically Shortened Text With "Show More"

    Hi there! i want to know how to make dynamically shortened text with show more or read more in my website using HTML 5 pages  or ASP.NET ?
    example like these paragraphs 
    Lorem Ipsum är en utfyllnadstext från tryck- och förlagsindustrin. Lorem ipsum har varit standard ända sedan 1500-talet, när en okänd boksättare tog att antal bokstäver och blandade dem för att göra ett provexemplar av en bok. Lorem ipsum har inte bara överlevt fem århundraden, utan även övergången till elektronisk typografi utan större förändringar. Det blev allmänt känt på 1960-talet i samband med lanseringen av Letraset-ark med avsnitt av Lorem Ipsum, och senare med mjukvaror som Aldus PageMaker.
    Det är ett välkänt faktum att läsare distraheras av läsbar text på en sida när man skall studera layouten. Poängen med Lorem Ipsum är att det ger ett normalt ordflöde, till skillnad från "Text här, Text här", och ger intryck av att vara läsbar text. Många publiseringprogram och webbutvecklare använder Lorem Ipsum som test-text, och en sökning efter "Lorem Ipsum" avslöjar många webbsidor under uteckling. Olika versioner har dykt upp under åren, ibland av olyckshändelse, ibland med flit (mer eller mindre humoristiska).
    I motsättning till vad många tror, är inte Lorem Ipsum slumvisa ord. Det har sina rötter i ett stycke klassiskt litteratur på latin från 45 år före år 0, och är alltså över 2000 år gammalt. Richard McClintock, en professor i latin på Hampden-Sydney College i Virginia, översatte ett av de mer ovanliga orden, consectetur, från ett stycke Lorem Ipsum och fann dess ursprung genom att studera användningen av dessa ord i klassisk litteratur. Lorem Ipsum kommer från styckena 1.10.32 och 1.10.33 av "de Finibus Bonorum et Malorum" (Ytterligheterna av ont och gott) av Cicero, skriven 45 före år 0. Boken är en avhandling i teorier om etik, och var väldigt populär under renäsanssen. Den inledande meningen i Lorem Ipsum, "Lorem Ipsum dolor sit amet...", kommer från stycke 1.10.32.
    Den ursprungliga Lorem Ipsum-texten från 1500-talet är återgiven nedan för de intresserade. Styckena 1.10.32 och 1.10.33 från "de Finibus Bonorum et Malorum" av Cicero hittar du också i deras originala form, åtföljda av de engelska översättningarna av H. Rackham från 1914.

    Moved to the main Dreamweaver support forum.
    There are several ways you could approach this. Here's one you might try:
    Give the first paragraph an ID, such as "first", and wrap the paragraphs you want to hide in a <div> with another ID, such as "more". Then add the following block of JavaScript just before the closing </body> tag of the page:
    <script>
    var first = document.getElementById('first'),
         more = document.getElementById('more'),
         trigger = document.createElement('span');
    trigger.id = 'trigger';
    trigger.innerHTML = 'Show less';
    first.appendChild(trigger);
    function toggleDiv() {
      var state = more.className,
           text = trigger.innerHTML;
      more.className = (state == 'open') ? 'closed' : 'open';
      trigger.innerHTML = (text == 'Show more') ? 'Show less' : 'Show more';
    toggleDiv();
    if (trigger.addEventListener) {
        trigger.addEventListener('click', toggleDiv, false);
    } else if (trigger.attachEvent) {
      trigger.attachEvent('onclick', toggleDiv);
    } else {
      trigger.onclick = toggleDiv;
    </script>
    This gets references to the "first" paragraph and the "more" <div>. It also creates a <span> with the ID "trigger" that's appended to the "first" paragraph. The rest of the script defines a function called toggleDiv(), which toggles the "more" <div> open and closed, and changes the text in the "trigger" <span>.
    You also need to create the following style rules for the various elements:
    <style>
    #trigger {
        text-decoration: underline;
        color: blue;
        cursor: pointer;
    #more {
        transition: ease-out .7s;
        overflow: hidden;
    #more p:first-child {
        margin-top: 0;
    #more.closed {
        height: 0;
        -webkit-transform: translateY(-600px);
        transform: translateY(-600px);
    #more.open {
        -webkit-transform: translateY(0);
        transform: translateY(0);
        max-height: 600px;
    #more + p {
        margin-top: 0;
    </style>
    This solution hides the text and creates the "trigger" <span> only if JavaScript is enabled in the browser. It should work in all browsers, including Internet Explorer 8 and earlier.

  • Dynamically change the size of a text field.

    Is it possible to change the size of a text field depending on the amount of text in the field?
    Thanks,
    Chad

    You can find the answer from this post.
    jimmypham, ""Shrink to Fit" - Text Field capability?" #1, 18 Jul 2005 10:36 pm

  • Dynamically passing text and url-based images as an input parameter to cf8 report builder

    I'm unsuccessfully trying to dynamically pass text and url-based images to a group footer or the detail section via an input parameter or even hardcoded. The field has the attribute 'XHTML Text Formating' set to True. The following are failed samples of a simplified value:
    "<img height=’300’ alt=’Document’ width=’300’ src=’http://www.google.com/intl/en_ALL/images/logo.gif’ />"
    or
    "<img src=’http://www.google.com/intl/en_ALL/images/logo.gif’ />"
    This just results in the above text being output. The end result would have various text and images from a database as input by a user, thus the reason I cannot just use the hyperlink information attribute as I could if it were a single known image. I tried rtf and pdf report types. Ideas?

    HTH,
    Thanks. I'll keep that in mind, although I don't know how many images my user might need or what sizes so that might be tricky.
    Since my target output is rtf so that MS Word can be used to edit the result, I added a pagebreak to a MS Word doc and used the resulting html source to replace the rich text editor source code for the page break, but that did not help either. The page break was so a user could add an image later. Something is wrong with the Report Builder related to intepreting XHTML, especially anything that has an attribute, including URL-based image links. I hope they try to provide another update before CF9. I doubt my client will be going to CF9 for some time, since they are just completing the migration to CF8.
    BrianO

  • Upgrade from CS4 to CS5: Dynamically created text isn´t shown anymore.

    Hello,
    since I have updated my Flash CS4 to CS5, textfields that have been dynamically created inside external classes aren´t filled with text anymore. At least they exist; the cursor appears, when I roll over the place, where it has been placed.
    This is how I place it:
    1. The font is embeded as Font-Symbol inside the library. Name: "BertholdWalbaumBook", Linkage: "BertholdWalbaumBook";
    2. Code:
              moreInfoButtonText = new TextField();
              moreInfoButtonText.text = "More Info";
                   //TEXTFORMAT
                var pre_Disco_RecordStandard_TextFormat:TextFormat = new TextFormat();
                pre_Disco_RecordStandard_TextFormat.align = TextFormatAlign.LEFT;
                pre_Disco_RecordStandard_TextFormat.color = "FFFFFF";
                pre_Disco_RecordStandard_TextFormat.font = "BertholdWalbaumBook";
                pre_Disco_RecordStandard_TextFormat.leading = 3;
                pre_Disco_RecordStandard_TextFormat.size = 14.62;
                pre_Disco_RecordStandard_TextFormat.letterSpacing = 0;
                //COORDINATES
                moreInfoButtonText.x = moreInfoButtonBG.x+5;
                moreInfoButtonText.y = moreInfoButtonBG.y-30;
              //TEXTFIELD
                moreInfoButtonText.embedFonts = true;
                moreInfoButtonText.setTextFormat(pre_Disco_RecordStandard_TextFormat);
                moreInfoButtonText.antiAliasType = AntiAliasType.ADVANCED;
                moreInfoButtonText.sharpness = -400;
                moreInfoButtonText.thickness = -200;
                moreInfoButtonText.autoSize = TextFieldAutoSize.RIGHT;
                moreInfoButtonText.wordWrap = true;
                moreInfoButtonText.multiline = false;
              //ADD CHILD
                addChild(moreInfoButtonText);
    When I set       moreInfoButtonText.embedFonts = false;    the text is shown with system font, so the problem must cohere with embedding.

    In case you haven't seen these
    http://www.dotstrosity.net/2010/05/10/flash-cs5-font-embedding-its-totally-different/
    http://kb2.adobe.com/cps/831/cpsid_83162.html

  • Change item size dynamically

    Hii All
    I need to change an item size dynamically. For eg. If i have an item size (width) 20 and i entered text of 100 alphabates then the size of item is increase dynamically along with text.
    I use set_item_property but it shows an error that *" Cannot resize item. Position of item places it off of canvas. "*
    Please Assist.
    Pradhyumn

    write both the actions at the same time
    if the canvas size is less then the field size plus the increament then increase the size of the canvas tooo...

  • Problem with text resizing and moving

    After much pain with this issue, I'm going to ask for help.
    The whole issue(s) resolves around text upsizing, changing and moving in Muse.
    No amount of grouping, layering and locking has stopped this issue for me.
    I don't have divs that are a pixel off and whatnot. This happens even when I have a blank site and I test it (as seen in the example pic below).
    The majority of the time, this is an issue when viewing Muse created sites on Android, although text does move when viewed on iOS.
    Example 1:
    I have a square div. I put text in the div that I want to stay contained in the div. Basic right?
    View site on browsers and iOS devices it generally plays by the rules (although not always, there are some movement going on). When viewing this example text and div on an android device, the text resizes larger. This results in the text overlapping the div and moving EVERYTHING below it down. This makes it impossible to tightly design anything for a website.
    I know Android has options within it for users to set text viewing size, but this worthless from a web designer standpoint. That is something I can't control.
    Example 2:
    I have 1 text field and set the typeface to 15. There is nothing else on the page, just a background image (under "Fill"). Viewed on browsers and iOS looks fine. When viewed on Android this text balloons to some enormous size (25+) that makes the website utterly useless. This random resizing makes it impossible to design to. 
    Example 2.5:
    I take that same text from example 2, copy it into 2 of the same size text fields. They are placed next to each other, taking up the same width as Example 2. It now looks like 2 columns of text. Set the typeface to 15 again. I view it on Android and get the resizing issues from example 1 not example 2. It's noting to the extent of example 2 but like example 1, it still changes enough to ruins any design I'm trying to accomplish.
    Is there any place in Muse to lock the text? I don't want to make the text into an image (obviously).
    I been dealing with this in Muse for 6 months and haven't been able to find anything online or in forums about. I understand with the bevy of platforms out there nothing will look the same across the board, but right now I don't see how I can continue working with this issue.
    Am I the only one dealing with this?
    Thank you for any assistance.

    Welcome to the annoying realities of working with text on websites... Nothing you describe is unique to Muse.
    Every browser has it's own text engine and thus each line breaks text differently. Even the exact same web page on the same computer with the same fonts will sometimes result in different line breaks in different browsers, or even in different versions of the same browser. It's just a side effect of the nature of determining a line break, where even the most miniscule difference in calculations can result in an entire word fitting, or not fitting.
    There are two "tools" that are especially important to understand and use effectively in order to create designs that work as effectively as possible with the variation in line breaks from one site viewer to the next.
    Text Frame Height Always Matters
    If a text frame is drawn to the exact height of the text wthin the frame, then any increase in the number of lines of text due to changes in line breaks will result in the text frame growing and other objects below the text frame being moved down.
    If a text frame is drawn larger than the height of the text then when line breaks change the text frame won't grow unless the changes in line breaks are severe enough to result in the flowed text being taller than the text frame was originally drawn.
    If you resize a text frame smaller than the text within the frame in Muse Design view, the frame will snap back to be large enough to accommodate the text, but a dotted horizontal line will appear within the text frame indicating the "minimum height" for the text frame. If line breaks change in the browser the text frame will grow or shrink in height down to the minimum height indicated by this dotted line.
    Careful sizing of text frames can go a long way to creating a design that will continue to work well even when line breaks, and thus text frame heights change.
    Grouping Has Consequences
    As part of the output process, Muse collections the objects you've drawn into a hierarchy of horizontal groupings, vertical groupings, or stacks. When line breaks change in different browsers and text frames change height, when the text frames are located in this output heirarchy determines what impact the change in height has on other objects (if any).
    For example, if you have a layout that looks like a 2x2 grid of text frames, by default Muse will interpret it to act as two colums. So if the first text frame gets taller it will push the text frame below it down, but won't impact the location of the two text frames in the second column.
    If that's not the behavior you want, the way to tell Muse to treat things differently would be to group the two items in the first "row". This would cause the top to to be treated as a horizontal group. If anything in the group grows taller than the group, the group resizes taller and pushes the objects below it down. Thus if the top to items are grouped, if either one of them grows taller than the group it would push both the text frames below downward.
    The 2x2 grid is just a simple example of the concept. In most cases you don't have to do anything special to get the behavior you want, but it is important to understand grouping has this ramification. Grouping an arbitrary set of objects on your page can result in undesired behavior when text frames resize in the browser.
    For the Andriod screenshot you've provided, I don't have an immediate explanation. For us to explain what's shown we need to know the exact browser, browser version, Android version and device the screenshot is for. It would also be immensely helpful to have the URL for the page, so we can attempt to reproduce what you're seeing and view the exact code involved.

  • How Do I Display Quotation Marks in Dynamic HTML Text

    I'm using a dynamic text file that has some Quotation Marks
    that need to be displayed with the content on certain words in the
    TXT file.
    How do i display Quotation Marks inside a Dynamic text field?
    Please Advise. As soon as possible.
    Thanks

    Try this page - it does the job for you:
    http://www.dommermuth-1.com/protosite/experiments/encode/index.html
    Otherwise search this forum for "Special and characters and
    dynamic and text"
    You'll see a couple of thread on the topic. You have to
    encode the special characters for them to display correctly.

  • Is there a way to increase the icon size (and the text below) without using zoom?  I am trying to help out someone who has moderate visual impairment that does not want to use zoom just to see the icons and their labels.

    Is there a way to increase the icon size (and the text below) without using zoom in iOS 7?  I am trying to help out someone who has moderate visual impairment that does not want to use zoom just to see the icons and their labels.

    Hello Apple.
    It seems you have gone to great lengths to improve accessibility in many areas of the iPad. Why was this obvious problem with icon text size missed?  (It's not with the Mac.). And for so long too.
    Do you employ people with actual accessibility problems to help you do UI design?
    I think too, that some buttons are too close for people who might have motor control problems.
    I love my iPad but I fear as I age, the iPad might not keep up with me.

  • PDF Form with Text in Particular Font

    I have created a Certificate of Completion in CS4. It is 8.5x11 and, among other things, has a TIFF certificate background and border overlaid with text. My customer wants a PDF in which they can type two pieces of info: the name of the awardee and the date. These go in different places and in different fonts and sizes. How do I create such a PDF so that only this info can be entered, and entered in the correct size, font and area?
    Should I post this in the PDF forums?

    Basically, you need to create a pdf form.
    Add a text field to your form.
    There you can choose which font your want the text to appear in.
    The trick is, when you export from InDesign, in the "Advanced Tab" — set "Subset fonts when percentage…" to 0%, so the whole font embeds.'
    I believe there's an option in Acrobat to embed the font as well, but I'm not recalling what it it.
    But that will ensure the font appears correctly.
    d

  • I'm having issues with text layers in photoshop. Text layers show it's there but not visible on the canvas.

    I'm having issues with text layers in photoshop. They aren't visible. I've checked font size, alignment, layer order and color. And the layer list shows that it's there. All seems well but I still can't see the text that I write. Need help trouble shooting. (I asked this question about a month ago but I got sidetracked and never circled back.) Thanks.

    Please refer to your original topic (Text Layer not Visible.) instead of posting a new topic.

Maybe you are looking for