Inserting HTML into JTextPane

Hi,
I am trying to insert HTML into JTextPane.
I am using the following code for the same.
JTextPane jedit = new JTextPane();       
jedit.setContentType("text/html");
        HTMLDocument doc = (HTMLDocument)jedit.getDocument();
        String text = "<a href=\"???\">hyperlink</a>asd<a href=\"???\">hyperlink123</a>";
        HTMLEditorKit editorKit = (HTMLEditorKit)jedit.getEditorKit();
        editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null);
        doc.insertString(doc.getLength(),"Hi testing",null);
        text = "<a href=\"???\">hyperlink123</a>";The problem is that the HTML gets inserted into new line. I do not want the new line.
I know there is an API like insertBeforeEnd(...) but do not know how to use that.
Any help for the above problem will be of great use.
Thanks.

look I have got the answer ... I guess this would be the root cause of the problem of new line.
when ever you want the text to be inserted
-at new line provide the last argument  of HTMLDocument.insertHTML as null
- at same line provide the last argument as the HTML tag you are inserting into the JtextPane's document.thats it !!!
ENJOY :-)

Similar Messages

  • A Simple Question... inserting image into JTextPane...

    Well my problem is very simple (but not for me). Before I explain it, please take a look at a simple class...
    public class Window extends JTextPane {
        Window() {
            super();
        }// Window
        public void appendText(String s,Color col) throws BadLocationException {
            StyledDocument sd = getStyledDocument();
            SimpleAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setForeground(attr,col);
            sd.insertString(sd.getLength(),s,attr);
          *     THE POINT - what should I write here, please consult description followed by the class.
        } //appendText
    } //classThe appendText method simply appends the text in text pane with desired color. Now I want to know what should I write at point THE POINT so that at end of appended string an icon (suppose end.gif) is added and is displayed in text pane. Simple?
    Stay happy,
    fadee

    Dear Fadee,
    here is a small programe for inserting images into JTextPane;
    find this comment and start
    /*All Code In this Button Action*/if you need any thing feel free to tell me,
    i'm with you brother, i'll do my best :O)
    -Best regards
    mnmmm
    * Fadee.java
    * Created on June 7, 2002, 1:13 AM
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.color.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    * @author  Brother Mohammad, Cairo, Egypt.
    * @version
    public class Fadee extends javax.swing.JFrame {
        JTextPane   tp;
        JButton     b;
        StyledDocument sd;
        SimpleAttributeSet attr;
        public Fadee() throws BadLocationException {
            b = new JButton("Press");
            tp = new JTextPane();
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    /*All Code In this Button Action*/
                    try {
                        sd = tp.getStyledDocument();
                        attr = new SimpleAttributeSet();
                        /*get default style*/
                        Style def = StyleContext.getDefaultStyleContext().
                                            getStyle(StyleContext.DEFAULT_STYLE);
                        /*add style for text default style*/
                        Style regular = tp.addStyle("regular", def);
                        StyleConstants.setFontFamily(def, "SansSerif");
                        StyleConstants.setAlignment(def, StyleConstants.ALIGN_CENTER);
                        StyleConstants.setForeground(def, Color.RED);
                        /*add style for icon create as many as icons you have
                         and don't forget to resize the photo at small size
                         to fit with font size*/
                        Style s = tp.addStyle("icon", regular);
                        StyleConstants.setAlignment(s, StyleConstants.ALIGN_JUSTIFIED);
                        StyleConstants.setIcon(s, new ImageIcon("d:\\My Photo.GIF"));
                        /*here is what user will see*/
                        sd.insertString(sd.getLength(), "Allah Akbar ", tp.getStyle("regular"));
                        sd.insertString(sd.getLength(), " ", tp.getStyle("icon"));
                    } catch (BadLocationException x) {
                        x.printStackTrace();
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(b, BorderLayout.NORTH);
            getContentPane().add(tp, BorderLayout.CENTER);
            setSize(500, 500);
            setVisible(true);
        public static void main(String args[]) {
            try {
                Fadee f = new Fadee();
            } catch (BadLocationException x) {
                x.printStackTrace();
    }

  • Inserting HTML into a table?

    I am trying to find an easier method of inserting html code into a column of type varchar2. I have to insert 100's of lines of html into a table weekly and the inserts keep failing because of special charecters within the html code itself. I have written scripts using UTL_FILE functions but this is very tedious to do weekly. Is there a better method to accomplish inserting html?

    try this.
    Hi,
    procedure start_import (p_filename in varchar2)
    is
    v_lob clob;
    v_offset number := 1;
    v_file bfile := bfilename('IMPORT',p_filename);
    v_lob_length number;
    begin
    -- File open
    dbms_lob.fileopen(v_file);
    -- get file length
    v_lob_length := dbms_lob.getlength(v_file);
    -- Create temp LOB (CACHED)
    dbms_lob.createtemporary(v_lob,TRUE);
    -- fill Temp Lob with filecontent
    dbms_lob.loadfromfile(v_lob,v_file,v_lob_length);
    -- Close file
    dbms_lob.fileclose(v_file);
    So, now you have the Filecontent in your temp LOB.
    For more info. about LOB, read Oracle Documentation.
    Hope this helps,
    Kalpen
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Troy Johnson ([email protected]):
    I am trying to find an easier method of inserting html code into a column of type varchar2. I have to insert 100's of lines of html into a table weekly and the inserts keep failing because of special charecters within the html code itself. I have written scripts using UTL_FILE functions but this is very tedious to do weekly. Is there a better method to accomplish inserting html?<HR></BLOCKQUOTE>
    null

  • Inserting html into a composition in muse

    Hi, I am trying to insert some html into a composition in Muse.  I would like to have a clickable button trigger, and then a kind of overlay opens up with an interactive calculator inside.  I have the html for the calculator, the problem is no matter how I try to insert it into Muse, the calculator either disappears (as well as the trigger) for some reason, or the calculator stays on the page the entire time, losing the whole clickable effect.
    Can someone tell me the best way to do this?

    Hello,
    Which Composition are you trying to Use ? Blank,Featured News, Lightbox Display, Presentation or Tooltip ?
    Also Make Sure to drag and drop the inserted HTML window over the target (Border of target gets activated once you move it over), Hopefully this will work.
    I created the same using Tooltip composition and its working fine. Please take a look at the link.
    Home
    If it do not work then please share the calculator HTML  code that you are inserting so that I can do some test at my end.
    Regards
    Vivek

  • Inserting HTML into JEditorPane

    I have a window with a JEditorPane on top and a JTextField below it. I need to be able to type raw HTML into the edit field and have it appended to the HTML document displayed above.
    For example if I type...
    This is <b>bold
    I need to append that to the document. However I want the style to stick. Notice I did not close the tag above. I want the next line I enter into the edit field...
    and so is this but not</b> this.
    I want this to appear bold up until the closing tag and then return to normal. The problem is that every time I append new text to the document the style is restored to normal.
    I insert the text with the following code. I send the contents of the JTextField to the following function when I hit return.
    void processInput(String input) {
    try {
    HTMLDocument doc = (HTMLDocument) output.getDocument(); // output is my JEditorPane
    editor.insertHTML(doc, doc.getLength(), input, 0, 0, HTML.Tag.BODY); // editor is HTMLEditorKit
    // relevant catch clauses
    Basically I want the two broken input sequences to appear in the editor as one seamless entry. I want to be able to type these two entries and have them show up as if they were entered as one entry.
    entry 1:This is <b>bold
    entry 2: and so is this but not</b> this.
    I want to somehow cause this to be displayed as if I typed...
    This is <b>bold and so is this but not</b> this.
    Is there a way I can do this?
    Thanks.
    -Russ

    as i understand you you want to write
    entry 1:This is <b>bold
    entry 2: and so is this but not</b> this.
    in two lines
    Try this
    entry 1:This is <b>bold<br>
    entry 2: and so is this but not</b> this.

  • Insert html into styled document

    Hi,
    I would like to insert html content into a JEditorPane that uses a StyledDocument and DefaultStyledEditorKit. I do not want to use the HtmlEditorKit for some reasons though that might change later. Now, I want to insert ElementSpec objects into my styled document and the only way seems to be doc.insert(o, espec) where espec is of type ElementSpec[]. I would like to insert my ElementSpecs one by one if possible.
    Can someone tell me how I can do this.
    Cheers,
    Omprakash.V

    Hi,
    I was referring to DefaultEditorKit in the above post when I said DefaultStyledEditorKit.
    Cheers,
    Omprakash.V

  • Is there a way of inserting symbols into JTextPane?

    Hi there folks. Is there a way of inserting symbols like greek letters in a standard way into JTextPane?

    use getDocument(). insertString(offs,str, attributes);
    str should contain proper unicode chars and attributes must contain proper font family to show the chars.
    use StyleConstants.setFontFamily()
    regards,
    Stas

  • Inserting HTML into a web page

    On a previous thread I asked how to insert ones own code into a page created in iWeb.Some kind person told me how to do it,namely: find the html page in iMac on my hard drive,in TextEdit insert the code that I want and click Save.It all worked fine. However when I go back into my web page in iWeb and make a change followed by upload, the code that I inserted in TextEditor is wiped.Is there any way that I can insert my own code into a web page and not get it wiped when I make other changes in iWeb and upload to the server? Thanks in advance

    Nope, this is how it works. If you make a change to a page like this post-publishing, and later re-publish, you have to make the html changes again! Set up a Find/Replace command in MassReplaceIt and you can do this very quickly. You can save your queries so you can make all of your changes with one click the next time you save.
    Download here:
    http://www.hexmonkeysoftware.com

  • Inserting text into JTextPane

    I have a requirement where I need to insert some text into a JTextPane within its DocumentListener. I read somewhere that this is not a good practice. What would be the right way of doing this?
    Basically, I'm listening to what user is typing and helping him by inserting some text automatically based on user choice.
    Please provide code samples.

    Hmmm - not knowing anything about the document listener - maybe they were talking about some kind of loop, where you insert text and then it triggers the listener to insert text which triggers the listener to insert text.... etc.
    Maybe there are some other user input listeners, such as the keyListeners which might be better?
    I haven't even had a look at the JTextPane API at the moment, so I don't know what I'm talking about.
    Cheers,
    Rene

  • Some problems about insert String into JTextPane

    here is the colde:
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc =(HTMLDocument)kit.createDefaultDocument();
    String str="hello world";
    SimpleAttributeSet attr =new MutableAttributeSet();
    StyleConstants.setFontFamily(attr, "Times New Roman");
    StyleConstants.setFontSize(attr, 12);
    StyleConstants.setBold(attr, true);
    StyleConstants.setBackground(attr, UIManager.getColor("control"));
    doc.insertString(1,str,attr);
    JTextPanel panel =new JTextPanel();
    panel.setEditorKit(kit);
    panel.setDocument(doc);
    text "hello word" of document can be show correctly,i save it as a .html file then open it a strange problem occured,i can't see the word "hello world" in panel,i can't find the word "hello word" in html source code except some tags of html,who can tell me what's wrong?thanks in advanced!

    hello user457523
    I have found the reason to that error.It's because there's a trigger and ext_src_file_nm is populated by the trigger from another column ext_src_file_loc when inserting and I didn't give any value to ext_src_file_loc so ext_src_file_nm is null.
    I have disabled that trigger and now I get new errors.When I traced to a line of Jave code I got missing source file warning,and the source file is also oracle.sql.CharacterSet.java.I can not trace into the source file and then I skipped that code and then I got new errors.I want to know how to trace into the jave code and find what's the matter.
    Thank you very much.

  • Insert HTML into HTMLDocument

    hello
    i' have a problem using JTextPane. I want to select some text, and add some HTML tags around. For example, "Jeremie" is written ... i select all the text, i press the button and i want
    that the HTML code generated is "<font class="toto">Jeremie</font>"
    please help
    jeremie

    Yeah.. but. Where do you want the source code to be displayed ? Do you have a source code pane or something like that, or you just want HTML attributes to be applied to you text ?
    Il give you some random examples of HTML manipulation.. but I don't clearly see what you want to do :
    //set the appropriate EditorKit for JTextPane by determining its content type
    JTextPane tpa = new JTextPane();
    tpa.setContentType("text/html");
    //get a reference to the tpaDefault document
    HTMLDocument htmDoc = (HTMLDocument) tpa.getDocument();
    //get a referene to HTMLEditorKit
    HTLMEditorKit htmKit = (HTMLEditorKit) tpa.getEditorKit();
    //Get selected text from JTextPane
    String strSelText = JTextPane.getSelectedText();
    //Get selection start and end positions
    int intStartPos = JTextPane.getSelectionStart();
    int intEndPos = JTextPane.getSelectionEnd();
    //Calculate selection length
    int intSelLength = intEndPos - intStartPos;
    //Remove selection from HTMLDocument
    htmDoc.remove(intStartPos, intSelLength);
    //HTML String to insert
    String strToInsert = "<font face="Verdana" size="3" color="red">" + strSelText + "</font>";
    //Insert new formated HTML content using HTMLEditorKit
    htmKit.insertHTML(htmDoc,strToInsert,intStartPos, 0,0, HTML.Tag.FONT);  That's more or less how it works.
    Hope it helps,
    Diego

  • Inserting Components into JTextPane

    I need to be able to insert and remove the same components several times over, while knowing precisely where they in the text pane.
    In Swing 1.3, I can get a maximum of 3 components inserted, before an ArrayIndexOutOfBoundsException is thrown. After they are removed, they cannot be reinserted.
    Swing 1.1 worked better. You could get quite a few components in and out before things fell in a heap. However, it never was much good at knowing precisely where the component was.
    Yasmin

    I need to be able to insert and remove the same components several times over, while knowing precisely where they in the text pane.
    In Swing 1.3, I can get a maximum of 3 components inserted, before an ArrayIndexOutOfBoundsException is thrown. After they are removed, they cannot be reinserted.
    Swing 1.1 worked better. You could get quite a few components in and out before things fell in a heap. However, it never was much good at knowing precisely where the component was.
    Yasmin

  • Insertion of icons into JTextPane

    Hello!
    I am trying to insert icons into JTextPane object, and I got a problem.
    My partial code is as follows...
    StyleConstants.setIcon(s, icnIcons);
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    In the above code, s is an object of Style, and icnIcons is an object of ImageIcon, and doc is an object of StyledDocument.
    And the style, s, is registered with a name, "icon".
    If I execute the above code, then only one icon is displayed. But the length of the text is increased by 2.(I check this using doc.getLength() method.)
    So, I make a little change to the above code like the following:
    StyleConstants.setIcon(s, icnIcons);
    doc.insertString(doc.getLength(), "I\n", doc.getStyle("icon")); //changed
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    I just add "\n". And the second code is working, and displays two icons.
    But the two icons are on the separate line.
    And if I use two different icons, that is, two different styles, in the first code segment, then it works and shows the two icons on the same line, though I didn't use the "\n".
    Why does this happen?
    I am so confused. Please help me.
    Thanks for every body!
    Regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.text.*;
    public class IconPane {
        private void showTest(BufferedImage[] images) throws IOException {
            JTextPane textPane = new JTextPane();
            // Add some content.
            File file = new File("IconPane.java");
            BufferedReader br = new BufferedReader(
                                new InputStreamReader(
                                new FileInputStream(file)));
            textPane.read(br, file);
            br.close();
            // Make up a couple of styles.
            int pos1 = 875, pos2 = 876;
            StyledDocument doc = textPane.getStyledDocument();
            Style style = textPane.addStyle("icon1", null);
            StyleConstants.setIcon(style, new ImageIcon(images[0]));
            // Set  icons.
            doc.setCharacterAttributes(pos1, 1, style, false);
            style = textPane.addStyle("icon2", null);
            StyleConstants.setIcon(style, new ImageIcon(images[1]));
            doc.setCharacterAttributes(pos2, 1, style, false);
            // Add the icons again with the insertString method.
            addContent(doc);
            // Show me.
            JScrollPane scrollPane = new JScrollPane(textPane);
            scrollPane.setPreferredSize(new Dimension(500,400));
            textPane.addMouseMotionListener(mouseInput);
            JOptionPane.showMessageDialog(null, scrollPane, "",
                                          JOptionPane.PLAIN_MESSAGE);
        private void addContent(StyledDocument doc) {
            int pos1 = 1667, pos2 = 1669;
            try {
                // Try inserting icons with insertString.
                doc.insertString(pos1, " ", doc.getStyle("icon1"));
                doc.insertString(pos2, " ", doc.getStyle("icon2"));
            } catch(BadLocationException e) {
                System.out.printf("bad location error: %s%n", e.getMessage());
        public static void main(String[] args) throws IOException {
            String[] ids = { "--g--", "---h-" };
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++)
                images[j] = ImageIO.read(new File("images/geek" + ids[j] + ".gif"));
            new IconPane().showTest(images);
        private MouseMotionAdapter mouseInput = new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int pos = ((JTextComponent)e.getSource()).viewToModel(e.getPoint());
                System.out.println(String.valueOf(pos));
    }

  • Inserted HTML does NOT push content when resized

    Hi,
    we are building a website for a hotel and are bound to include their channel manager module into the site. In order to do that, you have to follow these steps:
    1. Paste JavaScript code into the head section to load the module.
    2. Place a short line of code with "insert HTML" into the site where the module should appear and that's it.
    The module is generated by a server-side script from the channel manager's server and pasted into an iFrame that is also generated by this very script. The thing is: It resizes the height of the iFrame depending on the displayed content in the iFrame. So we start with 301 px height when we call the page and start the search for free rooms. The results are displayed on a 1400 px iFrame, which resizes properly when showing the results.
    THE PROBLEM: The footers stays put and the iFrame runs behind it and off the display port. There is also no scrollbar showing up allowing me to scroll to the bottom of the iFrame.
    We got three layers:
    3. Top Layer (Containing top navigation and footer, both defined in a master page that is applied to the content page)
    2. Content Layer (Containing the inserted HTML with the generated iFrame)
    1. Background Layer (Well, it contains background elements)
    WE NEED: The footer to be pushed by the ever resizing iFrame and get a scrollbar when neccessary due to iFrame height.
    What are we doing wrong?

    Thank you for your suggestions, although I don't think they will fix the problem.
    We cannot alter the server script in any way, since it is located on the channel manager's server and is just called with a customer id to show our client's hotel related data. They resize the iFrame using an inline height style tag. This causes the page to not recognize the size change and not even showing a scrollbar at all, when the iFrame exceeds the view port.
    We already put a div around the JS-call which expands with the iFrame as expected.
    <div id="u1218"><!-- custom html -->
    <div>
    <script language="javascript" type="text/javascript">
    function();
    </script>
    </div>
    </div>
    This results in an iFrame inserted after the script tag, the div around the script expands correctly. We already removed any master page objects, created a blank new master page to define header and footer areas and pasted our menu and footer directly into the page of question on the same layer as the inserted html box went. So for our understanding the expanding div around the script should push the footer on this page to whereever it ends. It just doesn't. Also we do not get any scrollbar, although the iFrame clearly gets larger than the viewport area and the page just doesn't recognize it.

  • Ability to insert HTML code snippets not available

    Supposedly I can insert HTML into a file in Contribute but
    that option is grayed-out and can't be used. Does anyone know why
    that capability would not be functioning. I have the most recent
    version of Contribute and use it on a PC

    In the main menu go to:
    1. Edit, Administer Websites
    2. Users and Roles, click Edit Role Settings
    3. go to Editing
    4. check 'Allow HTML snippets insertion...' (last option)

Maybe you are looking for