Hyperlink in JTextpane without HTMLEditorKit?

Hi,
how is it possible to insert a hyperlink without HTMLEditorKit, simply with a StyledDocument ?
private void addCustomStylesToDocument(StyledDocument doc) {
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = doc.addStyle("regular", def);
StyleConstants.setFontFamily(def, "Arial");
Style s = doc.addStyle("link", regular);
StyleConstants.setUnderline(s, true);
StyleConstants.setBold(s, true);
StyleConstants.setForeground(s, Color.BLUE);
How is it possible to add the hyperlinkListener to a style?
Thomas

The way I do this is to create a child style for every link containing a key of my own making that maps to the url ref. Then you need a MouseMotionListener to do the hand cursor and a MouseListener for clicks.
  void mouseMoved(MouseEvent me)
       JTextComponent jt = (JTextComponent)me.getComponent();
       int pos = jt.viewToModel(me.getPoint());
       if (pos >= 0)
            StyledDocument d = (StyledDocument)jt.getDocument();
            Element el = d.getCharacterElement(pos);
            AttributeSet as = el.getAttributes();
            if (as.getAttribute(urlRefKey) != null)
              jt.setCursor(linkCursor__);
         else
            jt.setCursor(defaultCursor__);
  }Sorry about the tabbing. In MouseListener.mouseClicked(MouseEvent) call the above code (which you factored out) and if you are over a URL then get the ref from the attributes and launch your browser...

Similar Messages

  • Hyperlink in JTextPane - It's not a hyperlink, what's wrong?

    Hi,
    I tried to insert a hyperlink into a JTextPane, but it looks like normal text and it has to much space to the rest of the inserted text, when refencing the JTextPane-Object "txtPane" to a HyperlinkListenerImpl()-Objekt and insert the strings with the method addHyperlinkA(url, sTxtSplit). Do you have any idea what the problem is? Here is the complete sourcecode.
    Best regards,
    Thomas
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class HyperPane extends JFrame {
    private JTextField txtField;
    private JTextPane txtPane;
    private Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
    private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
    private HTMLDocument document;
    private MutableAttributeSet attributes = new SimpleAttributeSet();
    private int linkID = 0;
    public HyperPane() {
    this.setSize(500, 500);
    this.setTitle("HyperPane");
    initGUI();
    Dimension fsize = this.getSize(),
    ssize = Toolkit.getDefaultToolkit().getScreenSize();
    int fX = (ssize.width - fsize.width)/2,
    fY = (ssize.height - fsize.height)/2;
    this.setLocation(fX, fY);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    public static void main(String args[]) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    new HyperPane();
    private void initGUI() {
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new BorderLayout());
    txtPane = new JTextPane();
    //document = (HTMLDocument)txtPane.getStyledDocument();
    document = new HTMLDocument();
    //attributes = new SimpleAttributeSet();
    txtPane.setEditorKit(new HTMLEditorKit());
    txtPane.setDocument(document);
    txtPane.setEditable(false);
    txtPane.setMargin(new Insets(5, 5, 5, 5));
    //LinkControllerB lc = new LinkControllerB();
    //txtPane.addMouseListener(lc);
    //txtPane.addMouseMotionListener(lc);
    // txtPane.addHyperlinkListener(new HyperlinkListener() {
    // public void hyperlinkUpdate(HyperlinkEvent he) {
    // System.out.println("link");
    txtPane.addHyperlinkListener(new HyperlinkListenerImpl());
    contentPane.add(new JScrollPane(txtPane), BorderLayout.CENTER);
    contentPane.add(createInputPanel(), BorderLayout.SOUTH);
    private JPanel createInputPanel() {
    JPanel panel = new JPanel();
    txtField = new JTextField(30);
    txtField.setText("text before link -> http://www.denic.de <- text after link");
    JButton butAdd = new JButton("Hinzuf�gen");
    butAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    parseMsg(txtField.getText());
    panel.setLayout(new FlowLayout());
    panel.add(txtField);
    panel.add(butAdd);
    return panel;
    private void parseMsg(String sTxt) {
    SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
    String[] sTxtSplit = sTxt.split(" ");
    for (int i = 0; i < sTxtSplit.length; i++) {
    int iHttpPos = sTxtSplit[i].indexOf("http:");
    System.out.println(sTxtSplit[i]);
    if (sTxtSplit[i].indexOf("http:") > -1) {
    try {
    URL url = new URL(sTxtSplit[i]);
    addHyperlinkA(url, sTxtSplit[i]);
    } catch (MalformedURLException male) {
    } else {
    try {
    document.insertString(document.getLength(), sTxtSplit[i] + " ", attributes);
    } catch (Exception e) {
    e.printStackTrace();
    try {
    document.insertString(document.getLength(), "\n\n", attributes);
    } catch (Exception e) {
    e.printStackTrace();
    public void addHyperlink(URL url, String text) {
    try {
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setUnderline(attrs, true);
    StyleConstants.setForeground(attrs, Color.BLUE);
    //attrs.addAttribute(ID, new Integer(++linkID));
    attrs.addAttribute(HTML.Attribute.HREF, url.toString());
    document.insertString(document.getLength(), text, attrs);
    catch (BadLocationException e) {
    e.printStackTrace(System.err);
    private void addHyperlinkA(URL url, String text) {
    try {
    MutableAttributeSet hrefAttr = new SimpleAttributeSet();
    hrefAttr.addAttribute(HTML.Attribute.HREF, url.toString());
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    attrs.addAttribute(HTML.Tag.A, hrefAttr);
    document.insertString(document.getLength(), text + " ", attrs);
    } catch (BadLocationException e) {
    e.printStackTrace(System.err);
    public void addHyperlinkB(URL url, String text) {
    // First, setup the href attribute for <A> tag.
    SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
    hrefAttr.addAttribute(HTML.Attribute.HREF, url.toString());
    // Second, setup the <A> tag
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    attrs.addAttribute(HTML.Tag.A, hrefAttr);
    // Apply the hyperlink onto the selected content.
    // textPane is a reference to the JTextPane instance.
    int p0 = txtPane.getSelectionStart();
    int p1 = txtPane.getSelectionEnd();
    if (p0 != p1) {
    //StyledDocument doc = txtPane.getStyledDocument();
    document.setCharacterAttributes(p0, p1 - p0, attrs, false);
    class HyperlinkListenerImpl implements HyperlinkListener {
    public void hyperlinkUpdate(HyperlinkEvent event) {
    JTextPane pane = (JTextPane)event.getSource();
    HyperlinkEvent.EventType type = event.getEventType();
    System.out.println("hyperlinkUpdate");
    if (type == HyperlinkEvent.EventType.ENTERED) {
    pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    System.out.println("type == HyperlinkEvent.EventType.ENTERED");
    } else if (type == HyperlinkEvent.EventType.EXITED) {
    pane.setCursor(Cursor.getDefaultCursor());
    System.out.println("type == HyperlinkEvent.EventType.EXITED");
    } else if (type == HyperlinkEvent.EventType.ACTIVATED){
    pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    System.out.println("type == HyperlinkEvent.EventType.ACTIVATED");
    // if (event instanceof HTMLFrameHyperlinkEvent) {
    // HTMLDocument doc = (HTMLDocument)pane.getDocument();
    // doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent)event);
    // System.out.println("event instanceof HTMLFrameHyperlinkEvent");
    // } else{
    // try {
    // pane.setPage(event.getURL());
    // } catch(IOException ex){
    // ex.printStackTrace();
    class LinkControllerB extends HTMLEditorKit.LinkController {
    public void mouseMoved(MouseEvent ev) {
    System.out.println("mouseMoved");
    public void mouseClicked(MouseEvent e) {
    JTextPane editor = (JTextPane) e.getSource();
    if (!editor.isEditable()) {
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
    if (pos >= 0) {
    System.out.println("mouseclicked at pos: " + pos);
    class LinkController extends MouseAdapter
    implements MouseMotionListener {
    public void mouseMoved(MouseEvent ev) {
    JTextPane txtPane = (JTextPane) ev.getSource();
    System.out.println("mousemoved");
    if (!txtPane.isEditable()) {
    Point pt = new Point(ev.getX(), ev.getY());
    int pos = txtPane.viewToModel(pt);
    if (pos >= 0) {                   
    Document doc = txtPane.getDocument();
    if (doc instanceof HTMLDocument) {
    HTMLDocument hdoc = (HTMLDocument) doc;
    Element e = hdoc.getCharacterElement(pos);
    AttributeSet a = e.getAttributes();
    String href = (String) a.getAttribute(HTML.Attribute.HREF);
    if (href != null) {
    System.out.println("href != null");
    // if (isShowToolTip()){
    // txtPane.setToolTipText(href);
    // if (isShowCursorFeedback()) {   
    // if (txtPane.getCursor() != handCursor) {
    // txtPane.setCursor(handCursor);
    else {
    System.out.println("href == null");
    // if (isShowToolTip()){
    // txtPane.setToolTipText(null);
    // if (isShowCursorFeedback()) {   
    // if (txtPane.getCursor() != defaultCursor) {
    // txtPane.setCursor(defaultCursor);
    } else {
    //setToolTipText(null);
    public void mouseDragged(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    JTextPane editor = (JTextPane) e.getSource();
    if (! editor.isEditable()) {
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
    if (pos >= 0) {
    System.out.println("mouseclicked at pos: " + pos);

    Hi thechrimsonrabbit,
    Is your home page ''about:home'' or is it ''http://www.google.com''. The ''about:home'' is the default Firefox home page with a google search built in. The second link is the actual google page. You might want to save that as your home page if you want all the extra tabs.
    Hopefully this helps!

  • Force word wrap in JTextPane (using HTMLEditorKit)

    Hi!
    I have a JTextPane on a JScrollPane inside a JPanel. My text pane is using HTMLEditorKit.
    I set the scrolling policies of my JScrollPane to: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.
    I did not find in JTextPane�s API any relevant property I can control word-wrapping with (similar to JTextArea�s setLineWrap) and I have tried a few things to force word-wrapping but nothing worked...
    What happens is my text is NOT being wrapped (even though there is no horizontal scrolling) and typed characters (it is an enabled editable text componenet) are being added to the same long line�
    I�d like to force word-wrapping (always) using the vertical scroll bar whenever the texts extends for more then one (wrapped) line.
    Any ideas?
    Thanks!!
    Message was edited by:
    io1

    Your suggestion of using the example only holds if it fits the requirements of the featureDid your questions state anywhere what your requirement was?
    You first questions said you had a problem, so I gave you a solution
    You next posting stated what your where currently doing, but it didn't say it was a requirement to do it that way. So again I suggested you change your code to match the working example.
    Finally on your third posting you state you have some server related issues causing the requirement which I did not know about in my first two postings.
    State your problem and special requirments up front so we don't waste time quessing.
    I've used code like this and it wraps fine:
    JTextPane textPane = new JTextPane();
    textPane.setContentType( "text/html" );
    HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
    HTMLDocument doc = (HTMLDocument)textPane.getDocument();
    textPane.setText( "<html><body>some long text ...</body></html>" );
    JScrollPane scrollPane = new JScrollPane( textPane );If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Local Folio hyperlinks get published without updating article

    When creating a local folio, I don't even have to update the article and the hyperlinks are published and functioning when using preview folio. How is this possible? I haven't tried this with a remote folio yet.

    Hi Andrew,
    can't help unfortunatly, but I get the same error when trying to download a retina display folio using a normal dps account. Download is "prepared" for about 5 minutes after which I get the error message:
    An error has occurred while exporting the folio.
    Failed to download the folio to your local disk.
    [downloadIssueFailed]
    However, normal resolution folios can be exported and exporting a retina folio from a professional DPS account works.
    Best greetings,
    Philip

  • JTextPane - Need to override TAB insert for traversal

    I am using the JTextPane for HTML support. I want the TAB key to default to traversing components instead of inserting tabs or spaces. For JTable and JTextArea I was able to clear the focus traversal keys and they correctly defaulted to the standard component method (i.e., Tab traverses components)
    setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
    setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
    This works for JTextPane when using plain content ("text/plain") but not HTML content ("text/html"). I assume it is because of the default editor that is installed in each case, but i can not figure out how to change the behavior or the editor (e.g., HTMLEditorKit).
    Any help would be geatly appreciated.

    I did a quick test using method 1 on a JTextPane without HTML and it seemed to work. I'll let you test it when it's using the HTMLEditorKit:
         This example shows two different approaches for tabbing out of a JTextArea
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextAreaTab extends JFrame
         public TextAreaTab()
              //  Replace the Tab Actions (this is the solution I prefer)
              JTextArea textArea1 = new JTextArea(5, 30);
              textArea1.setText("1\n1\n3\n4\n5\n6\n7\n8\n9");
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              getContentPane().add(scrollPane1, BorderLayout.NORTH);
              InputMap im = textArea1.getInputMap();
              KeyStroke tab = KeyStroke.getKeyStroke("TAB");
              textArea1.getActionMap().put(im.get(tab), new TabAction(true));
              KeyStroke shiftTab = KeyStroke.getKeyStroke("shift TAB");
              im.put(shiftTab, shiftTab);
              textArea1.getActionMap().put(im.get(shiftTab), new TabAction(false));
              // Reset the FocusManager
              JTextArea textArea2 = new JTextArea(5, 30);
              textArea2.setText("2\n2\n3\n4\n5\n6\n7\n8\n9");
              JScrollPane scrollPane2 = new JScrollPane( textArea2 );
              getContentPane().add(scrollPane2, BorderLayout.SOUTH);
              textArea2.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
              textArea2.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
              // (we don't want the scroll bar to receive focus)
              scrollPane2.getVerticalScrollBar().setFocusable(false); // for tabbing forwards
              scrollPane1.getVerticalScrollBar().setFocusable(false); // for tabbing backwards
         class TabAction extends AbstractAction
              private boolean forward;
              public TabAction(boolean forward)
                   this.forward = forward;
              public void actionPerformed(ActionEvent e)
                   if (forward)
                        tabForward();
                   else
                        tabBackward();
              private void tabForward()
                   final KeyboardFocusManager manager =
                        KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusNextComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusNextComponent();
              private void tabBackward()
                   final KeyboardFocusManager manager =
                        KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusPreviousComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusPreviousComponent();
         public static void main(String[] args)
              TextAreaTab frame = new TextAreaTab();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

  • Changing filename of hyperlink

    Hi - Is there a way to set up hyperlinks to files without iWeb inserting the filename into the web page? The filenames of my pdf documents that I want to link to tend to be very long and I would prefer to use some generic text, say "(pdf)", for people to click on.
    Thanks a bunch!
    MacBook Pro Mac OS X (10.4.8)

    check this video tutorial:
    http://karreth.com/files/hyperlinks.mov
    here for all
    http://karreth.com/iweb
    max
    From the Apple Terms Of Use I must state to provide this link: I may receive some form of compensation, financial or otherwise, from my recommendation or link

  • Can't create hyperlinks after converting a Word document with Acrobat XI Pro

    Hello,
    Here's my problem.
    I'm making a catalog document for my company.
    The document that I'm converting to PDF is made on Office Word 2013 and it's a .docx format file.
    I'm on Windows 8 and the latest version of Adobe Acrobat XI Pro installed.
    Inside my word document I have some pictures that have a hyperlink. Those hyperlinks directionate to a bookmark inside the word document. Inside the word document, if I do Ctrl+Click over the image, it will go to the page that has that bookmark. And it works. Period.
    Beside that I also have some Cross-references on the word document. Those cross-references basically are the page number from the bookmark reference. By accident on most of those cross-refrences I left enabled the "Insert as hyperlink" on the cross-reference box options. When I Ctrl+Click over those cross-references I also go into the page of that cross-reference.
    After I convert the word document into pdf, I can't get any hyperlink on the pictures, if I simply click on them, like if I click on a hyperlink on a webpage or something similar, the pdf won't go the the bookmark on the page that I've set on the word document.
    The funny thing is that if I click on the other cross-references I can go to the page were that cross-reference is...
    I tried all the methods to convert the file in order to obtain hyperlinks on the images...
    I tried to use the Acrobat tab and the File -> Save as Adobe PDF, as both uses Acrobat PDFMaker, but nothing works.
    Even tried all options on Acrobat PDFMaker but can't get it. "Create bookmarks", "Add links", "Convert Word Bookmarks", "...Word Styles to Bookmarks", "...Word Headings to Bookmarks", none works....
    If I try to simply print from inside Word by choosing the Adobe PDF printer (like if I choose a regular printer), in the printers options it doesn't show up any hyperlink/link/bookmark option related, so that way is definitely a no go...
    To reference, on 2006/2007 I also worked on a similar project and used this method on the word document (on Word 2003). At that time I had another Adobe Acrobat version, can't remember what version was...
    This hyperlink situation was without any problem. After conversion, on the pdf file, if I click on a image it went to the right place inside that pdf file...
    So I'm simply lost wether it's a problem of me, a problem of Word, a problem from Acrobat... simply lost...
    I'm desperated....please, someone help me!!!

    Ok, sorry for never talk since the last time, but I finally discovered why I had this problem.
    I found out that M$ decided somehow to change the process of embedded hyperlinks on a image, but in a docx it doesn't get affected. Only after transforming it into a pdf by Acrobat that the problem emerges...
    I found this site http://www.pb-solv.net/2013/08/embed-pictures-in-microsoft-word.html
    Basically all I have to do is "Use Insert, Quick Parts, Field, IncludePicture. This inserts the picture in the old way as a field. You can use Alt-F9 to reveal the field codes and change the images to be embedded rather than linked."
    Then, after converting it with acrobat, the pdf finally have hyperlinks on the images!!!
    They change this on Word 2007. As I had the 2003, at the time, I didn't had this problem.
    As I said, M$ changed something, but only is affected after converting with acrobat. So, acrobat also missed something in the process. I call it a 50/50 guilt.
    To bad no one ever notice this problem...

  • Hyperlinks not closing out in RH

    Here's another odd behavior:
    When I bring my FM book into RH, my hyperlinks are not closed
    out in the converted content in RH. In FM, the hyperlinks are
    correctly inserted using the gotolink and newlink Hypertext
    markers. Yet in RH, the rest of the sentence in which the hyperlink
    appears is also erroneously tagged as part of the hyperlink.
    Is this is a bug? Has anyone else seen this behavior and if
    so, how did you fix it?

    Hello Michael,
    This is not an issue, you'd always get the hyperlinks
    appearing corrcetly without any tagging in the Design view of RH.
    Just try to close and reopen the topic in the Design view or try to
    view it in preview - it shoudl appear correctly.
    Regards,
    Pooja

  • Same Image every time in JTextField with HTMLEditorKit and HTMLDocument

    Hi all
    I have a JTextPane with HTMLEditorKit as editorkit and HTMLDocument as document. I am trying to load an html file into the text pane. the html file contains image. When loading first time it is shown perfectly. After I change the image file with other file with the same name(overwrite it) and trying to load the html file again,the image is the first time loaded image. As i think the image is kept somewhere in "cash" or kind of that. But I need to refresh the html every time it is loaded and not to read from "cash".
    And code which i use:
    package client.temp;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class TestPanel extends JPanel {
    public TestPanel(File htmlFile) {
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane();
    HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
    HTMLDocument htmlDocument = new HTMLDocument();
    setLayout(new BorderLayout());
    scrollPane.getViewport().add(textPane, null);
    add(scrollPane, BorderLayout.CENTER);
    URL baseUrl = null;
    try {
    baseUrl = htmlFile.getParentFile().toURL();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    htmlDocument.setBase(baseUrl);
    textPane.setEditorKit(htmlEditorKit);
    try {
    FileInputStream fi = new FileInputStream(htmlFile);
    InputStreamReader isr = new InputStreamReader(fi, "UTF8");
    BufferedReader r = new BufferedReader(isr);
    htmlEditorKit.read(r, htmlDocument, 0);
    r.close();
    isr.close();
    fi.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (BadLocationException e) {
    e.printStackTrace();
    textPane.setDocument(htmlDocument);
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton b = new JButton();
    b.setText("push");
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    TestPanel panel = new TestPanel(new File("c:\\temp\\temp.html"));
    JFrame fShow = new JFrame();
    fShow.getContentPane().setLayout(new BorderLayout());
    fShow.getContentPane().add(panel, BorderLayout.CENTER);
    fShow.setSize(800, 600);
    fShow.setVisible(true);
    frame.getContentPane().add(b);
    frame.pack();
    frame.setVisible(true);
    and here is the html file structure of my temp.html file
    <html>
    <body>
    <p>
    <img src='image01.jpg'>
    </p>
    </body>
    </html>
    the folder in which the temp.html located (in my case c:\\temp\\) contains image01.jpg file too.
    The piece above works correctly when clicking on the button first time.i.e. shows the image01.jpg correctly. After closing the showing frame fShow(not exiting application) and replacement of the image01.jpg by other file named image01.jpg, but with other content and clicking button again shows the first image again.If I exit the application and start again the picture is shown correctly.
    I need this because I am getting images from database while the template is same always.
    Thanks in advance.

    URL baseUrl = null;
    try {
    baseUrl = htmlFile.getParentFile().toURL();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    htmlDocument.setBase(baseUrl);All you want is to defeat the cache. You could do it using random number generation.
    String newURL = htmlFile.getParentFile().toURL().toString();
    String rand = "rand="+new java.utl.Random().nextLong();
    if ( newURL.indexOf("?")>=0)
    newURL +="&"+rand;
    else
    newURL +="?"+rand;
    baseURL = new URL(newURL);
    htmlDocument.setBase(baseURL);
    This will ensure that u are using different url everytime.(well mostly!)

  • How to replace a particular striing with another string in jtextpane

    how to get replace a particular string with another string of a jtextpane without taking the text in a variable using getText() method .

    Thanks for your answer,
    "relevant object" means for you datasources, transfer rules and transformations ?
    With the grouping option "Save for system copy" I can't take easily all datasources, and others objects
    Will I have to pick all object one by one ?
    What would be the adjustement in table RSLOGSYSMAP ? For the moment it's empty.
    Regards
    Guillaume P.

  • How to see page ends/page breaks in JTextPane?

    Hi guys!
    I have a JTextPane with HTMLEditorKit.
    can i make possible for user to see page ends in document?
    If i'm not wrong it's related with ViewFactory, but how to do it?
    and is that possible at all?
    thank you

    Unfortunately you are right. It's impossible with HTML.
    I just needed to see the page ends like for ex. in MSWord.
    So, it seems there is also no way to do something with headers and footers...
    I'm developing the text editor that supports image inserts. I tried RTFEditorKit first, but it seems to be unfinished and there is also no support of images. So i decided to use HTMLEditorKit.
    And one question:
    I understand - HTML page is one whole page, but how desired page numbers are printed using PrintDialog? when i'm giving pages 1,3,5, How can system get page ends?
    So can i get somehow where the A4 page ends and starts the next one?
    thenks

  • HTMLEditorKit renders tables width attribute wrong inside paragraph

    I noticed that the following html
    <html>
    <body>
    <p>
    <table width="100%" border="1">
    <tr>
    <td>
    something
    </td>
    </tr>
    </table>
    </p>
    </body>
    </html>
    .. doesn't 'stretch' the tables width to 100% when using JTextPane and HTMLEditorKit - it's only a few chars wide. Mozilla, Explorer and other browsers display the table right. If I remove the <p> then it works as expected.
    Is there a workaround for this behavior.. it sure would be nice to have it display the table like the 'standard' browsers do.

    I noticed that the following html
    <html>
    <body>
    <p>
    <table width="100%" border="1">
    <tr>
    <td>
    something
    </td>
    </tr>
    </table>
    </p>
    </body>
    </html>
    .. doesn't 'stretch' the tables width to 100% when using JTextPane and HTMLEditorKit - it's only a few chars wide. Mozilla, Explorer and other browsers display the table right. If I remove the <p> then it works as expected.
    Is there a workaround for this behavior.. it sure would be nice to have it display the table like the 'standard' browsers do.

  • I have no bullets with HTMLEditorKit

    I am using JEditorPane, StyleSheet and HTMLEditorKit for simple HTML viewer with css support.
    It works fine, but my list does not have bullets !!!! Here is my code:
    style = new StyleSheet();
    style.addRule("H1{ color: red;font-family: arial, helvetica, sans-serif;font-size: 12 pt;font-weight: bold;text-align: center;}");
    style.addRule("H2{color: blue;ont-family: arial, helvetica, sans-serif;font-size: 16 pt;font-weight: bolds;text-align: center;}");
    style.addRule("body{line-height : 22px;}");
    style.addRule("li {list-style-type: disc;font-size: 12 pt;font-weight: bold;}");
    style.addRule("P{font-size: 12 pt;font-weight: normal;margin: 0.5 em;margin-left: 1 em;}");
    objHTMLKit = new HTMLEditorKit();
    objHTMLKit.setStyleSheet(style);
    jep.setEditorKit(objHTMLKit);
    jep.setText(strSource);
    scroll = new JScrollPane(jep);
    when i just set the HTML source right to the JEditorPane, without HTMLEditorKit and CSS it is fine.
    Do i have to work on the HTMLEditorKit or it has to do it by default ?????
    Everything else is ok and the <li> element is getting bigger or smaller but without bullets.
    thanks for any help :)

    This phone uses a Sim Card but as I found it's a 3G only phone but if the Sim handles all the phones information Like on a 4G phone the Sim might need to be replaced)  If the card is used for something totally different simply *228 send 1 phone refresh is all that is needed)  but it's best to call customer Service and ask as they can walk you through the steps and it may be you just need to update your PRL  preferred roaming list..
    Here is Customer Service's Number:  they open in just a few Hours.. 1-800-922-0204 use Option 3 when ask what you like to do Say you would like to talk to a Representative.. If this is your only phone available to talk on then I recommend a stop by a Local Verizon Comm store for further assistance..
    Good Luck Welcome to the Forum.. b33  

  • Home key not working in JTextPane?

    Hi all,
    I have a very simple example with a JTextPane. I call the method:
    pane.setPage("someHTMLPage.html");
    to load the html page. When I'm editing the JTextPane and press the "home" key, the cursor disapears. This only happens on the first line of text, and if you then press the right arrow key, the cursor appears again. But you can't input any text in the JTextPane when the cursor has disapeared.
    Is this a bug? Its a very simple example I'm using, so I can't see it being my code thats introducing the issue.
    any help?
    thanks,
    Justin

    Just adding the example I'm using.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Enumeration;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.JToolBar;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.HTMLWriter;
    * Simple class to print out the html from the text pane.
    * Got the basic code to do this from a posting on the swing forms on the javasoft website.
    public class WISIWIGTextPane extends JFrame {
        private JTextPane pane;
        private JButton bold;
        private JButton italic;
        private JButton underline;
        private JButton dump;
        private JToolBar tb;
        private HTMLEditorKit kit;
        private HTMLDocument doc;
        public WISIWIGTextPane() {
            super("WISIWIGTextPane");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            init();
        public void init() {
            pane = new JTextPane();
            kit = (HTMLEditorKit)(pane.getEditorKitForContentType("text/html"));
            doc = (HTMLDocument)(kit.createDefaultDocument());
            pane.setEditorKit(kit);
            pane.setDocument(doc);
            try {
                pane.setPage("file:///c:/java/testingJava/TextSamplerDemoHelp.html"); //my html file
            catch(java.io.IOException e) {
                System.out.println(e.toString());
            tb = new JToolBar(JToolBar.HORIZONTAL);
            bold=new JButton(new StyledEditorKit.BoldAction());
            italic=new JButton(new StyledEditorKit.ItalicAction());
            underline=new JButton(new StyledEditorKit.UnderlineAction());
            dump=new JButton("Dump");
            // prints the underlying html code on the console for verifying
            dump.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println(pane.getText());
            tb.add(bold);
            tb.add(italic);
            tb.add(underline);
            tb.add(dump);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(tb,"North");
            getContentPane().add(new JScrollPane(pane),"Center");
        public static void main(String[] args) {
            new WISIWIGTextPane().setVisible(true);
    }

  • JTextPane and HTMLDocument : setCharacterAttributes does not work

    Hi,
    I'm trying to change the background color of a part of some HTML text
    within a JTextPane - without having the focus on the JTextPane.
    I had a piece of code that did work fine with standard text, using the
    following code:
    doc = new DefaultStyledDocument();
    jTextPaneSrc = new JTextPane(doc);
    MutableAttributeSet attr= new SimpleAttributeSet();
    StyleConstants.setBackground(attr, Color.white);
    doc.setCharacterAttributes(start,end,attr,true);
    Ok, now I'm trying migrate this piece of code in order to handle HTML.
    So, replacing DefaultStyledDocument with an HTMLDocument (which extends it) should work fine.
    Well, actually it does for rendering - but not for the setCharacterAttributes method.
    Any idea why or any workaround ?
    Many thx & rgds,
    - Francois

    hi fbabin,
    did you find a solution to this problem ... i think i've just run into the same one.
    thanx for your or anyones help
    dominik

Maybe you are looking for

  • Link db results to Dropdown list and link to email

    I need to pull information from a table 'Suppliers' in an (datebase.mdb) and retrieve two items, name and email. This in itself Dreamweaver makes fairly simple. From this information I need to produce a dropdown list, again Dreamweaver makes this sim

  • How to return jolt connection back to the joltpool?

    hi I used following codes to get joltconnection pool: SessionPool sessionPool = sessionPoolManager.getSessionPool(poolName);      DataSet request = new DataSet(requestString.length()*2);      request.setValue("STRING", requestString);      Result res

  • What is the problem in my Connection Pool ???

    Hello,guys: My using connection pool is in trouble,it always dies and does't output any error messages(can not get an available connection),so I should restart my Tomcat(4.1), The following code in Login.jsp page initializes the pool : <%      Connec

  • Has anyone else lost their Sucure Notes in Keychain since upgrading to Mavericks?

    Since upgrading to Mavericks i have lost all my Secure Notes in Keychain. I had backed up OS10.8.5 on my Time capsule  before upgrading but can not access the backups in time capsule- they appear as a black screen in the Time Capsule window. Is anyon

  • Really not sure what to categorize this question as......

    How do I fix a problem that I have with an online game site.  I downloaded a game from Shockwave and it wouldn't work.  So I tried trouble shooting and my computer stated that the game had incompatible files.  I need help with resolving incompatible