Html in JEditorPane

Hello again! I am in the following situation. I have succeeded in loading an HTML document in a JEditorPane component. My question is can I recognize somehow if a click is performed on an image of the html document or on the text of the html document? If there is a possibility I would very much appreciate if you'd share it.
Thank you.

JTextComponent.viewToModel
then get the element at that location, either the character or
paragraph element, then get its StyleContext.NameAttribute value, which is a HTML.Tag.
That was a fun walk round the API, to find out more, I recomend reading through JTextComponent, and its Model/View Split section.
The the Element and View interfaces.

Similar Messages

  • Problem to display Animated Gif from HTML into JEditorPane

    I have a problem displaying animated gif that comes from URL (HTML) into JEditorPane.
    Let me show you the source I have:
    * @author Dobromir Gospodinov
    * @version 1.0
    * Date: Dec 6, 2002
    * Time: 6:47:53 PM
    package test.advertserver;
    import javax.swing.*;
    import java.awt.*;
    import java.io.IOException;
    public class Test {
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JEditorPane ed = new JEditorPane();
              try {
                   ed.setPage("http://localhost:8200/servlet?key=value");
              } catch (IOException e) {
                   e.printStackTrace();
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(500, 500));
              panel.add(ed);
              frame.getContentPane().add(panel);
              frame.pack();
              frame.setVisible(true);
    }Part of the returned from servlet HTML includes an img tag:
    <img src="/images/MyAnimatedGif.gif" alt="animated gif comment" width="480" height="50"  border="0">Let us assume that MyAnimatedGif.gif has 10 frames and gif is looped - when the 10th is dipslayed it has to display the 1st and so on.
    JEditorPane displays frames from 1 to 10 correctly but does not start from the first again. Instead JEditorPane displays a broken image.
    I locate where the problem arise:
    JEditorPane has an HTMLEditorKit that creates javax.swing.text.html.ImageView instance for every IMG tag.
    And here is the problem:
    ImageView has an ImageObserver necessary for the asynchronous image download. ImageObserver has the imageUpdate method. But this imageUpdate method is never called with ALLBITS flag raised up. Instead, after the last frame of MyAnimatedGif.gif is downloaded the imageUpdate method is called with flag ERROR raised up. Obviously this is a bug of Sun's implementation. Finaly the flag ALLBITS has to be received for normal end of image observing. But ALLBITS flag does not come.
    So, can anybody help me how to load an animated gif within JEditorPane completely.
    Thank You in advance,
    Dobromir Gospodinov
    P.S. If somebody of you wants to debbug what happens within ImageView will have to implement it (and related classes too, because of the limited package visability) borrowing the source from Sun's ImageView.

    I'm also having this problem with java 1.4.1 I discovered that some animated gifs work fine, while others stop animating. Running with java 1.3.1 fixed the problem. I'm going to report this as a bug
    Here's my code:
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class AnimatedGifTester
    extends JFrame
    public static void main(String argv[])
    throws Exception
    new AnimatedGifTester();
    public AnimatedGifTester()
    throws Exception
    String[] images = new String[] {
    "http://www.gif.com/ImageGallery/Animated/Animals/Photographic/dog_running.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/java.gif",
    "http://www.webdeveloper.com/animations/bnifiles/anielg.gif",
    "http://www.webdeveloper.com/animations/bnifiles/cat2.gif",
    "http://images.animfactory.com/animations/animals/fish/big_fish_swimming_md_wht.gif",
    "http://www.webgenies.co.uk/images/martian.gif",
    "http://www.webdeveloper.com/animations/bnifiles/at_sign_rotating.gif",
    "http://www.webdeveloper.com/animations/bnifiles/arrow_1.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/javaacro.gif",
    "http://java.sun.com/products/java-media/2D/samples/suite/Image/duke.running.gif",
    "http://www.gif.com/ImageGallery/Animated/SouthPark/Cartoon/stan.gif"
    StringBuffer buffer = new StringBuffer("<html><body>");
    for (int idx = 0; idx < images.length; idx++)
    buffer.append("<img src='" + images[idx] + "'>");
    buffer.append("</body></html>");
    String html = buffer.toString();
    // save a copy of the html to open in a browser so we can see what it's
    // supposed to look like
    BufferedWriter writer = new BufferedWriter(new FileWriter("animatedGifTest.html"));
    writer.write(html);
    writer.close();
    JEditorPane editorPane = new JEditorPane("text/html", html);
    editorPane.setEditable(false);
    getContentPane().add(editorPane);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(new Dimension(400, 600));
    show();

  • Display HTML in JEditorPane

    Hi
    I am trying to display a String containing HTML text on a JEditorPane.
    I have downloaded the HTML from a webpage using sockets, and now I want to display the downloaded page. I have a project in school about sockets.
    This is why I can't use getPage(URL);
    The following is the code I am using:
    String temp = "String with HTML text"
    HTMLEditorKit htmlEdKit = new HTMLEditorKit();
    JEditorPane.setEditorKit(htmlEdKit);
    JEditorPane.setContentType("text/html");
    JEditorPane.setEditorKitForContentType("text/html", htmlEdKit);
    JEditorPane.setContentType("text");
    JEditorPane.setText(temp);
    When I run the code, all that is displaying is the raw HTML code, with all the tags. As I understand it, this is how it should be done.
    What is wrong, would appreciate some help.
    /David Mossberg

    it's not necessary to use socket but if use socket get the inputstream from it.
    in = socket.getinputstream(); //return inputstream from socket
    htmldoc = JEditorPane.getDocument(); //return the htmldoc in JEditorPane
    if(htmldoc.getlength()>0)
    htmldoc.remove(0,htmlDoc.getLength());//if the htmldoc has some content then remove it
    reader = new InputStreamReader(in);//construct a new reader from in
    JEditorPane.getEditorKit.read(reader,htmldoc,0); //read new content into the htmldoc from reader
    Hope the above code helps you.
    joney

  • Edit html in JEDITORPANE

    HEllo friends!
    I need your help, for editing html in editorpane.
    I want to create a textarea in which the user type simple text than select some part of it & makes it bold, italic etc. by using an event of button or popup any thing.
    So guide me that which textcomponent provide this , i already used JEditorPane, and insert tags manually but it is not good, if i try to overlap the tags og italic & bold.
    So please help me is this any way pre built to provide these func. of add html tags in jeditorpane & use see the render html test in area.
    than please provide me. at [email protected]
    Thanks
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax .swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.IOException;
    public class TestJEditor extends JFrame {
    Panel p1 = new Panel();
    JButton b1 = new JButton("BOLD");
    JButton b2 = new JButton("ITALIC");
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane jEditorPane1 = new JEditorPane();
    HTMLEditorKit editorKit = new HTMLEditorKit();
    DefaultEditorKit defaultKit = new DefaultEditorKit();
    public TestJEditor() {
    super("Note");
    this.getContentPane().add(p1);
    //jEditorPane1.setEditable(false);
    jEditorPane1.setEditorKit(editorKit);
    p1.setLayout(null);
    p1.add(jScrollPane1);
    jScrollPane1.setBounds(10, 10, 350, 100);
    jScrollPane1.getViewport().add(jEditorPane1, null);
    b1.setBounds(370, 10, 100, 20);
    p1.add(b1);
    b2.setBounds(370, 40, 100, 20);
    p1.add(b2);
    b1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e)
         // jEditorPane1.setEditorKit(defaultKit);
         String str = jEditorPane1.getText();
         System.out.println(str);
         String temp = jEditorPane1.getSelectedText();
         if(temp.indexOf("<B>") != 0)
         int start = str.indexOf(temp);
         int end = start + temp.length();
         System.out.println("start "+start+" end "+end);
         str = str.substring(0,start)+"<B>"+str.substring(start,end)+"</B>"+str.substring(end);
         jEditorPane1.setText(str);
         //System.out.println(jEditorPane1.getText());
    b2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e)
         String str = jEditorPane1.getText();
         System.out.println(str);
         String temp = jEditorPane1.getSelectedText();
         System.out.println("Italic");
         int start = str.indexOf(temp);
         int end = start + temp.length();
         str = str.substring(0,start)+"<I>"+str.substring(start,end)+"</I>"+str.substring(end);
         jEditorPane1.setText(str);
    public static void main(String[] args) {
    JFrame frame = new TestJEditor();
    frame.setSize(600,500);
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    //frame.pack();
    frame.show();
    }

    Hi kashif10,
    JEditorPane or JTextPane are the classes to use. You can have both bold and italic for a text portion.
    See http://java.sun.com/products/jfc/tsc/articles/ for an overview of articles covering the swing text package.
    Or try application SimplyHTML at http://www.lightdev.com/template.php4?id=3 it is open source and has a lot of documentation too.
    Ulrich

  • HTML in JEditorPane question

    Hello
    I am having trouble with displaying HTML with image maps in JEditorPane component. I am trying to load a simple html file as follows:
    <html>
    <IMG SRC="monk.gif" HEIGHT="255" WIDTH="262" ISMAP USEMAP="#mapareas">
    <map NAME="mapareas">
    <area SHAPE=CIRCLE COORDS="107,158 132,162" HREF="basic.htm" ALT="Basic Page">
    <area SHAPE=default HREF="index.html">
    </MAP>
    </html>
    There is no problem with displaying the image. It's rendered fine without any problem. But, When I click on the circle area, I can't seem to get the URL corresponding to the map area. I tried the HyperlinkEvent::getDescription() and HyperlinkEvent::getURL() methods and both of them return the reference to the map as opposed to the reference specified for the specific map area ( in my case, "sample.map" instead of "basic.htm" ).
    Can someone tell me if HTML with image maps is supported in EditorPane? if so, how do I get the reference to the map area clicked?
    thanks in adv
    Venkat Kota

    JTextComponent.viewToModel
    then get the element at that location, either the character or
    paragraph element, then get its StyleContext.NameAttribute value, which is a HTML.Tag.
    That was a fun walk round the API, to find out more, I recomend reading through JTextComponent, and its Model/View Split section.
    The the Element and View interfaces.

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

  • How to load file.html in  JEditorPane

    Hello
    how to display HTML file including images in JEditorPane
    the file is on local system
    thanks

    This is how I read contents of a file and put it into my JEditorPane.
    I don't know if it will incliude images or not, but it might.
          try {
               editorPane1.read(new FileReader(getFile),null);
             catch(IOException e)
                       e.printStackTrace();
         

  • Missing the content when saving HTML from JEditorPane.write(..)

    hi,
    i m trying to develop html editor using JEditorPane. the document type used is HTMLDocument and HTMLEditorKit. when I try to save using the following function:
    try{
    FileWriter     w = new FileWriter("doc.html");
    //HTMLEditorKit edi = (HTMLEditorKit)editorPane.getEditorKit();
    EditorKit edi = editorPane.getEditorKit();
    //StyledEditorKit edi = new StyledEditorKit();
    //edi.write(w, (StyledDocument)editorPane.getDocument(), 0, editorPane.getDocument().getLength());
    editorPane.write(w);
    w.close();
    }catch(Exception de){System.out.println(de);
    }all the contents are missing, only the tags are intact in the output file doc.html. I am using JDK 1.4.2
    anybody can help me? thank you very much

    here is the code. hehe sorry lol it took me sometime to take off all the function. please try to type something and then save. only the update is saved but the default heading (well in this case, i have replace them all with a "something must be here". thank you very much
    // HTMLEditor.java
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class HTMLEditor extends JFrame{
      private JTextComponent textComp;
      public static void main(String[] args) {
        HTMLEditor editor = new HTMLEditor();
        editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        editor.setVisible(true);
      public HTMLEditor() {
        super("Swing Editor");
        textComp = createTextComponent();
        Container content = getContentPane();
        content.add(textComp, BorderLayout.CENTER);
        content.add(createToolBar(), BorderLayout.NORTH);
        setSize(320, 240);
        Template t = new Template((HTMLDocument)(textComp.getDocument()));
        t.setupTemplate();
      // Override to create a JEditorPane with the HTMLEditorKit in place
      protected JTextComponent createTextComponent() {
        JEditorPane jep = new JEditorPane();
        jep.setEditorKit(new HTMLEditorKit2());
        JEditorPane.registerEditorKitForContentType
         ("text/html", "HTMLEditorKit2");
        return jep;
      protected JTextComponent getTextComponent() { return textComp; }
      // Add HTML actions to the toolbar
      protected JToolBar createToolBar() {
        JToolBar bar = new JToolBar();
        bar.addSeparator();
        bar.add(new StyledEditorKit.BoldAction());
        bar.add(new SaveAction());
        return bar;
      class SaveAction extends AbstractAction {
        public SaveAction() {
          super("Save", new ImageIcon("icons/save.gif"));
        // Query user for a filename and attempt to open and write the text
        // components content to the file
        public void actionPerformed(ActionEvent ev) {
          JFileChooser chooser = new JFileChooser();
          if (chooser.showSaveDialog(HTMLEditor.this) !=
              JFileChooser.APPROVE_OPTION)
            return;
          File file = chooser.getSelectedFile();
          if (file == null)
            return;
          FileWriter writer = null;
          try {
            writer = new FileWriter(file);
            textComp.write(writer);
          catch (IOException ex) {
            JOptionPane.showMessageDialog(HTMLEditor.this,
            "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
          finally {
            if (writer != null) {
              try {
                writer.close();
              } catch (IOException x) {}
      class HTMLEditorKit2 extends HTMLEditorKit{
           public Document createDefaultDocument(){
             HTMLDocument doc = new HTMLDocument();;
             doc.setAsynchronousLoadPriority(-1); // load synchronously
             return doc;
    class Template{
         HTMLDocument doc;
         StyleContext styles = new StyleContext();
         public Template(HTMLDocument doc){
              this.doc= doc;
              Style def = styles.getStyle(StyleContext.DEFAULT_STYLE);
             Style heading = styles.addStyle("heading", def);
             StyleConstants.setFontFamily(heading, "SansSerif");
             StyleConstants.setBold(heading, true);
             StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER);
             StyleConstants.setSpaceAbove(heading, 10);
             StyleConstants.setSpaceBelow(heading, 10);
             StyleConstants.setFontSize(heading, 18);
         public void setupTemplate(){
              Style s = styles.getStyle("heading");
              try{
                   doc.insertString(doc.getLength(), "Something must be here", s);
                   doc.insertString(doc.getLength(), "\n", null);
                    doc.setLogicalStyle(doc.getLength() - 1, s);
              }catch(Exception e){}     
    }

  • Inserting HTML in JEditorPane

    Extremely frustrating trying to work with the HTML editing model (JEditorPane - content type text/html). I am using 1.4.2_06. Tying some basic actions to buttons or keystrokes is no problem (eg bold, italic etc.) but the most NB things like being able to drop a <br> in where the user presses enter doesn't seem possible. Has anyone found a way to drop in HTML at the caret? Would hugely appreciate any ideas.
    Matthew

    Ok, figured it out myself:
            notesArea.getInputMap().put(KeyStroke.getKeyStroke("enter"), "enterAction");
            notesArea.getActionMap().put("enterAction", new HTMLEditorKit.InsertHTMLTextAction("InsertBR", "<br>", null, HTML.Tag.IMPLIED, null, null));

  • Rendering html in JEditorPane

    hi
    i have a problem in JEditorPane.
    when i rendering a html with frameset then i cannt resize the frames (like JSplitPane) but it working in browser.
    so how i do it in JEditorpane??
    thanks

    I think it just ignores it, but I could be wrong. If you want to do what you are saying, I think you need some custom document or something. The standard classes aren't going to help much, as far as I can tell.

  • Problem viewing html with JEditorPane..

    The program will run, but it displays nothing but an empty pane. The program program also stars out very small in the top right hand corner of the screen so I have to resize it. What do I need to do to be able to view the HTML file?import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.io.IOException;
    public class test_pane extends JFrame //implements ActionListener
    public test_pane()
    super("Note");
    //Create editor pane
    JEditorPane editPane = createEditorPane();
    JScrollPane escroll = new JScrollPane(editPane);
    escroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    escroll.setPreferredSize(new Dimension(500, 250));
    escroll.setMinimumSize(new Dimension(10,10));
    private JEditorPane createEditorPane()
    JEditorPane editPane = new JEditorPane();
    editPane.setEditable(false);
    String s = null;
    try {
    s = "file:"
    + System.getProperty("user.dir")
    + System.getProperty("file.separator")
    + "TextSamplerDemoHelp.html";
    URL helpURL = new URL(s);
    displayURL(helpURL, editPane);
    catch (Exception e)
    System.out.println("Couldn't create help URL: " + s);
    return editPane;
    private void displayURL(URL url, JEditorPane editPane)
    try {
    editPane.setPage(url);
    catch (IOException e)
    System.out.println("Attempted to read a bad URL: " + url);
    public static void main(String[] args)
    JFrame frame = new test_pane();
    //frame.setSize(600,500);
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

    Ok, I couldn't see where you add the scroll pane to the content pane of the frame and without a minimum size set somewhere the frame.pack() would shrink it completely. I recreated what you wrote and put the minor changes in there.
    Try this out:
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.io.IOException;
    public class Temp extends JFrame {
         BorderLayout borderLayout1 = new BorderLayout();
         JScrollPane jScrollPane1 = new JScrollPane();
         JEditorPane jEditorPane1 = new JEditorPane();
         HTMLEditorKit editorKit = new HTMLEditorKit();
         public Temp() {
              super("Note");
              this.getContentPane().setLayout(borderLayout1);
              jEditorPane1.setEditable(false);
    jEditorPane1.setEditorKit(editorKit);
              this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
              jScrollPane1.getViewport().add(jEditorPane1, null);
              String s = null;
              try {
                   s = "file:"
                   + System.getProperty("user.dir")
                   + System.getProperty("file.separator")
                   + "TextSamplerDemoHelp.html";
                   jEditorPane1.setPage(new URL(s));
              catch (Exception e) {
                   System.out.println("Couldn't create help URL: " + s);
         public static void main(String[] args) {
              JFrame frame = new Temp();
              frame.setSize(600,500);
              frame.addWindowListener(new WindowAdapter()
              public void windowClosing(WindowEvent e)
              System.exit(0);
              //frame.pack();
              frame.show();
    }

  • Getting caret position in HTML of JEditorPane

    Hi
    How can I get the equivalent position of the caret in the HTML behind a JEditorPane?
    Regards
    Peter

    Do you mean how to take the int that is returned from
    editorPane.getCaretPosition();
    and figure out what HTML is at that position?
    HTMLEditorKit (javax.swing.text.html) may help. Also check out class HTMLDocument and its method getReader(int pos).
    Sorry, I haven't actually done this, so I am just throwing out ideas.
    Barb

  • Disple html using JEditorPane

    I want display html file using JEditorPane
    but I become an exception
    java.net.MalformedURLException: unknown protocol: e
    what schould be the problem
           import javax.swing.*;
           import java.net.URL;
           import java.io.File;
    public class Browser extends JFrame
          JEditorPane  ePane = new JEditorPane();
          public Browser(){
              this.setBounds(200,50,700,650);
              this.setLayout(null);
              ePane.setBounds(50,20, 600,500);
              try {
                       File file = new File("xx.html");
                       String ss = file.getAbsolutePath();
                     URL url = new URL(ss);
                     ePane.setPage(url);
                 } catch (java.io.IOException ex) { ex.printStackTrace(); }
              this.add(ePane);
    }  

                   File file = new File("xx.html");"xx.html" lacks a protocol, like "http" or "ftp". But anyway, why not just use File.toURL()?

  • Interactive HTML in JEditorPane?

    --Sorry, I just realized this belongs into the Swing forum, I'll repost it there.                                                                                                                                                                               

    as for example reacting to link clicks Read the JEditorPane API. It has an example of using a HyperlinkListener.

  • Some HTML pages (JEditorPane) work in 1.4.1 but not in 1.4.0

    Is anyone aware of this problem?

    Check the 1.4.1 Release Notes for the changes between versions and see if any of those apply.

Maybe you are looking for