JTextPane.setText(String) - New line problem

Hello.
I'm usin a JTextPane for a small editor I need.
I'm using it for it's ability to use HTML format codes (<font color = #color>string</font> for a singular line);
Now, It's loading lines from a text file. Then, I made a function to parse the array data into a singular string, and return it.
It's along the lines of
String parseArrayToString(String[] data) {
    String returnString = "";
    for(String s : data)
        returnString += s+"\n";
    return returnString;
}This worked for JTextArea, but not for this.
Is there any way to do this using JTextPane?

More or less straight from from the number 2 google hit...
package forums;
// a slighty cleaned up version of:
// http://www.java2s.com/Code/Java/Swing-JFC/JTextPanedemowithvariousformatandhtmlloadingandrenderering.htm
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.Document;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class JTextPaneDemo extends JPanel
  private static final long serialVersionUID = 1L;
  private static final SimpleAttributeSet ITALIC_GRAY = new SimpleAttributeSet();
  private static final SimpleAttributeSet BOLD_BLACK = new SimpleAttributeSet();
  private static final SimpleAttributeSet BLACK = new SimpleAttributeSet();
  static {
    StyleConstants.setForeground(ITALIC_GRAY, Color.gray);
    StyleConstants.setItalic(ITALIC_GRAY, true);
    StyleConstants.setFontFamily(ITALIC_GRAY, "Helvetica");
    StyleConstants.setFontSize(ITALIC_GRAY, 14);
    StyleConstants.setForeground(BOLD_BLACK, Color.black);
    StyleConstants.setBold(BOLD_BLACK, true);
    StyleConstants.setFontFamily(BOLD_BLACK, "Helvetica");
    StyleConstants.setFontSize(BOLD_BLACK, 14);
    StyleConstants.setForeground(BLACK, Color.black);
    StyleConstants.setFontFamily(BLACK, "Helvetica");
    StyleConstants.setFontSize(BLACK, 14);
  private JTextPane textPane = new JTextPane();
  public JTextPaneDemo() {
    textPane.setPreferredSize(new java.awt.Dimension(640, 480));
    JScrollPane scrollPane = new JScrollPane(textPane);
    add(scrollPane, BorderLayout.CENTER);
    appendText("\nHere's", BLACK);
    appendText(" Duke Baby", BOLD_BLACK);
    appendText("!\n\n", BLACK);
    textPane.insertIcon(new ImageIcon("C:/Java/home/src/crap/Java2D/images/duke.gif"));
    appendText("\n\nIsn't he just so cute ;-)\n\n", ITALIC_GRAY);
    JButton btnLoad = new JButton("Load web-page: The Java Tutorials");
    btnLoad.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          textPane.setEditable(false);
          try {
            textPane.setPage("http://java.sun.com/docs/books/tutorial/");
          } catch (IOException e) {
            e.printStackTrace();
    textPane.insertComponent(btnLoad);
    setVisible(true);
  private void appendText(String text, AttributeSet attributes) {
    try {
      Document doc = textPane.getDocument();
      doc.insertString(doc.getLength(), text, attributes);
    } catch (BadLocationException e) {
      e.printStackTrace();
  private static void createAndShowGUI() {
    JFrame frame = new JFrame("JTextPane Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new JTextPaneDemo());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
}Cheers. Keith.

Similar Messages

  • Jtextfield new line problem

    Hey guys :-)
    I seem to have a little problem with my jtextfield, it seems to be ignoring any "\n"'s i tell it to print. The code to setup my jtextfield is below and was created with jigloo for eclipse!
    fileInputjTextField1 = new JTextField();
    this.getContentPane().add(getFileInputjTextField1());
    fileInputjTextField1.setBounds(20, 20, 420, 200);
    fileInputjTextField1.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));And i'm setting it with...
         public void setWindowText(){
              LoadHelp helpLoader = new LoadHelp(fileName);
              fileInputjTextField1.setText(helpLoader.readInHelp());
         }The readInHelp function returns a string which contains "\n's". using println it recognises the new lines, but the text field won't.
    Also, the text is appearing the the center of the box instead of the top line?
    Any help appreciated :-) Am a little new to gui coding

    This give the code below :
    JTextArea textarea = new JTextArea();
    textarea.setBounds(20, 20, 420, 200); // Set the dimensions
    textarea.setText("line1\nline2");

  • Add New Line Problem in Mobile Device

    Hi Abapers Guru,
    i have a problem when developing java webdynpro.. i intend to view SAP Long Text in Text Edit.. in doing so, i'm adding string "\n" to trigger new line.. it is working fine when i'm running in web browser or blackberry simulator.. but when i'm running in true blackberry device, it won't trigger a new line.. so the text show concatenated..
    i have tried some posibillity like '\n' "\n", "\n\r", "\r\n", '\', but it didn't work..
    any suggest please?
    thanks so much..
    Regards,
    Rendy Pranadithya
    Edited by: Rendy Pranadithya on Nov 8, 2010 12:13 PM

    Have you tried with line feed?
    i.e.
    instead of:
    constants: c_tab type c value cl_abap_char_utilities=>NEWLINE.
    try:
    constants: c_tab type c value cl_abap_char_utilities=>CR_LF.

  • FileUtilsService Write String New Line Character

    Hi All,
    SITUATION:
    Writing a custom log file using the Write String service operation.
    Everytime an event occurs, i want to insert a new line, with date time stamp, details etc.
    PROBLEM:
    In the "value" property of the "write string" service operation... im inputting my relevant data but dont know how to indicate a new line
    WHAT I TRIED:
    I've tried every form of new line character i know: \n, \r, <BR>, \u0000a, \u0000d, ACSII, CRLF, etc, etc... none of them works.
    WHAT I FEAR:
    the exact same situation as http://forums.adobe.com/message/2780658#2780658 ... with a fairly definite answer
    I'm hoping i dont have to go this LONG ugly scary route.
    WAY FORWARD:
    Your thoughts, answers, suggestions....
    Thanking you all in advance.

    if going the "executeScript" way....
    this code worked for me:
    ===========================
    import java.lang.String;
    String vLogEntry = patExecContext.getProcessDataStringValue("/process_data/@logEntry");
    String vLogEntry = vLogEntry + " \r\n";
    patExecContext.setProcessDataStringValue("/process_data/@logEntry", vLogEntry);
    =================

  • New line problem in sending sms through SAP

    Hi all,
    I need to send sms through sap. I have a code working fine.
    constants: c_tab type c value cl_abap_char_utilities=>NEWLINE.
    concatenate 'Sales INFO-' date3  into line1 separated by space.
      move 'Order Input' to line2.
      concatenate 'Day: Rs.' day_oamt   into line3 separated by space.
      concatenate 'MTH: Rs.' month_oamt into line4 separated by space.
      concatenate 'YTD: Rs.' yord       into line5 separated by space.
      move 'Billing' to line6.
      concatenate 'Day: Rs.' day_bamt   into line7 separated by space.
      concatenate 'MTH: Rs.' month_bamt into line8 separated by space.
      concatenate 'YTD: Rs.' ybill      into line9 separated by space.
    concatenate line1 line2 line3 line4 line5 line6 line7 line8 line9 into text separated by C_TAB
    concatenate '+91' m_no+len(10) into m_no.
    'http://************************************='
      M_NO
      '&msg='
       text
        '&************************************************=text'
       inTO WF_STRING.
    CALL METHOD cl_http_client=>create_by_url
        EXPORTING
          url                = wf_string
        IMPORTING
          client             = http_client
        EXCEPTIONS
          argument_not_found = 1
          plugin_not_active  = 2
          internal_error     = 3
          OTHERS             = 4.
      CALL METHOD http_client->send
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2.
      CALL METHOD http_client->receive
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2
          http_processing_failed     = 3.
      CLEAR result .
      result = http_client->response->get_cdata( ).
    I am able to send the message but it gets displayed in one line.
    SALES INFO- <dd.mm.yyyy> Order Input DAY: Rs.123 MTH: Rs.123 YTD: Rs.123 Billing DAY: Rs.123 MTH: Rs.123 YTD: Rs.123
    What I need to do is this.
    SALES INFO- <dd.mm.yyyy>
    Order Input
    DAY: Rs.123
    MTH: Rs.123
    YTD: Rs.123
    Billing
    DAY: Rs.123
    MTH: Rs.123
    YTD: Rs.123

    Have you tried with line feed?
    i.e.
    instead of:
    constants: c_tab type c value cl_abap_char_utilities=>NEWLINE.
    try:
    constants: c_tab type c value cl_abap_char_utilities=>CR_LF.

  • Having problems PrintWriter and new lines in a string

    I apologise if this topic is in the wrong place, but this is my first time asking on these forums.
    At the moment I have a window with an output text area which I want to store the contents of into a file. I use getText() to store the contents to a string, and then write the string to a file using a BufferedWriter. the code is as follows:
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    String contents = output.getText();
    out.write(contents);
    out.close();The file-name is specified by a FileChooser. All of this works fine, and the text is actually written to the file ok, except that there are no line breaks in it (it's just one continual line of text). I have tried the same process using a string containing "test\ntest" to see if it is just a problem getting the contents of the text area, however it still gives me the same problem.
    Any help on this would be much appreciated.

    Take a look at PrintWriter.
    o See if you can wrap it around a BufferedWriter. (It
    may alrady BE one.)
    o Use it's .println(...) method.That'll still make it appear as one line though. The one-and-only "line" will have the correct platform-specific line terminator (\r\n I suppose), but the string he is writing has embedded \n characters in it, which he is expecting to show up as new lines.
    The OP needs to realize that there really aren't any such thing as "lines". It's all up to the software rendering the text to treat "newline" characters/sequences special. If you were to open that file with a different tool (not Notepad, which only recognizes \r\n as newline sequences), it may display it the way you are expecting.
    Or, you'll have to parse the text and convert it to the proper newline sequences before you write it to the file.

  • How to make new line in JButton.setText()?

    how to make new line in JButton.setText()?
    I want to set the text of jbutton in tow line ,as follows
    | jbutton-line1 |
    | xxxxxxx-line2 |
    i konw i can jbtton.settext("<html>line1<br>line2</html>");
    but i find it's ugly using html,
    is there anyother way to create new line in JButton's Text

    As for the above comment....
    I thought the question was well purposed. Using HTML was not acceptable in this instance, which was made clear, so why critisize his comments? "Using HTML" is a poor solution, it does NOT work in many instances due to browser, OS variations. Usually the "common answer" is never a COMPLETE answer.
    Possible Solution:
    Use JLabels to render the text on the button.
    import javax.swing.*;
    import java.awt.*;
    public class ButtonMaker {
    public static void makeButton(JButton jb, String[] titleList) {
    jb.setLayout(new FlowLayout());
    for (int i = 0; i < titleList.length; i++) {
    JLabel tmpLabel = new JLabel(titleList);
    tmpLabel.setForeground(Color.black);
    jb.add(tmpLabel);
    public static void clearButton(JButton jb) {
    Component[] cList = jb.getComponents();
    for (int i = 0; i < cList.length; i++) {
    if (cList[i] instanceof JLabel)
    jb.remove(cList[i]);
    Known Limitations:
    1. Flowlayout does not work well with single line text buttons... perhaps another layout manager may work better for various buttonsizes-linenumber combos.
    2. Mac OSX : The default UI for Mac OS X (and above it seems), is to have rounded edged buttons. These rounded edges are destoryed when using JLabels, leaving a square, blocky button in its place.
    POSSIBLE SOLUTION:
    (this is ugly and time consuming)
    - create images of the button with text on them.

  • How to write this logic  in EL expression ? (new line characters in string

    iam using JSTL EL expression in my JSP.
    iam printing a string in JSP as ${vobject.rmessage} where rmessage is a string .
    problem is i want to identify the newline characters in the above rmessage string and print the line break <br> in html where ever the new lines character is present in the string.
    How should i write an EL expression for the above.
    Can anyone please guide me on writing EL expression for the above problem?

    Several ways. You can wrap the output with <pre> tags. You can apply CSS property white-space: pre; to the element. You can use String#replaceAll() in the Java code to replace each occurence of "\r\n" by "<br>".

  • Problem in creating New line in --File writing(Urgent)

    Hi all
    I am facing a tipical problem.
    I am writing a Text file using FileWriter and i am using "\n" for writing a new line,
    but when i open notepad all are falling on a single line with a special char
    (if i open the text file in some other editor vie wis very fine)
    C-0-1@C-1-0@ C-2-1
    @ is where i am writing new line.
    but this king of writing is not supported by my third party tool to which i am sending the text file
    as parameter..
    Kindly any one provide me a solution.
    Bye

    newlines differ between windows and linux/unix. Windows' new line character is somthing like "\n\m" where linux uses "/n". So to keep your program platform independent I would suggest using System.getProperty("line.separator") so your code might look like:
    String s = "C-0-1" + System.getProperty("line.separator") + "C-1-0" + System.getProperty("line.separator") + "C-2-1";
    //then write the string to the filethis will give you the appropriate newline character for the platform your program runs on.

  • Problem is occurring in docx format; it is not printing "New Line" character in extracted txt using IFilter (offfiltx.dll) while with doc file IFilter (OffFilt.dll) is working fine.

    Problem: Problem
    is occurring in docx format; it is not printing “New Line” character in extracted txt using IFilter (offfiltx.dll) while with doc file IFilter (OffFilt.dll) is working fine.
    Environment: -
    Operating
    System:
    Windows XP SP2/7
    Language:
    C#
    MS
    Office Version: - MS Office 2007/2010/2013
    Problem
    Description: -
    We
    havedocx
    file with new line character, and we are processing this file in IFilter for extracting text, and it is giving output with concatenation of lines.
    Docx
    file format (Sample.docx)
    Test this music
    Word processing
    Testing docx file
    Output:
    - Test this music Word processing Testing docx file
    Requirement:
    - We
    have requirement to get following text in particular format with New Line from docx because client is using docx format only.
    Test this music
    Word processing
    Testing docx file
    Attempt:
    We have tried a lot after changing IFilter configuration,
    but it is not giving required output. Then we saved same file in doc format (Sample.doc), which is giving required output.
    Because it is application specific problem, kindly
    assist to resolve issue on priority. We are sharing IFilter paths for extracting text for doc and docx.
    Doc Filter Location: - %systemroot%\system32\OffFilt.dll
    Docx Filter Location: - <Drive>:\PROGRA~1\COMMON~1\MICROS~1\Filters\offfiltx.dll
    Code Snippet for setting property of filter
    internal static IFilter LoadAndInitIFilter(string fileName, string extension)
                IFilter filter
    = LoadIFilter(extension);
                if (filter
    == null)
                    return null;
                IPersistFile persistFile
    = (filter as IPersistFile);
                if (persistFile
    != null)
    persistFile.Load(fileName, 0);
                    IFILTER_FLAGS flags;
                    IFILTER_INIT iflags
    =
                                IFILTER_INIT.CANON_HYPHENS
    |
                                IFILTER_INIT.CANON_PARAGRAPHS
    |
                                IFILTER_INIT.CANON_SPACES
    |
                                IFILTER_INIT.APPLY_INDEX_ATTRIBUTES
    |
                                IFILTER_INIT.HARD_LINE_BREAKS
    |
                                IFILTER_INIT.FILTER_OWNED_VALUE_OK;
                    if (filter.Init(iflags,
    0, IntPtr.Zero, out flags)
    ==IFilterReturnCode.S_OK)
                        return filter;
                Marshal.ReleaseComObject(filter);
                return null;
    Kindly
    assist to resolve this issue and also let us know if any input is required.
    For any help, we would be really
    thankful.

    Kindly
    assist to resolve this issue and also let us know if any input is required.
    For any help, we
    would be really thankful.

  • Add a new line at the begining of a string in a Xquery ALSB3.0

    Has anyone figured out how to Add a new line at the begining of a string in a Xquery in ALSB3.0?
    Thanks for your Help.

    I believe this is related to BI Publisher. Any comments would be greatly appreciated.
    Thanks,
    Sinan

  • Problem with CDATA and new line character

    I parse a xml document with org.w3c.dom, the document contain a CDATA section in which there are more lines of text, each line is terminated with the new line character (\n).
    Example:
    <nota>
    <[CDATA[
    first line
    second line
    third line
    ]]>
    </nota>
    When a parse this node:
    Text txt_nota=(Text)elm_nota.getFirstChild();
    String nota=txt_nota.getData();
    the value returned is one string with no new line characters, example:
    "first linesecond linethird line"
    what's wrong?

    Because i use the string nota into a jsp page and i print the string nota into a textarea and the text is with no newline, example:
    <textarea name="nota" rows="4" cols="60"><%= nota %></textarea>
    the text into textarea is:
    first linesecond linethird line
    but i want that the text displayed into textarea is equal the text into the CDATA section:
    first line
    second line
    third line

  • I'm having problem with text boxes.  Whenever i hit the enter button to start a new line or paragraph, the cursor doesn't drop down to the next line.  Instead i get this little red + sign in the box.

    I'm having problem with text boxes.  Whenever i hit the enter button to start a new line or paragraph, the cursor doesn't drop down to the next line.  Instead i get this little red + sign in the box.

    You are absolutely right.  Thought Enter meant Enter.  I was wrong.  Thank you for the help.
    Rod Rogers, Broker
    Accredited Land Consultant (ALC)
    Metcalf Land Company, Inc.
    Office: 864-585-0444
    Mobile: 864-316-0297
    Fax: 864-583-6000
    <http://www.metcalfland.com> www.metcalfland.com

  • Regarding problem with new line feed for DME file generation

    Hello Experts,
    I m facing a problem in the DME file generation.
    we want each record in the DME file should be in new line. for that we have add the new line feed character in the each row end. So in the SAP output it looks ok, But if we download that file the carriage return field is coming in the end of every row.
    can any one tell how to solve this issue.
    Please refer the below line code which i m using for new line
    DATA: GM_newline TYPE c VALUE cl_abap_char_utilities=>CR_LF
    You reply is valuable..
    Thanks,
    Suresh

    DATA: GM_newline TYPE c VALUE cl_abap_char_utilities=>newline.

  • Problem with new-line-character and java.io.LineNumberReader under AIX

    Hi folks,
    I got the following problem: I wrote a little parser that reads in a plain-text, tabulator-separated, line-formatted logfile (and later on safes the data to a 2-dimensional Vector). This logfile was originally generated by an AIX ksh script, however, I copied it on my Windows machine to work with it (for I'm using a Java editor that runs under Win Systems).
    For any reason, Windows, and what is worse Java too, seems not to recognize correctly the new-line character (in the API it is written that this should be a newline '\n' or a carriage-return '\r' or one followed by the other) that marks the end of a line in the logfile.
    Also, when I'm opening the logfile with the "Notepad"-editor, this special character does not seem to be recognized, every line is inserted right after the other.
    On the other side, when I open the logfile with the built-in editor in the CMD-Shell ("Dos-shell"), the newline chars seem to be recognized correctly.
    But when start my parser on the AIX-machine the newline does not seem to be recognized correctly again.
    I tried to read in the logfile with MS-Excel and safe it as a plain-text, tabulator-separated, line-formatted logfile again, with such files my parser works fine both on the AIX as it does on Windows.
    Any ideas? Anybody got over the same problem already?
    Greetz FK

    Under windows, text files' lines are usually delimited by \r\n,
    under Unix/Linux/AIX etc. \n
    and under Mac \r.
    I recommend to use the following editors, which are capable to handle files with Unix and Windows-styled line-delimiters or convert between these types:
    Programmer's File Editor (PFE; available on Windows)
    The Nirvana Editor (http://www.nedit.org/; available on Unix, MAcOS, Windows)
    (BTW good old vim can handle that too. Transferring text files to windows in order to edit them, even using Excel for this purpose means your being a UNIX newbie, (I mean no offense by writing this) so vim is probably beyond your reach for the moment.)
    Java normally assumes the platform's line delimiters where it is running, so if you transferred the file from Unix to Windows might be distrurbing.

Maybe you are looking for