Setting JTextArea text within a JScrollPane

Hey all. I'm attempting to use the setText() method of JTextArea to set the text of various areas located in various scroll panes. The general procedure I'm following is to initialize a new JTextArea and JScrollPane within an initializeGui function, set the properties of the JTextArea, then add it to the scroll pane using .getViewport().add(). After that, a separate function goes through all my form fields loading them with whatever data type is appropriate, in the case of the text areas I'm trying to use setText() to set a string. However, after using setText() the text area is displaying nothing. Here's some code for example (workerPane is using a layout manager exclusive to the environment I'm working in, but I don't believe it's the problem).
workerLabel = new JLabel("Customer Address:");
          JScrollPane sp = new JScrollPane();          
          JTextArea ta = new JTextArea();          
          //set ta's properties to whatever is needed
          ta.addKeyListener(new java.awt.event.KeyAdapter(){
               public void keyTyped(KeyEvent e){
                    JTextArea text = (JTextArea)e.getSource();                    
                    String txt = text.getText();                    
                    int nameLength = 240;
                    if ( txt.length() >= nameLength ){
                         text.setText ( txt.substring( 0, nameLength-1 ) );                         
                         Toolkit.getDefaultToolkit().beep();                    
          sp.getViewport().add(ta);          
          workerPane.add("3.1.right.top",workerLabel);
          workerPane.add("3.2.left.center",custAddScrollPane);After each area has been initialized, another function is called to load the data into it. Here are some methods I've tried that haven't worked.
//basic, but leaves an empty field.
ta.setText(formProperties[2].getStringValue());
//this results in two NullPointerException warning windows popping
ta=(JTextArea)sp.getViewport().getView();
if(formProperties[2].getStringValue() != null)         ta.setText(formProperties[2].getStringValue());
sp.getViewport().removeAll();
sp.getViewport().add(ta);Can anyone point me in the right direction as to how to set my textarea's text?

I usually use the approach given above. The other option is:
scrollPane.setViewportView( textArea );

Similar Messages

  • JTextArea within a JScrollPane

    Hi!
    I've searched through the Project Swing archive and found lots of questions regarding how you ensure that when text is entered into a JTextArea control (via the append() method) the JScrollPane automatically scrolls to the position where the text was appended.
    Unfortunately I haven't yet found a satisfactory solution to this issue.
    I have a JTextArea control within a JScrollPane control. I start a seperate thread in order to perform some processing. This operation being run within this thread needs to provide progress information to the user and I present this progress information via the JTextArera control. Although the information is displayed within the JTextArea the JScrollPane unfortunately doesn't scroll down so that the last message entered into the JTextArea is visible. The user needs to scroll down manually in order to see the messages.
    I have read that if you invoke JTextArea.setText() or JTextArea.append() from within a thread otherthan the event dispatching thread then the JScrollPane will have no knowledge that text as been added. The article suggested using SwingUtilities.invokeLater(Runnable run) to ensure that the call to JTextArea.setText() or JTextArea.append() is performed within the event dispatching thread. I did create a Runnable class whose sole purpose was to call JTextArea.append() with message information but still the JScrollPane fails to automatically scroll as successive lines of text are being added to the JTextArea control.
    Can somebody please shed some light on my problem?

    Here's a simple program that works for me. Note, if you comment out the setCaretPosition() method it stops working.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestTextArea extends JFrame
         JTextArea textArea;
    public TestTextArea()
         JPanel panel = new JPanel();
         setContentPane( panel );
         panel.setPreferredSize( new Dimension( 200, 200 ) );
              textArea = new JTextArea( "one two", 3, 15 );
              JScrollPane scrollPane = new JScrollPane( textArea );
              panel.add( scrollPane );
              JTextArea textArea2= new JTextArea( "abcd", 3, 15 );
              textArea2.setPreferredSize( new Dimension( 50, 10 ) );
              panel.add( textArea2 );
         public void updateTextArea2()
              int line = 0;
              while ( true )
                   textArea.append( "\nline: " + ++line );
                   textArea.setCaretPosition( textArea.getText().length() );
                   try
                        Thread.sleep(1000);
                   catch (Exception e) {}
    public static void main(String[] args)
    TestTextArea frame = new TestTextArea();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
              frame.updateTextArea2();

  • How to apply style to partial text within a tag in xml file

    I have created a webpage using Dreamweaver CS4 Spry Regions. Everything is functioning as expecting, however now I need to apply a style to part of the text. Every occurance of the company name needs to be in italics - the problem is that the company name appears within different parts of the text within a set of tags.
    http://www.certifiedangusbeef.com/private1/sales/facts/index.php
    ie - <description> this is my company name which must appear in italics</description>
    In this example, only "company name" needs to be italicized. We have created an XSL file that applies the italics properly when the XML file is viewed in the browser. But it does not have any effect on the final web page - as though spry is blocking the XSL or we've missed a step in linking all the files together.
    Here's the XSL code:
    <?xml version="1.0" encoding="utf-8"?><!-- DWXMLSource="facts.xml" --><!DOCTYPE xsl:stylesheet  [
    <!ENTITY nbsp   "&#160;">
    <!ENTITY copy   "&#169;">
    <!ENTITY reg    "&#174;">
    <!ENTITY trade  "&#8482;">
    <!ENTITY mdash  "&#8212;">
    <!ENTITY ldquo  "&#8220;">
    <!ENTITY rdquo  "&#8221;">
    <!ENTITY pound  "&#163;">
    <!ENTITY yen    "&#165;">
    <!ENTITY euro   "&#8364;">
    ]>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="node()|@*">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="text()[ancestor::description]" name="replace">
            <xsl:param name="pString" select="."/>
            <xsl:choose>
                <xsl:when test="contains($pString,'Certified Angus Beef ®')">
                    <xsl:value-of select="substring-before($pString,'Certified Angus Beef ®')"/>
                    <i>Certified Angus Beef<sup> &reg;</sup> </i>
                    <xsl:call-template name="replace">
                        <xsl:with-param name="pString"
                        select="substring-after($pString,'Certified Angus Beef ®')"/>
                    </xsl:call-template>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="$pString"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:template>
        <xsl:template match="text()[ancestor::item]" name="replace1">
            <xsl:param name="pString" select="."/>
            <xsl:choose>
                <xsl:when test="contains($pString,'Certified Angus Beef ®')">
                    <xsl:value-of select="substring-before($pString,'Certified Angus Beef ®')"/>
                    <i>Certified Angus Beef<sup> &reg;</sup> </i>
                    <xsl:call-template name="replace">
                        <xsl:with-param name="pString"
                        select="substring-after($pString,'Certified Angus Beef ®')"/>
                    </xsl:call-template>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="$pString"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:template>
    </xsl:stylesheet>

    An element attribute is set with the method
    setAttribute(String name,
                             String value)or the
    setAttributeNode(Attr newAttr)method.

  • Set image src within a symbol - How?

    I have created a symbol in Edge Animate, which contains a rectangle as view area and an image and text as contents of that view area. I want to set text and image src before I start the animation of the symbol. I can set "Text" with
    var thing = sym.getSymbol("mySymbol");thing.$("Text").html("I can set some text here to change the content of Text.");
    and when I start the animation of that symbol, the new text is used. Question now is, how I can set the image source for the item "Image" within that symbol. I have looked into the files Edge Animate creates, and the text as shown above is in a field called "text", while the name of the image is contained with other information in a field called "fill". I don't have a clue how to set the image source. Any pointers?
    I don't want to create 24 instances of something for an advent calender, I just want to have one, which I fill through JavaScript, before the animation is shown. All text and all images have almost the same size, so this should be doable somehow.
    The follow on question would be, whether the preloader loads all 24 images, because they are not actually referenced in any EA object...
    Thanks in advance!

    This tutorial (with sample file) should assist with what you are attempting to accomplish.
    http://www.gotoandlearn.com/play.php?id=168
    hth
    Darrell

  • Box in  Sap Script and text within

    Hi,
    I want to create a box at the end of the main window and text within it.
    The main window can end at 1st page itself or it can be extended to second page based on the articles. So the box should appear at the end of the last article in the main window.
    and also i would like to know, how do we write text in a box.
    Could any1 help me out on this.
    Thanks

    You can create a variable window in the main window.
    You can restrict the last item of the main window by varying the size of main window. In your wite-form ,
    CALL FUNCTION 'WRITE_FORM'
          EXPORTING
             element                  = 'ITEM'
          function                 = 'SET'
          type                     = 'BODY'
          window                   = 'MAIN'
          EXCEPTIONS
            element                  = 1
            function                 = 2
            type                     = 3
            unopened                 = 4
            unstarted                = 5
            window                   = 6
            bad_pageformat_for_print = 7
            spool_error              = 8
            codepage                 = 9
            OTHERS                   = 10.
        IF sy-subrc <> 0.
    DO this. in the bottom of the main window, create a variable window.
    you can add your text in the variable window inside main window.
    it will be displayed just after the item ends.
    Reagrds,
    Pritha.
    Message was edited by:
            Pritha Agrawal

  • Can I set the text color in a Label?

    Hi everyone ~
    Can I set the font color in PP? I only found that there is a "setBackground".. but I want to set the color within a Label.
    Thanks!
    Gary

    Fixed it!
    There was a global style for s|Label and since the Spark button uses one of these for the text, that was it.

  • How do I format text within a TextArea

    Hello,
    I would like to create a simple text editor that performs
    syntax highlighting. In order to do so, I would need the ability to
    set the style of individual pieces of text within a TextArea. Is
    this possible? Do I need to subclass the TextArea (or perhaps the
    Text control) to do this? Any pointers in the right direction would
    be appreciated. Thanks!

    The issues around formatting text in the Flash Player are
    numerous. There are several experts who have weighed in on this,
    including .
    Axel
    Jensen who has made available a modification of the
    RichTextEditor component. Additionally,
    Jesse Warden has several older
    articles in his blog on this issue. Finally, there is a
    commercially available Flash/Flex text editor developed by Igor
    (last name unknown to me), and found at:
    http://www.flashtexteditor.com/.
    Overall, the issue of accurately formatting text in
    Flash/Flex has been an exercise in frustration, especially when
    trying to implement htmlText and CSS. I am absolutely amazed that
    Adobe's documentation for this very important aspect of web
    development is either unavailable or deeply flawed, and on top of
    that: How is the Acrobat Connect Buzzword application able to do so
    much with text formatting, clearly within a Flex Framework, and yet
    no concrete documentation of the techniques are available

  • Adding text to a JScrollPane

    I have a splitpane - the left pane is a tree and the right pane is a JScrollPane (similar to the Treedemo example code). When I select a node on the tree I add text to the JScrollPane. This works fine apart from the fact that the viewable area when the text is too big to fit in the original window shows the bottom part of the text instead of the top part. I have tried setting the scrollbars using myScrollPane.getVerticalScrollBar().setValue(newVValue) and
    myScrollPane.getHorizontalScrollBar().setValue(newHValue) but it doesn't seem to do anything. The values do not reset the scrollbars. It looks like this is because I am issuing the setValue methods in the TreeSelectionListener method. Is there a way I can reset the scrollbars to show the top part of the text rather than the bottom part ?

    textComponent.setCaretPosition(0);

  • How to set textfield.text on frame after goto

    This seems a little ridiculous to be asking this question coz
    it seems like it should be so simple but here goes anyway.
    STEPS TO RECREATE:
    Step 1 - create a class called simpleButt(see attached)
    Step 2 - create a MovieClip with two frame labels on
    different keyframes- ROLLOVER and ROLLOUT. on these different
    keyframes place a dynamic textfield with instance name -
    'buttonTitle'. give it different styling attributes on the ROLLOVER
    frame such as text colour, bold or even a glow filter.
    Step 3 - In the movie clip's linkage properties, give it the
    'simpleButt' class.
    Step 4 - With nothing on the stage, add the following two
    lines to frame actions:
    var newButt:simpleButt=new simpleButt("hello");
    this.addChild(newButt);
    Step 5 - compile!
    this should add a simple button to the stage and set the
    button's textfield's text property.
    However, after going to another frame on rollover, we lose
    the dynamic text - i assume because we have another instance of the
    textfield on a different keyframe because it has new styling
    properties on rollover. but if i try to set the text after going to
    the new frame, it doesn't seem to recognise the textfield yet.
    (uncomment lines in simpleButt to see what i mean)
    through trial and error i've found that if i wait two
    ENTERFRAMEs, the textfield object becomes available, but by this
    time the textfield flickers. is there an event i'm missing or
    function i could override where i could set the properties of an
    object on a frame after a gotoAndStop before it is rendered?
    cheers
    Craig

    STEP 2(where the textfield was created) is all done manually
    within the authoring environment - no actionscript. This is usually
    done by the design team here so to save time i'm trying to avoid
    replicating every style change they've made in code.

  • Using CTRL + F not working to find any text within the query result

    Hi friends,
    I am trying to use find option to find any text within the result section of a query but when I do CTRL+F  the find window appears and I can input the text that I wanted. But when I press Enter it is not giving me any result though the entered text
    is in the query result. I am using Sql Server 2012 Management studio. Any Body please help me. There is a job that I have to search certain things after running a script and now I am doing copy paste to excel and doing searching from there. 

    Prashant,
    Looks like you are trying to do in SSMS, and it is because the result set is in Grid view , if you want to use CTL + F then your result should be in Text format, try to do using CTL + T ( To get result in Text) and then use CTL + F to find any
    text.
    Thanks
    Manish
    Please click Mark as Answer if my post solved your problem and click
    Vote as Helpful if this post was useful.

  • ActionEvent/Setting gui text in an infinite loop

    Hi,
    I have set up a gui that contains ~ 100 JTextFields and one JTextButton
    Pressing the JTextButton on the gui triggers an action event that
    1.     establishes a socket connection w/ a server
    2.     reads input from the server in an infinite loop
    3.     should use the server data to dynamically setText in the various JTextFields found on the gui.
    for example, during one iteration of the infinite loop, the data may set the text of JTextField #1 to ?foo? and in a later iteration of the loop, the new data from the input stream may set the text of the same field to something else (e.g. ?bar?). Thus, the gui should show a dynamically changing collection of TextFields after the user presses the JTextButton.
    Problem: because of the infinite loop, NONE of the fields is ever updated (see pseudocode below). If I remove the infinite loop and simply have 1 iteration of the block of code within the actionPerformed method, the gui updates properly.
    How might I alter the code to a) maintain the server connection, b) continuously read from the input stream and c) have a dynamic update of the textfields w/in the gui?
    I've tried adding "this.paint(this.getGraphics());" within the infinite loop and it sort of works, but the updates to the gui are FAR SLOWER than the data that are streaming in from the server.
    Thanks for any help!
    The code looks something like this
    Public class abc extends JFrame
    Public abc()
         {initialize components}
    instantiate all textfields & button
    create various arrays
    public void initialize components
         (set up gui using gridbaglayout
         add actionListener to button)
    private actionperformed
    (establish socket connection w/ server
         read data from server in an infinite loop
         parse data and use information to setText on the gui)
    public static void main(blah blah)
         show abc();

    have the reading loop in a different class which will have its own Thread running aside from the main program's thread. This way your application will do both at once :)

  • Centering Text within JLabel

    I am trying to figure out a way to center the text within a JLabel. I trying to set a specific size of the label, and then center the text in the very middle (horizontally) of that label. I have tried many different methods from this forum and other places on Google, but none of them have had any effect. For example:
    label = new JLabel ("<html>blah, blah, blah, blahblah, blah...</html>"); 
                                                         // HTML tags make the lines wrap.
              label.setHorizontalAlignment(JLabel.CENTER);
              label.setPreferredSize (new Dimension (84, 48));The text remains aligned left within the label. Is there a way to get it to center within the label?

    what version are you using?
    your posted code works OK in 1.5.0_05
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setSize(300,100);
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        JLabel label = new JLabel("<html>line 1<br>line 2</html>");
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setPreferredSize (new Dimension (84, 48));
        label.setBorder(BorderFactory.createLineBorder(Color.black));
        p.add(label);
        getContentPane().add(p);
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Positioning text within block

    Hi
    I am wanting to postion text within a Box/block, these are list items that I have used as navigation buttons.
    I have set the box size and have selected "center" for text positioning, this positions the text in the centre horizontally ok.
    I would like to know how to position the text centrally verticially aswell?
    Many thanks
    Mark

    Hi
    Thanks for quick answer.
    I can get the padding within a div option to work, but one of the List  items/ button texts needs different padding to the others because it is two lines of text.
    Can I differentiate the treatment of one "Li" ??
    Cheers
    Mark

  • Text within textframe disappearing once placing tiled background

    Hello,
    I'm new with the creative suite and trying to navigate and learn!  Super steep learning curve..
    Here's my issue:  The text within my text frames in InDesign disappears when I place a tiled background I created in photoshop.  I've put the background .psd file in the bottom-most layer, tried sending it back, but for some reason, text in higher layers just keep disappearing.  Images will show up, but never text.
    Any help with this issue?  And I apologize in advance if this has already been answered somewhere in the forum. 
    Many thanks!

    Sounds like you have text wrap applied to the background image. Either turn it off, or set the text frame options to "ignore Text Wrap"

  • Message styuled text within a popup region

    Hi
    i am working on extension of standard pages. I have a requirement of displaying a message styled text within a popup region when i click on a button. This message styled text should hold large value like a set of instructions. How do i assign the region with this text? Should i use message styled text or some other region?
    Can anyone suggest me an approach?

    Hi
    I think this instruction s given in dev guide will be helpful to you
    You can declaratively create either short or long field-level hints:
    The short hints render immediately below the item as shown in Figure 1 (see the Purchase Order field).
    The long hints render as a selectable information icon next to the item (see the Created poplist in
    Figure 1). When the user selects the information icon, a dialog window opens as shown in Figure 3
    378
    below.
    Note that you cannot configure a static error message as shown in the UI Guidelines (this is displayed
    automatically for you when field-level validation fails; see Error Handling for additional information about this).
    You also cannot associate a warning icon with an item as shown in the UI Guidelines.
    Field-Level Hint
    To configure a field-level hint for any field that is not displaying a date (see the date format instructions below
    for this case):
    Step 1: In the JDeveloper structure pane, select the item with which you want to associate a hint.
    Note: Field-level hints can be configured only for those items whose name begins with message (for example,
    a messageChoice or a messageTextInput).
    Step 2: Set the Tip Type property to shortTip.
    Step 3: Define a message in the Applications Message Dictionary for the text you want to display. Set the Tip
    Message Appl Short Name and the Tip Message Name properties accordingly.
    The OA Framework displays your text in the current session language immediately beneath the related item.
    To configure the standard date format example beneath a date field:
    Step 1: In the JDeveloper structure pane, select the date item that needs a format example.
    Step 2: Set the Tip Type property to dateFormat.
    The OA Framework automatically renders a standard date format example using the user's date format
    preference.
    Long Hint (with Information Icon)
    To add a long hint to an item:
    Step 1: In the JDeveloper structure pane, select the item with which you want to associate a hint.
    Step 2: Set the Tip Type property to longMessage.
    Step 3: Configure the long message content:
    (Option 1) Define a message in the Applications Message Dictionary for the text you want to display.
    Set the Tip Message Appl Short Name and the Tip Message Name properties accordingly, and the OA
    Framework displays your message in the dialog shown below when the user selects the item's
    information icon.
    (Option 2) If you need complete control of the contents in the dialog window, do not specify the Tip
    Message Appl Short Name and Tip Message Name properties. Instead, design your own region and
    specify its fully qualified name for the Long Tip Region property (for example,
    /oracle/apps/fnd/framework/toolbox/webui/PurchaseOrderLongTipRN). At runtime, the OA Framework
    displays your region in the dialog.
    Figure 3: Dialog window that opens when the information icon is selected.
    Please refer OAD Devguide for complete details
    Thanks
    Pratap

Maybe you are looking for