Formatting JTextArea text

I want to take the text of a JTextField and save it on the file system formatting with character length limited to a certain amount per line (say 77) and save any blank lines the user enters. Each line is prefixed with "//$" which I look for when I read it back in. The problem I am running into is when I encounter a blank line. My code looks like this (str is the string from the JTextField.getText() method):
          if(!str.trim().equals(""))
               try
                    for(x = 0; x < str.length(); x++)
                         while(count != 76 && x < str.length() && !endOfLine)
                              count++;
                              if(str.charAt(x) == '\n')
                                   endOfLine = true;
                              x++;
                         if(x == str.length())
                              tmpStr+="//$ " + str.substring(start, x) + "\n";
                              count = 0;
                         else if(endOfLine)
                              tmpStr+="//$ " + str.substring(start, x);     
                              start = x;
                              count = 0;
                              endOfLine = false;
                         else if(str.substring(start, x).equals(null))
                              tmpStr+="//$$";
                              start = x;
                              count = 0;
                         else                         
                              tmpStr+="//$ " + str.substring(start, x) + "\n";
                              start = x;
                              count = 0;

Refer to the Java Tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html for more info on how to use the JTextArea. JTextArea only allow you to display plain text, so if you want the selected text to change color, you will have to use the JEditorPane (or its subclass JTextPane). Refer to http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html for more info.

Similar Messages

  • Formatting the text file

    hi folks,
    I have an text file with records, each record has several field values  and there is blank space between them, I need to remove the blank spaces, is there a way that i can do with all records at one stretch? Instead doing it for each record.
    I know it is not related to SAP but I need some help in this regard as there are  a lot of records and formatting each record manually is extremely painful. This is a corrected  file manually on a spreadsheet and converted into the text file from thereon.
    Any help is really appreicated.
    Thanks,
    SK

    Hi,
    What you are trying to do with the text file after removing the spaces?
    Are you going to use in SAp Upload? or just to remove the spaces in text fiel?
    If you are using it for other purposes, you should not remove the spaces, because for that particular field no data will be entered.
    (generally we remove the other chars's like " by Find and Replace method)
    Generally we format the text files from the Excel to utilise it somewhere?
    And we won't remove the spaces for surther uses.
    Regards,
    Anji

  • I created a pdf form from a Word doc with 9 pt aerial font formatting; the text on the pdf form is aerial 9 pt, but the fields are formatted in courier 12 pt - How do I reformat the font in the fields??

    I created a pdf form from a Word doc with 9 pt aerial font formatting; the text on the pdf form is aerial 9 pt, but the fields are formatted in courier 12 pt - How do I reformat the font in the fields??

    You can set up a temporary button (or link, bookmark, etc.) and add the following JavaScript action:
    // Mouse Up script for a temporary button (or bookmark, etc.)
    // Change the font and font size for all text fields in this document
    for (var i = 0; i < numFields; i += 1) {
        var f = getField(getNthFieldName(i));
        if (f.type === "text") {
            f.textFont = font.Helv;
            f.textSize = 9;
    It also sets the font size, but you can remove that line if you don't need to do that.

  • How to copy paste a table structure from word document into Text Field [field format Rich Text]

    In our current implementation we have a Blank page with Text Field [field format Rich Text] on generated PDF Document.
    Once the PDF document is generated, user can copy paste content form any word/rtf document to into the Text Field.
    Pasted content retains all text formatting [Bold, Italic, Underline, Indentation] except the Table format. Text Field is removing table metadata from the content and converting it into plant text.
    Is there anyway to copy paste table structure as it is from word document into Text Field?

    Hi,
    I don't think you can! While you can paste formatted text into the rich text field, the table metadata means nothing to the textfield.
    Niall

  • Format ICML text placed in InDesign

    Is it possible to format the text of ICMLs placed in an InDesign doc? (see below)

    Yes, but you need to check the story out first.
    Bob

  • Requirment Urgent: How to format standard text in Script like two columns.

    Hi,
    I want to format the text in two columns like this.
    1. This is the note. 5. This is the note.
    2. This is the note. 6. This is the note.
    3. This is the note. 7. This is the note.
    4. This is the note. 8. This is the note.
    I have to include a standard text and format like this.
    Thanks in advance.

    Hi,
    You have to create a paragraph format and create two tabs according to your column positions.
    and write.
    ,,&column1& ,,&column2&
    Regards,
    Wasim Ahmed

  • How to format a text object

    Post Author: ftpaxa
    CA Forum: Other
    I use a SQL server DataBase on Windows server 2003 with service pack 2. i use Crystal Report 10 with ODBC connection. I read that the nice DLL is "Crdb_odbc.dll".I saw a VB code "How to format a text object" on this site :http://technicalsupport.businessobjects.com/KanisaSupportSite/search.do?cmd=displayKC&docType=kc&externalId=crxiTechrefenpdf&sliceId=&dialogID=7686352&stateId=1%200%207680692--' Create a new instance of the report.Dim oReport As New CrystalReport1Private Sub Form_Load()' Declare a TextObject object.Dim oTextObject As CRAXDRT.TextObject' Declare a generic Object.Dim oObject As Object' Declare a Section object.Dim oSection As CRAXDRT.Section' This variable is set to true once the' text object is found.Dim bText As BooleanbText = False' Search for all the report objects in each section.For Each oSection In oReport.SectionsFor Each oObject In oSection.ReportObjects' Find the first text object.If oObject.Kind = crTextObject Then' Get the text object and exit the loop.Set oTextObject = oObjectbText = TrueExit ForEnd IfNext oObjectIf bText Then Exit ForNext oSection' Format the text object and change the text.With oTextObject.BackColor = vbYellow.BorderColor = vbRed.BottomLineStyle = crLSDoubleLine.CanGrow = True.CharacterSpacing = 125.CloseAtPageBreak = True.FirstLineIndent = 25.Font.Italic = True.Font.Bold = True.Font.Size = 14.HasDropShadow = True.Height = 900.HorAlignment = crLeftAlign.KeepTogether = True.Left = 200.LeftIndent = 750.LeftLineStyle = crLSDashLine.MaxNumberOfLines = 16.RightIndent = 250.RightLineStyle = crLSDotLine.Suppress = False.SuppressIfDuplicated = True.SetText "Hello World".TextColor = vbBlue.TextRotationAngle = crRotate0.Top = 25.TopLineStyle = crLSSingleLine.Width = 3000End With' Set the report source of the viewer and view the report.CRViewer1.ReportSource = oReportCRViewer1.ViewReportEnd SubSo, i would like to do the same thingswith winbatch language. I tried this code :;Get CrystalRuntime Application Object HandleobjCra = ObjectCreate("CrystalRuntime.Application");Logs on to on or more SQL servers or ODBC data sources.objCra.LogOnServer("Crdb_odbc.dll","Magic","xxx","xx","zzzz") ; ("DLL file", "Server", "dbname", "username", "password"); open the saved reportobjReport = objCra.OpenReport("C:\Download\Perso\Programmation\Winbatch\Crystal Report\Final\rapport exploitation - abend.rpt")objReport.DiscardSavedData()TxtObj = objReport.Sections("PHb").ReportObjects("Text11")txtObj.Text = "testing" ; *** Error on this line : 1266: Ole:Bad Param Count;Export htmlPathHTML = strcat("C:\Download\Perso\Programmation\Winbatch\Crystal Report\Final\Resultat\rapport exploitation - abend.htm")hfile = PathHTMLcre = crr.ExportOptionscre.DestinationType = 1 ; diskfilecre.FormatType = 32 ; 24 = (HTML 3.2 standard), 31 = (PDF), 32 = (HTML4.0) cre.HTMLFileName = hfilecrr.Export(BOOL:@false)objectclose(cre)objectclose(objReport)objectclose(objCra)exit--
    Everythings work good except this linetxtObj.Text = "testing" I receive this error :1266: Ole:Bad Param CountI may be don't have the nice recipe. If you have a solution, it is welcome.

    Post Author: KAM
    CA Forum: Other
    Try using SetText.  Thanks.

  • 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 );

  • Conversion of a attached file in raw format to text format

    Hi All,
           We have a requirement where in which we will be getting an attachement to the mail which wil be in rqw format,we wanted to convert this attachement in raw format to text fiel.Is there any function moduel for the same.
            Pointers wil be appreciated.
            Thanks in advance.
    Regards,
    zareena.

    Hi,
    Check this FM'S,
    SX_OBJECT_CONVERT_RAW_TXT
    SCMS_BINARY_TO_TEXT
    for more info search SDN forum with the keyword 'raw to text format'
    Regards
    Adil

  • Conversion of a  file in raw format to text format

    Hi All,
    We have a requirement where in which we will be getting a mail with an attachemnt , which wil be in raw format,we wanted to convert this attachement in raw format to text file.Is there any function moduel for the same.
    Pointers wil be appreciated.
    Thanks in advance.
    Regards,
    zareena.

    Hi Zareena.
    I would like to suggest,
    SX_OBJECT_CONVERT_RAW_TXT.
    Hope that's usefull.
    Good Luck & Regards.
    Harsh Dave

  • Date Format in text

    Hai all
    I want to get the date format in text like dd/mm/yyyy based on the locale value.
    Is it posible to get the string format insted of date.
    Thanks a lot
    Aniesh U.K

    Hai all
    I want to get the date format in text like dd/mm/yyyy
    based on the locale value.
    Is it posible to get the string format insted of
    date.
    Thanks a lot
    Aniesh U.KLook in the API documentation for java.text.SimpleDateFormat

  • How to display query variable in text element and format the text element

    Hi All,
    I want to display the value of the value of variable against fiscper3 and the value of the variable against 0fiscyear in the web application template from the query in the text element in the web template in BI 7 Web application designer.
    Also, in the web application designer I need to format the text element in the web application designer to set the text element to center the display change the size and make it bold. I am bit lost I cannot find these properties in the web application designer against the text element.
    Appreciate if you could kindly help.
    Thanks
    Karen

    Hi
    hope below tags would help you
    Re: Search by text on a variable
    Re: Need to display text part of TEXT variable in query designer
    regards
    nag

  • Getting unformatted text after decryption of formatted encrypted text

    The problem getting unformatted text after decryption of a formatted encrypted text.
    Im using Bouncy Caslte for encrypting the mail message.its a well formatted text but
    after decryption its unformmated?
    What will be the problem? why im getting the decrypted text as unformatted?

    sorry im using Bouncy Castle for encryption
    This is my code
    try {               
                   Security
                             .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
                   KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
                   ks.load(new FileInputStream("C:/rajesh/raj_gmail.cer"), "tomcat".toCharArray());
                   Enumeration e = ks.aliases();
                   String keyAlias = null;
                   String alias = null;
                   while (e.hasMoreElements()) {
                        alias = (String) e.nextElement();
                        if (ks.isKeyEntry(alias)) {
                             keyAlias = alias;
                   Certificate[] chain = ks.getCertificateChain(keyAlias);
                   // create the generator for creating an smime/encrypted message
                   SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
                   gen.addKeyTransRecipient((X509Certificate) chain[0]);
                   Properties props = System.getProperties();
                   try {
                        InputStream path = getServlet()
                                  .getServletContext()
                                  .getResourceAsStream(
                                            "/WEB-INF/classes/com/ips/ApplicationResources.properties");
                        props.load(path);
                   } catch (Exception e1) {
                        System.out.println("Not able to load the properties file");
                   props.put("mail.smtp.host", props.getProperty("mail.smtp.host"));
                   Session session = Session.getDefaultInstance(props, null);
                   MimeMessage msg = new MimeMessage(session);
                   String body_heading = props
                             .getProperty("mail.request.message.body");
                   body_heading = body_heading.replaceAll("[{]{1}[0]{1}[}]{1}",
                             Integer.toString(forms));
                   msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                             props.getProperty("mail.to.address")));
                   msg.setSubject(props.getProperty("mail.request.message.subject"));
                   StringBuffer body = new StringBuffer();
                   body.append(body_heading);
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.line1"));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.contact"));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.line2"));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.title")
                             + props.getProperty("mail.colon")
                             + String.format("%15s", title));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.fname")
                             + props.getProperty("mail.colon")
                             + String.format("%17s", firstname));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.lname")
                             + props.getProperty("mail.colon")
                             + String.format("%17s", lastname));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.address1")
                             + props.getProperty("mail.colon")
                             + String.format("%19s", address1));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.tab")
                             + props.getProperty("mail.colon")
                             + String.format("%20s", address2));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.tab")
                             + props.getProperty("mail.colon")
                             + String.format("%20s", town));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.tab")
                             + props.getProperty("mail.colon")
                             + String.format("%20s", county));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.pcode")
                             + props.getProperty("mail.colon")
                             + String.format("%11s", postcode));
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.email")
                             + props.getProperty("mail.colon")/*
                                                                      * +String.format("%33s",email
                   body.append(props.getProperty("mail.linebreak")
                             + props.getProperty("mail.message.thanks"));
                   MimeBodyPart bp1 = new MimeBodyPart();
                   bp1.setText(body.toString());
                   bp1 = gen.generate(bp1, SMIMEEnvelopedGenerator.RC2_CBC, "BC");
                   Multipart multipart = new MimeMultipart();
                   multipart.addBodyPart(bp1);
                   msg.setContent(multipart);
                   msg.saveChanges();
                   Transport.send(msg);
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              }if i print the original text im getting the content in my mail as
    Please send me 1 application form pack(s)
    Contact Details
    Title: Mr
    First name: rchanged
    Last name: rchanged
    Address: rchanged
    : rchanged
    : r
    : r
    Postcode: r4 4rr
    Email:
    Thank You
    if encrypted is send
    Please send me 1 application form pack(s) ------------------------------------------------------ Contact Details ------------------------------------------------------ Title: Mr First name: rchanged Last name: rchanged Address: rchanged : rchanged : r : r Postcode: r4 4rr Email: Thank You

  • How format a text with "Justified"?

    Hello!
    I would like to make a photo book (iphoto '08) with lengthy passages of text.
    Does anyone know how I can format a Text in "justified"?
    Siggo

    Create the text in another app - say Pages or TextEdit and set your alingment as you wish. Then copy and paste t the book
    Regards
    TD

  • Formatting XML text

    Hi. I've been trying to figure out XML in flash and found a
    (old) tutorial that worked for me. i want to format the text using
    html tags. I have found other tutorials on this claiming it's easy
    using CDATA, but i can't get it to work with mine. It either shows
    the text with the tags, or NULL when i add it wrong. I understand i
    need to add bold fonts, etc, but i'm adding the code wrong.
    If this IS simple (or even possible), will someone help and
    show where it needs to be placed in the code? Any help at all is
    appreciated.
    Thanks.

    You do use CDATA tags if you want to put HTML inline in your
    XML. When you
    do that though, you need to set the htmltext property of the
    field, not the
    text property. And not all HTML will work - tables for
    instance.
    Dave -
    www.offroadfire.com
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

Maybe you are looking for

  • How do I install Mountain Lion on FileVault2 encrypted System disk

    So I got a Mountain Lion installation DVD from our system administrator at work to upgrade my 2010 MacBook Pro. I run the installer from the disk under Lion and it copis stuff to /OS X Install Data and reboots. Now, it just displays the "Lion" passph

  • Oracle 8.1.6 on RH Linux 6 installation problem

    I am using Universal Installer to load Oracle 8.1.6 on Red Hat Linux 6 and it isn't able to complete the Oracle Database Configuration Assistant routine. Up until then everything has been fine, but loading DCA results in the following error detail: S

  • Weblogic server is not getting started.

    Hi We are getting problem in starting weblogic server 10.2 . We have two machine they switch each other by cluster. On one machine , Weblogic server does not start when cluster switch to this machine. When server starts , it hangs. We get following e

  • Looking for chmod equivalent for Windows

    A little back story, I've managed to cobble together an After Effects psuedo plugin installer for one of my upcoming scripts. One hiccup was dealing with file permissions, to properly install the plugin. After many searches, trial & errors, and final

  • How do I order prints from more than one Photo in Aperture?

    I can figure out how to order prints through Apple for ONE photo but can't find how to add more photos to the order.  Is there a manul for Aperture 3.4.5 version? This whole program has me confused.  I need a manual I think.  Thank you.