Inserting components to JTextPane

Hi,
I need to insert components to JTextPane. I know JTextPane provides a method insertComponent() for this purpose.
But this does not work when you set the content type to "text/html".
For example if I do the following:
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");and then try to insert a component it does not work.
My question is, can I insert a JLabel/JButton to JTextPane once I set the content type to "text/html"?

My question is, can I insert a JLabel/JButton to JTextPane once I set
the content type to "text/html"? You don't really know what you did, do you?
No, you can not add other widgets into a JTextPane since it's not a container. That is completely irrelevant from the fact that you can specify a MIME type for what's written inside the text pane.

Similar Messages

  • 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

  • Inserting Component in JTextPane

    hai
    I have a problem while inserting components in JTextPane
    i first inserted text using insertString() function and then a JLabel using
    insertComponent() function but the Label is appearing before the text.
    This is the case with any of the component that is being added
    The components are being added before the text
    can someone tell me a solution by which the components appear in the order they
    were added
    Thanking you in anticipation

    u r inserting the component at the 0 caret position, so as ur need set the caret position where u want to insert the component like..
    textPane.setText("Hello");
    textPane.setCaretPosition(5);
    textPane.insertComponent(new JLabel("World"));

  • Can you get ordered list of inserted Components from a JTextPane?

    Hello,
    Does anyone know of a way to get the collection of Components that have been inserted into a JTextPane? Further, assuming you can get such a collection, how do you know how they're positioned/ordered in the text?
    Thanks for any help,
    -Michael

    Hello Paul, that's true but I see some weird things happpening in my case. I know for sure my project related objects are moved to prod because I ran the processes in PROD but when I look at the source database the upgradeaction is set as 2, which mean 'none' and says copydone as 0 which implies it is not moved, which is in correct because I can see those in PROD when I open in app designer. So in this case I am missing some information in the report because of the filters UPGRADEACTION in (0,3) and COPYDONE = 1. Is there any other way other than this to get the list of migrated projects from source to target database.
    Thanks,

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

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

  • Insert String to JTextPane as hyperlink

    Hi,
    I have a JTabbedPane with 2 tabs, on each tab is one panel.
    On first pannel I add JTextPane and I would like to insert in this JTextPane some hyperlinks.
    I found some examples in forum, but doesn't work for me.
    Could somebody help me ?
    Thank's.
    Here is my code :
    JTextPane textPane = new JTextPane();
    textPane.setPreferredSize(new Dimension(500,300));
    HTMLEditorKit m_kit = new HTMLEditorKit();
    textPane.setEditorKit(m_kit);
    StyledDocument m_doc = textPane.getStyledDocument();
    textPane.setEditable(false); // only then hyperlinks will work
    panel1.add( textPane,BorderLayout.CENTER); //add textPane to panel of
    //JTabbedPane
    String s = new String("http://google.com");
    SimpleAttributeSet attr2 = new SimpleAttributeSet();
    attr2.addAttribute(StyleConstants.NameAttribute, HTML.Tag.A);
    attr2.addAttribute(HTML.Attribute.HREF, s);
    try{
    m_doc.insertString(m_doc.getLength(), s, attr2);
    }catch(Exception excp){};
    The String s is displayed like text not like hyperlink..

    Hi , You can take a look at this code , this code inserts a string into a StyledDocument in a JTextPane as a hyperlink and on clicking fires the URL on the browser.
    /* Demonstrating creation of a hyperlink inside a StyledDocument in a JTextPane */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.Border;
    import javax.swing.text.*;
    public class Hyperlink extends JFrame {
        private Container container = getContentPane();
        private int toolXPosition;
        private int toolYPosition;
        private JPanel headingPanel = new JPanel();
        private JPanel closingPanel = new JPanel();
        private final static String LINK_ATTRIBUTE = "linkact";
        private JTextPane textPane;
        private StyledDocument doc;
        Hyperlink() {
              try {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
                   setSize(300, 200);
                   Rectangle containerDimension = getBounds();
                   toolXPosition = (screenDimension.width - containerDimension.width) / 10;
                            toolYPosition = (screenDimension.height - containerDimension.height) / 15;
                            setTitle("HYPERLINK TESTER");
                         setLocation(toolXPosition, toolYPosition);
                         container.add(BorderLayout.NORTH, headingPanel);
                         container.add(BorderLayout.SOUTH, closingPanel);
                   JScrollPane scrollableTextPane;
                   textPane = new JTextPane();
                   //for detecting clicks
                   textPane.addMouseListener(new TextClickListener());
                   //for detecting motion
                   textPane.addMouseMotionListener(new TextMotionListener());
                   textPane.setEditable(false);
                   scrollableTextPane = new JScrollPane(textPane);
                   container.add(BorderLayout.CENTER, scrollableTextPane);
                   container.setVisible(true);
                   textPane.setText("");
                   doc = textPane.getStyledDocument();
                   Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                   String url = "http://www.google.com";
                   //create the style for the hyperlink
                   Style regularBlue = doc.addStyle("regularBlue", def);
                   StyleConstants.setForeground(regularBlue, Color.BLUE);
                   StyleConstants.setUnderline(regularBlue,true);
                   regularBlue.addAttribute(LINK_ATTRIBUTE,new URLLinkAction(url));
                   Style bold = doc.addStyle("bold", def);
                   StyleConstants.setBold(bold, true);
                   StyleConstants.setForeground(bold, Color.GRAY);
                   doc.insertString(doc.getLength(), "\nStarting HyperLink Creation in a document\n\n", bold);
                   doc.insertString(doc.getLength(), "\n",bold);
                   doc.insertString(doc.getLength(),url,regularBlue);
                   doc.insertString(doc.getLength(), "\n\n\n", bold);
                   textPane.setCaretPosition(0);
              catch (Exception e) {
         public static void main(String[] args) {
              Hyperlink hp = new Hyperlink();
              hp.setVisible(true);
         private class TextClickListener extends MouseAdapter {
                 public void mouseClicked( MouseEvent e ) {
                  try{
                      Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
                       AttributeSet as = elem.getAttributes();
                       URLLinkAction fla = (URLLinkAction)as.getAttribute(LINK_ATTRIBUTE);
                      if(fla != null)
                           fla.execute();
                  catch(Exception x) {
                       x.printStackTrace();
         private class TextMotionListener extends MouseInputAdapter {
              public void mouseMoved(MouseEvent e) {
                   Element elem = doc.getCharacterElement( textPane.viewToModel(e.getPoint()));
                   AttributeSet as = elem.getAttributes();
                   if(StyleConstants.isUnderline(as))
                        textPane.setCursor(new Cursor(Cursor.HAND_CURSOR));
                   else
                        textPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         private class URLLinkAction extends AbstractAction{
              private String url;
              URLLinkAction(String bac)
                   url=bac;
                 protected void execute() {
                          try {
                               String osName = System.getProperty("os.name").toLowerCase();
                              Runtime rt = Runtime.getRuntime();
                        if (osName.indexOf( "win" ) >= 0) {
                                   rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
                                    else if (osName.indexOf("mac") >= 0) {
                                      rt.exec( "open " + url);
                              else if (osName.indexOf("ix") >=0 || osName.indexOf("ux") >=0 || osName.indexOf("sun") >=0) {
                                   String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                                     "netscape","opera","links","lynx"};
                                   // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
                                   StringBuffer cmd = new StringBuffer();
                                   for (int i = 0 ; i < browsers.length ; i++)
                                        cmd.append((i == 0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
                                   rt.exec(new String[] { "sh", "-c", cmd.toString() });
                   catch (Exception ex)
                        ex.printStackTrace();
                 public void actionPerformed(ActionEvent e){
                         execute();
    }Here , what I have done is associated a mouseListener and a mouseMotionListener with the JTextPane and I have created the hyperlink look with a Style of blue color and underline and have added the LINK_ATTRIBUTE to that Style which takes care of listening to mouse clicks and mouse motion.
    The browser can be started in windows using the default FileProtocolHandler using rundll32 and in Unix/Sun we have to take a wild guess at which browser could be installed , the first browser encountered is started , in Mac open command takes care of starting the browser.
    Hope this is useful.

  • 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

  • Components in JTextPane Won't Print

    When printing the contents of a JTextPane, all the text shows up in the correct font and location. However, any components that are embedded in he document are not rendered. Their are blocks of whitespace where the component should have been, however.
    I've tried all manner of tricks like hiding the JTextPane, reloading the JTextPane but not showing it, etc. Nothing seems to work.
    I'm using a stock DefaultStyledDocument for the model.
    I'm bound in that I cannot use a 3rd party solution to fix this. ( don't ask :) ).
    Anyone solved this problem?
    Thanks,
    Brian

    That's the code I"m using now. I didn't work with components, but I was able to tweak it and get it working.
    What I did was check the Element for each View. If the Element was a component, I created a new Graphics instance from the "base" instance, and paint()-ed the component on that. For example:
    Element element = view.getElement();
    if ( element.getName().equals("component") ) {
    Component c = StyleConstants.getComponent(element.getAttributes());
    Graphics g2 = graphics2D.create((int)allocation.getBounds().getX(),
    (int)allocation.getBounds().getY(),
    (int)allocation.getBounds().getWidth(),
    (int)allocation.getBounds().getHeight());
    c.paintAll(g2);
    } else {
    view.paint(graphics2D, allocation);
    That seems to have done the trick. Mabye there is a better/faster/cheaper way to do this ( via coordinate translation? ), but this seems to work in the cases I care about ( images, checkboxes, tables ).
    Thanks for your suggestions!
    Brian

  • Inserting Icons in JTextPane with setEditable=false

    Aloha!
    I'm working on this for years now, but i haven't found an acceptable solution yet.
    The problem: I have a JTextPane, where the user shall not be able to edit anything by clicking onto the JTextPane. So I have to setEditable=false. Now I want to insert an icon with insertIcon and therefore i have to setEditable = true. But for short time it's now possible for the user to click onto the screen and change the caretPosition, which must be prevented at all costs (because I'm working with the expected caretPosition of course)! This only happens when I try the brute force testing method, but it happens sometimes...
    So can someone give me a better solution than:
    setEditable = true;
    insertIcon(blahblah);
    setEditable = false;
    Thanks a lot for your attention,
    Holm

    To use HTML, you must use javax.swing.text.html.HTMLDocument instead of StyledDocument,
    Instead of StyleConstants, you must use javax.swing.text.html.HTML$Tag and javax.swing.text.html.HTML$Attribute.
    And you can use an HTMLEditorKit instead of DefaultEditorKit.
    this is an example of initialization:
    javax.swing.text.html.HTMLEditorKit htmlEditorKit = new javax.swing.text.html.HTMLEditorKit();
    javax.swing.text.html.HTMLDocument htmlDoc = (javax.swing.text.html.HTMLDocument)htmlEditorKit.createDefaultDocument();
    yourJTextPane.setEditorKit(htmlEditorKit);
    yourJTextPane.setDocument(htmlDoc);
    yourJTextPane.setEditable(true);
    yourJTextPane.setContentType("text/html");and you can use it by yourJTextPane.setText(HtmlCodeString)
    HTMLDocument and HTMLEditorKit allow you main modifications.
    thanks for duke dollars :)

  • Make an inserted component in JTextPane not deletable ?

    Hi all,
    I insert some buttons in my JTextPane and of course I have to make them not eraseable, it is said that when they are inserted, they cannot be deleted by pressing the delete key. How can I do this ? Can I set some portion in a JTextPane not editable and another portion editable ?
    Thanks

    You have to extend document and override remove(int offset, int length) method. In the method just check whether specified (by offset and length) part of the document contains component. If not call super.remove() in other cases just return.
    regards
    Stas

  • Getting inserted icons from JTextPane

    I have inserted some text including icons in JTextPane. Now i want to copy all contents as such in second Jtextpane. Plz help me

    http://liquidaurum.imgur.com/all/
    This is what's happening, and same thing for terminal

  • 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

  • Insert ComboBox in JTextPane

    hi,
    how can i insert a HTML Combobox in a JTextPane ?
    thx.

    Use JEditorPane and load a HTML page containing a combobox ..
    - bjorn

  • 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.

Maybe you are looking for

  • Availability of new J2EE 1.4 SDK

    I am pleased to announce availability of new J2EE 1.4 SDK. You can download this today from http://java.sun.com/j2ee/1.4/download.html J2EE SDK now includes App Server Platform Edition 8.2 (SJSAS PE 8.2) delivering a rich application deployment envir

  • Virtual Machine crashing all the time: The previous system shutdown at a certain date was unexpected

    Hello, I've a build node that is constantly crashing and rebooting.  When I go to system event log I'm not able to identify the reasons for such behavior. For instance regarding the machine latest crash I can see: The previous system shutdown at 10:2

  • Iphone will not sync pics to Adobe Photoshop Album 3.0

    When i connect my Iphone to my PC, Photoshop album detects it as a digital camera and opens up. It even brings up thumbnails of all the pictures on my Iphone. But when i click on "GET PHOTOS" to download the pictures to my computer, the process start

  • Itunes not opening properly

    for the past 2 months whenever i open my iTunes it opens, however not properly. I am able to see all of my songs in my library but the actual menu does not appear. I have tried reinstalling itunes multiple times as well as reinstalling quicktime. I h

  • XML repot out put printing

    hi all i have developed a xml report and it prints out put down wise but i want to print the data across for example column1 -- row 1-row2--- column2 -- row 1--row2-- thanks for all in advance, maddy