JEditorPane & HTML img rendering

Hi folks,
I was trying to render some HTML with images in it, trying to get the text to flow around the image but so far it has not worked. The HTML in question is not at all complicated, it is a simple <img align='left' .... > followed by text. Unfortunately, it seems like the component is ignoring the align attribute.
Anyone has any ideas on how to correct this, or wether I'm simply doing something wrong?
To try to clarify my problem:
This is how it should be displayed:
Line of text 1
|         | Line of text 2
|  Image  | Line of text 3
|_________| Line of text 4
Line of text 5...and this is how it renders it:
Line of text1
|         |
|  Image  |
|_________| Line of text 2
Line of text 3
Line of text 4
Line of text 5I'd appreciate any help.

Try this example.
regards,
Stas
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.FlowView.*;
public class Test extends JFrame{
    JEditorPane pane=new JEditorPane();
    public Test() throws Exception{
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().add(new JScrollPane(pane));
        pane.setEditorKit(new MyEditorKit());
        MutableAttributeSet attrs=new SimpleAttributeSet();
        pane.getDocument().insertString(0,"Align left flow test flow test flow test flow test flow test flow test flow test flow test flow test flow test\n",null);
        attrs=new SimpleAttributeSet();
        ImageIcon img=new ImageIcon("c:/test.jpg");
        StyleConstants.setIcon(attrs,img);
        pane.getDocument().insertString(0," ",attrs);
pane.getDocument().insertString(0,"\n\n",null);
        pane.getDocument().insertString(0,"Align right flow test flow test flow test flow test flow test flow test flow test flow test flow test flow test\n",null);
        attrs=new SimpleAttributeSet();
        StyleConstants.setIcon(attrs,img);
        StyleConstants.setAlignment(attrs,StyleConstants.ALIGN_RIGHT);
        pane.getDocument().insertString(0," ",attrs);
    public static void main(String args[]) throws Exception {
        Test gI = new Test();
        gI.setSize(300, 300);
        gI.setLocationRelativeTo(null);
        gI.setVisible(true);
class MyEditorKit extends StyledEditorKit {
    ViewFactory defaultFactory=new StyledViewFactory();;
    public ViewFactory getViewFactory() {
        return defaultFactory;
    static class StyledViewFactory implements ViewFactory {
        public View create(Element elem) {
            String kind = elem.getName();
            if (kind != null) {
                if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
                } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                    return new MyParagraphView(elem);
                } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    return new BoxView(elem, View.Y_AXIS);
                } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
                } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
            // default to text display
            return new LabelView(elem);
class MyParagraphView extends ParagraphView {
    ImageIcon icon=null;
    int iconWidth=0;
    int restHeight=0;
    int imgAlign=StyleConstants.ALIGN_LEFT;
    public MyParagraphView(Element elem) {
        super(elem);
        strategy = new MyFlowStrategy();
    public void paint(Graphics g, Shape a) {
        super.paint(g,a);
        if (icon!=null) {
            Rectangle rect = a.getBounds();
            rect.width -= iconWidth;
            int x = rect.x;
            if (imgAlign == StyleConstants.ALIGN_RIGHT) {
                x += rect.width;
            g.drawImage(icon.getImage(), x, rect.y, null);
    protected void layout(int width, int height) {
        super.layout(width,height);
    public int getFlowSpan(int index) {
        int span= super.getFlowSpan(index);
        if (restHeight>0) {
            span-=iconWidth;
        return span;
    public int getFlowStart(int index) {
        int span=  super.getFlowStart(index);
        if (restHeight>0) {
            span+=iconWidth;
        return span;
    protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
        super.layoutMinorAxis(targetSpan,axis,offsets,spans);
        if (imgAlign==StyleConstants.ALIGN_LEFT && icon!=null) {
            restHeight=icon.getIconHeight();
            int i=0;
            while (restHeight>0 && i<offsets.length) {
                offsets[i]+=iconWidth;
                i++;
                View row=this.getView(i);
                if (row!=null) {
                    restHeight -= row.getPreferredSpan(View.Y_AXIS);
    public class MyFlowStrategy extends FlowStrategy {
        protected View createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) {
            View v=super.createView(fv,startOffset,spanLeft,rowIndex);
            while (v instanceof IconView) {
                v=super.createView(fv,startOffset+1,spanLeft,rowIndex);
            return v;
        protected int layoutRow(FlowView fv, int rowIndex, int pos) {
            if (rowIndex==0) {
                int count=getElement().getElementCount();
                for (int i=0; i<count; i++) {
                    Element el=getElement().getElement(i);
                    Icon ic=StyleConstants.getIcon(el.getAttributes());
                    if (ic!=null) {
                        icon=(ImageIcon)ic;
                        iconWidth=ic.getIconWidth();
                        restHeight=ic.getIconHeight();
                        imgAlign=StyleConstants.getAlignment(el.getAttributes());
            int res=super.layoutRow(fv,rowIndex,pos);
            View row=fv.getView(rowIndex);
            restHeight-=row.getPreferredSpan(View.Y_AXIS);
            return res;
}

Similar Messages

  • JEditorPane/HTML image loading delay

    I am using a JEditorPane to render HTML to a graphics buffer which I then write as an image file. Since HTML loading is asynchronous I wait for the "page" property change event after calling setPage() before using print() to capture the rendered HTML to a graphics buffer. Unfortunately, the "page" property change event is fired after the HTML is loaded but before images referenced by the HTML are rendered. As a result, the image that I capture has little picture icons in place of the graphics. If I sleep for a short time before capturing the image, it works fine. However, sleeping is not an acceptable solution as there is no way to predict how long I will need to sleep because it varies based on system load and complexity of the HTML being rendered. Is there any way to check if an HTML document has completely loaded including all the images? Does anyone have a better way to capture an image of a rendered HTML document that would not have this problem?
    Below is a code snippet that shows what I am trying to do.
    static final JEditorPane p;
    static final Object done;
    static {
        done=new Object();
        p=new JEditorPane();
        p.setSize(1728, 2156);
        p.addPropertyChangeListener("page", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) {
            synchronized(done) {
                done.notifyAll();
    static void capture(File htmlFile) {
        BufferedImage img=new BufferedImage(1728, 2156, BufferedImage.TYPE_BYTE_GRAY);
        synchronized(done) {
            p.setPage(htmlFile.toURL());
            try {
                done.wait();
            } catch(InterruptedException e) {}
    /* without this code images are not rendered
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {}
        Graphics g=img.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, 1728, 2156);
        p.print(g);

    HI Sarnoth,
    I'm trying to do something similar and have used your code, but it doesn't work completely for me. Do you see anything that I'm doing wrong? I am trying to save the HTML page as a JPEG image. This is my code and I'm having problems. Anyone have any ideas? It is dying on the je.encode(bi) line. Also, for some reason, if I uncomment the commented out lines, it hangs. Any ideas on that one too?
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import javax.swing.JEditorPane;
    import com.sun.media.jai.codec.ImageCodec;
    import com.sun.media.jai.codec.ImageEncoder;
    import com.sun.media.jai.codec.JPEGEncodeParam;
    public class HTMLPageToImageConverter
         private HTMLPageToImageConverter() {
         static final JEditorPane p;
         static final Object done;
         static {
             done = new Object();
             p = new JEditorPane();
             p.setSize(1728, 2152);
    /*         p.addPropertyChangeListener("page", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) {
                 synchronized(done) {
                     done.notifyAll();
         static void GenerateHTMLBufferedImage(File htmlFile, BufferedImage img) {
             img = new BufferedImage(1728, 2152, BufferedImage.TYPE_BYTE_GRAY);
             synchronized(done) {
                 try {
                      p.setPage(htmlFile.toURL());
                 } catch(IOException e1) {}
    /*             try {
                     done.wait();
                 } catch(InterruptedException e) { System.out.println("GenerateHTMLBufferedImage InterruptedException"); }
             Graphics g = img.createGraphics();
             g.setColor(Color.white);
             g.fillRect(0, 0, 1728, 2152);
             p.print(g);
         public static boolean SaveHTMLFileToJPEG(String htmlFile, String jpegFile) {
              try {
                   BufferedImage bi = null;
                   GenerateHTMLBufferedImage(new File(htmlFile), bi);
                   FileOutputStream fos = new FileOutputStream(jpegFile);
                   JPEGEncodeParam jp = new JPEGEncodeParam();
                   ImageEncoder je = ImageCodec.createImageEncoder("JPEG", fos, jp);
                   je.encode(bi);
                   fos.close();
              } catch(FileNotFoundException fnfe) { System.out.println("SaveHTMLFileToJPEG FileNotFoundException"); }
                catch(IOException ioe) { System.out.println("SaveHTMLFileToJPEG IOException"); }
              return true;
    }Called from other code
    HTMLPageToImageConverter.SaveHTMLFileToJPEG("d:/page1.html", "d:/page1.jpeg");
    ...Thanks in advence,
    --Ed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Bug: JDev 9052 Build (1618) html:img ... /

    The XSS <style selector=...> is not honored in conjunction with the <html:img> tag.
    1. Create an xss style:
    <style selector=".handIconGroup">
    <property name="cursor">hand</property>
    <includeStyle name="DarkAccentBackground"/>
    </style>
    2. Create a UIX page and add the following widgets:
    a. <html:img style="handIconGroup" ... />
    b. <textInput sytle=handIconGroup" ... />
    4. Run the page, and hover over both widgets.
    I expected the cursor to turn into a "hand" when hovered over both widgets. The <html:img ... /> tag dose not respect the handIconGroup style.

    Typo:
    <textInput sytle="handIconGroup" ... />
    should read
    <textInput styleClass="handIconGroup" ... />

  • Content Server pcs:html:img tag

    I am attempting to create custom news article presentation & data entry templates. The data entry template includes a text field where the user would specify the filename of an image that will be included in the presentation of the news article. I am having trouble with syntax for the filename property in the presentation image. I found an example the looks like this
    <pcs:html:img expr:src="itemByPath('images/logo.gif').location" attr:border="0" attr:align="absmiddle" style="UNARY" ></pcs:html:img>
    This works great, however I need to use the filename property something like this
    <pcs:html:img expr:src="itemByPath('images/<pcs:value expr="imageName"></pcs:value>').location" attr:border="0" attr:align="absmiddle" style="UNARY" ></pcs:html:img>
    Any suggestion on how to do this is greatly appreciated!

    Hi!
    I get the same error. I think it is a class loading problem. I noticed that both pdkjava.jar and pdkstruts.jar contains the class oracle.webdb.provider.v2.struts.StrutsUtils, but only pdkstruts.jar implements the method isPortalRequest(). The classloader has obviously loaded the other version of the class already.
    Both jar files is in the WEB-INF\lib directory of my war file. Has anyone else found a solution to this problem?

  • Invalid HTML Collection Renderer

    Hi experts,
    I've been trying to implement a HTML Collection Renderer by following the How to configure the HTML Collection Renderer for the KM flexible user interface EP 6.0 SP2. Our system is currently NetWeaver 7.0 SP15.
    The HTML code is copied exactly from the how to document. However, no matter what I tried, I cannot get the HTML to display correctly and Rendering Information (I have enabled debugging setting) in preview iView complains that the layout set assigned (which is based on the HTML Collection Renderer) is invalid and always uses default layoutset instead. Below is the error text:
    Global Information based on Resource </documents/Public Documents/KM Documentation>
    Folder Settings Resource:  /documents/Public Documents/KM Documentation
    Invalid LayoutSet from iView/ URL Parameter:  HTMLandList
    LayoutMode:  force
    Used LayoutSet fromDefaults:  ConsumerExplorer
    In the HTML Collection Renderer, I have the following value as HTML Filename:
    /documents/Public Documents/HTML and List/KMdocinfo.html.
    I also tried specifying complete path from the html file as Portal Favorites link. This relates to another question I also have: Should I try to preview the html file this way? Because I also cannot get image rendered correctly with the internal system URL http://com.sap.cm/, unless I changed it to our portal host name. But from what I read, that seems a fixed syntax that I don't need to worry about.
    Any help would be greatly appreciated.
    Thanks
    Hsiao

    Thanks Darin,
    I have tried your suggestion however with no luck.
    I have a layout controller that allows a grid on top and a tree list below.  The Grid successfully displays the HTML collection renderer, and the tree-list behaves correctly.
    However, if I place a mass command in the HTML collection renderer using the suggested syntax, it does not seem to recognize the command.  I have tried several commands such as copy_admin_mass and move_admin_mass and the link opens an invalid page with the url of http://com.sap.cm/?uicommand=copy_admin_mass
    Any thoughts?

  • Puting into JEditorPane HTML file

    I want to put into JEditorPane HTML file from my local drive.
    How to do that?

    Hear is example try it.
    *(c)pesilEX - 2007
    * [email protected]
    * Let�s make a open source software world
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.URL;
    public class pesilEX extends JFrame implements ActionListener{
    JPanel cp;
    // Declaring a url to get file name
    // Also this can use to get url form online
    public URL helpURL;
    JScrollPane scrol;
    JEditorPane htmlPane;
    JButton btn1;
    // This string is use to store file name
    String fileName;
    public pesilEX(){
         cp = (JPanel)getContentPane();
         cp.setLayout(null);
    htmlPane = new JEditorPane();
    htmlPane.setEditable(false);
    scrol = new JScrollPane();
    scrol.getViewport().add(htmlPane);
    scrol.setBounds(10,10,370,300);
    cp.add(scrol);
    btn1 = new JButton("View!");
    btn1.setBounds(260,320,120,20);
    cp.add(btn1);
    btn1.addActionListener(this);
    public void actionPerformed(ActionEvent e){
         if(e.getSource()==btn1){
         // File name you can replace is as you want
    fileName = "pesilEX/help.htm";
    // Import html file to java
         helpURL = getClass().getClassLoader().getResource(fileName);
    try{
    // Set url to JEditorPane
         htmlPane.setPage(helpURL);
    catch(Exception er){
         System.out.println(er.toString());
    public static void main(String[] args){
    pesilEX pesil = new pesilEX();
              pesil.setSize(400,400);
              pesil.setTitle("pesilEX JHtml viewer");
              pesil.setResizable(false);
              pesil.setVisible(true);
    }

  • How to set value for html:img

    i am using <html:img tag to render image and i need to set some value to that image when selected and that value need to be checked in java code.
    How i can set the value for that image.
    Thanks,

    use javascript and hidden input to do this:
    <html:img src="your_img.gif"     ononclick="document.getElementById('your_hidden_input_id').value='your_value' ">
    <input type="hidden" name="your_hidden_input_name" id = "your_hidden_input_id" value="" />Hope that Helps

  • Use of Html Collection Renderer - Bulletin Board

    Hello,
    I wanted to create a Bulletin Board as in the document "How to create a bulletin Board". But when using the navigation iViews with the Html collection renderer. It allways opens a new browser. Isn't it possible to see the next navigation step in the same window?
    Is there anybody who tried to make the bulletin Board as in the document?
    Can anybody help me with finishing mine.
    Thanks

    Thanks Darin,
    I have tried your suggestion however with no luck.
    I have a layout controller that allows a grid on top and a tree list below.  The Grid successfully displays the HTML collection renderer, and the tree-list behaves correctly.
    However, if I place a mass command in the HTML collection renderer using the suggested syntax, it does not seem to recognize the command.  I have tried several commands such as copy_admin_mass and move_admin_mass and the link opens an invalid page with the url of http://com.sap.cm/?uicommand=copy_admin_mass
    Any thoughts?

  • How do I keep html from rendering in to a link, I need it to show

    Hi All,
    How do I keep html from rendering into a link, I need the html code to show in a comment box so others can copy and paste it in other comments on a photo sharing site.
    The code rightful renders into a link and the html no longer shows how do I stop
    it from rendering?
    I would really appreciate any help! Thank you for your time.
    Cheers,
    Maria /eMe

    Hi Eme
    I don't know for sure w/o trying the site, but I guess you mean that a href ="some-site.com" type things are rendering as links, rather than text people can read? same as these forums I spose.
    first, try replacing the opening < with &#60; and the closing > with &#62; for both the initial <a> and the closing </a>
    hopefully...that'll allow the code to be visible, tho' you may find the site still converts the url to a clickable link.

  • JEditorPane html

    I have a simple JEditorPane set up so that I can view source code and rendered version of an html page. I toggle between rendered and source view by setting the content type:
    setContentType("text/plain") - displays source code
    setContentType("text/html") - dispalys the rendered view
    The problem I have is with offsets. It would be natural to me that the first letter in the rendered view starts at 0 and ends at 1. That's not the case however. In any test page I have, the first letter has offset 3-4. The same things happen inside the text as well. When I count offsets by hand, they are different that what getSelectionStart() and getSelectionEnd() show.
    I'm assuming that there must be some characters that get rendered by JEditorPane but don't get displayed - but quite frankly I have no clue as to why it's happening.
    Any ideas would be appreciated. I wrote a simple algorithm (irrelevant to this post) that uses the rendred view offsets to mark things in the source view, but since my rendered view offsets are screwed up - I'm not able to mark things properly.
    Thanks
    M

    Have you tried displaying the characters between offsets 0-2 ? It could give you an idea of what it concerns...

  • JEditorPane HTML load GIF from JAR

    I'm using a jeditorpane to display a html page from a local file system with images in it, will the editor pane load the <img src> tags from a jar file or must the images be on the local file system?

    gifs will have to be on the local drive

  • JEditorPane, html, tables and images

    I am trying to use jEditorPane to display an HTML document. If images are included into cells of a table, the width and height of the cells do not adjust to the size of the images (as it happens with common web browsers), no matter what parameters I use for TD and IMG tags.
    Do you experience the same problem? Is there a solution?
    Thanks.
    Ruben Razquin

    Hi Ruben,
    you will have to implement adjustment of table cells yourself to achieve this. With the existing way JEditorPane et. al. render tables table cells always are sized either in default sizes or by attributes explicitly giving the size (such as attribute WIDTH).
    Ulrich

  • JEditorPane & HTML button tag

    Hi,
    I have a program the renders some HTML pages inside JEditorPanes. Everything seems to be rendered correctly, with the exception of the <button> tags. Buttons are not displayed, but in there place is an odd text field with the word "button" in it, surrounded by something of an arrow.
    Has anyone seen this? A work around? I tried using the <input> of type button, but that just didn't display. Thank you.

    You are correct. In terms of buttons, HTML 3.2 only supported type=submit, not type=button. I changed my code to this older(tho also still implemented in 4.0) format. Seems to work now, thanks a lot!
    Unfortunately though, the type=submit does not have the attribute "disabled" which is what I needed to do.
    Edited by: cpollock on Jan 6, 2009 9:05 AM

  • Japanese characters in JEditorPane HTML

    We have an application that displays HTML in a JEditorPane to take advantage of the font changes. The string starts off with <html><body><font face='Dialog' size='-1'><b>One of our translation testers is complaining that some of the Japanese characters look "jaggy" (I think because they look like italics to me). However, most of the Japanese characters in the same field look fine (albiet bold). At no point in the string to I switch to italic, in fact everything in this case is bold.
    We don't seem to have this problem anywhere else in our UI with traditional JLabels, JOptionPanes, etc. Is there something querky about JEditorPane and/or HTML rendering, the mapping of the Dialog font, or something? Any suggestions on anything else to check.

    Hi David, yes 'Content-type: text/html; charset=utf-8' is in
    the header...
    Thanks for the note on the poor Japanese translations,
    someone else is
    proofing it now.
    J
    "David Powers" <[email protected]> wrote in message
    news:epvh06$dq6$[email protected]..
    > James Noon wrote:
    > > My web app sends confirmation emails to customers
    in multiple languages,
    all
    > > work fine apart from Japanese which display all as
    ? on the email.
    > >
    > > Part of of my email code is formatted as this (ie
    sending as utf-8)
    >
    > What is the Content-type header of the email?
    >
    > It needs to be 'Content-type: text/html; charset=utf-8'.
    >
    > This needs to be sent as an email header, not just in
    the body of the
    HTML.
    >
    > --
    > David Powers, Adobe Community Expert
    > Author, "Foundation PHP for Dreamweaver 8" (friends of
    ED)
    > Author, "PHP Solutions" (friends of ED)
    >
    http://foundationphp.com/

  • JEditorPane HTML link in the same page

    Hi,
    I want to show an HTML page in JEditorPane.
    The HTML page have <a> tags that link to a bookmark in
    the same page, but I can�t show this because I get an error
    like this:
    MalformedURL or similiar.
    I try to do somethig like this:
    public void hyperlinkUpdate(HyperlinkEvent ev)
    ...Editor.setPage(ev.getURL());
    or
    ...Editor.setPage(ev.getDescription());
    without results.
    How can I listen for hyperlinksEvents than link in the same page.
    Thanks

    they dont want to see the first report.
    Is there a way in which the Prompts are also display along with the second report?Then create the same prompt on the second report also.
    Cheers
    Nawneet

Maybe you are looking for

  • Some questions regarding SSLSocket

    Hi, I'm trying to write application (3 servers and 1 client) that will be using ssl. I've got a question - is one keystore enough for 3 server and 1 client and will it provied secure conncetions for all (for example server1<->server2, server3<->clien

  • 2.2 GPIB driver for Solaris doesn't work with Sol. 2.3 tester

    Upgraded to 2.2 GPIB driver to fix issue of driver being lost on Sun Ultra60's at shutdown and reboot. The driver works fine with 10 of the 11 tester platforms we use. This tester is a Genesis III running Solaris 2.3. The program will run successfull

  • How do I upgrade Safari?  I have Snow Leopord with Safari 5.1.10 now

    How do I upgrade Safari?  I have Snow Leopord with Safari 5.1.10 now. Thanks

  • UCS integration with vSphere - invalid URI error

    Hi, I am struggling to integrate UCS Manager with vSphere vCenter. The vCenter extension is being exported from UCSM without any errors, but when trying to install the plugin via vCenter Plug-in Manager I am getting this error: "Invalid URI: The URI

  • Adware/Malware Problem

    I am not 100% sure how I actually got this issue but its really bothering me. I have some adware on my mac that is causing random text in any browser I use to turn into spam links and ads. I have tried to use the methods posted on thesafemac.com but