JTextPane  create hyperlinks

in my project,
strings are entered in separate field n get displayed in JTextPane
i want d strings get processed n to b checked if they r links like http://.....
or www. ...
if so they 've to b converted to hyperlinks.
how do i achieve this..

Swing related questions should be posted in the Swing forum.
You should be using a JEditorPane. Read the JEditorPane API. It shows you how to add a HyperlinkListener and has a link to the Swing tutorial on "Using Text Components" which has an example.

Similar Messages

  • Insert String to JTextPane as hyperlink

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

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

  • Report navigation after creating hyperlink

    Hi,
    I am using Webi rich clinet XI R3.1. I have one main report with six dashboards and associated detailed reports. I created hyperlink for each of the dashboard and linked to detailed report in infoview.
    If i need to see main report i've to close this detailed report.Now how can i make the detailed report open in same window and navigate forward and backward to the main report instead of closing.
    I would appreciate if some one could provide any work around available if possible atleast.
    Thanks,
    Eswar

    Hi
    Create two links one Back and one Next in each report.
    Drag two free standing cells in the report and use opendocument syntax to create the links.
    The thread Re: Hyperlink Back functionality may give an idea.
    Regards

  • How to create hyperlinked text in F1 help of a particular Data Element.

    Dear Guru
    I have encountered an issuse regarding to create hyperlinked text in F1 help of a particular Data Element.
    For Example what i am trying to do is ---
    If you open a particular data element say "ATNAM" in se11 you will found the below documentation available for ATNAM -->>
    DE ATNAM
    Text
    Characteristic Name
    Definition
    Name that uniquely identifies a *characteristic*.
    >> The "characteristics" comes in hyperlinked bluecolor and if we press this it linked to below --- >>
    Definition: characteristic
    Classification (CA-CL)
    Property for describing and distinguishing between objects, such as length, color, or weight.
    Profitability Analysis (CO-PA)
    I am able to make 1st part of the documentation using SE61.
    But I am not able to make Hyperlinked part of that documentaion .
    please show me some way to develop this
    Thanks & regards
    Saifur Rahaman

    HI,
    you can give the hyperlink in the documentation by going to the path below
    MENUBAR ----> INSERT -----> TEXT -----> HYPERTEXT.
    this will solve the issue
    have a good day
    regards
    sarves

  • How to create hyperlinks in Acrobat 9 Pro?

    Hi everyone,
    Is there a way to create hyperlinks from within Acrobat 9 Pro? If so, can you let me know how? I am having a hard time finding out how to do so.
    Thank you in advance for your help:)
    Christine

    I did this from the advanced menu to make all hyperlinks work. All I got were boxes around my links that are not clikcable to the web page.
    Now I cannot undo this.

  • How to automatically create hyperlink destinations based on numbered list?

    I am very new to InDesign and am creating a template for an academic journal. Each article contains a list of references at the end and the references are cited in the main text (like what you see in Wikipedia if you are not familiar with scientfic journal articles). In exported HTML, the citation in the main text should be hyperlinked to the coressponding reference in the reference list. I have two questions:
    1) It is possible to ask paragraphy style to assign each numbered item a hyperlink destination? If this is possible, I can then manually inserted hyperlinks in the main text.
    2) one step further, is there any way (e.g. script) which can then insert hyperlink to those destinations based on pattern match? For example, in main text, the citation to reference #1 appear in the text as [1] which should be hyperlinked to reference #1.
    One more question, is there anyone who knows how academic journals handle the flow from InDesign to html? Certainly, the exported html cannot go directly online without further editing.
    Thank you.

    Hi Eric,
    I posted the script here. But it should be adjusted to your particular document. (Anyone with basic scripting knowledge can do this). I am sure it won’t work as it is. I assume that “comments” and “references” are in two different stories.
    Can I have the scripts from you (for a fee or free)?
    I don't sell my scripts: they're free.
    Can the scripts handle the pattens like these [3], [1-5], [3,4], [6, 8, 11-13]?
    This script can't, but another handles both single page numbers and page ranges like so:
    I can post it as well.
    Now I’d like to make one thing clear:
    I made a set of scripts for creating hyperlinks in InDesign documents for further exporting them to ePub/HTML. I can’t make a script that would work for everyone because all books are very different. I simply adjusted scripts for every book I had to work with (mainly changing GREP expressions and names of styles) and I have numerous variations of scripts. I can post them if someone is interested but you should be aware that they have to be reworked.

  • How to create hyperlink using form

    if a user click on button then
    oulook express open for sending mail but i want to create hyperlink on it automatically.
    actually when user click then a word file created on server i want to hyperlink this file the file name is my form serial_no

    when i click on button outlook express is opening know and i can send text on body through forms
    i need it to send hyperlink on outlook express so i can open document through this link which is on outlook express file

  • My customer wants to create hyperlinks in the editor - surely this is possible?  And, if so, how?

    My customer simply wants to create hyperlinks when adding content to her site; this doesn't seem possible within the Muse editing interface.  It must be, surely?  That's the most basic thing to do with a web page. 

    At current stage In browser editing does not includes hyperlinks , but that’s definitely a request we hear often. Unfortunately we can’t comment on what features are coming to Adobe Muse, but please know the team is listening!
    Thanks,
    Sanjit

  • Problem in create Hyperlink

    Hi All,
    I create hyperlink by finding http and www in my active document.                //Works well
    But the problem is, if the url or websites contents coming twice or above then I found error   //not able to create hyperlink source with the same name
    i.e., www.gmail.com (comes 2 or more time in the document, then the below code is not working fine)
    var myDoc = app.activeDocument;
    app.findGrepPreferences = app.changeGrepPreferences = null;
    //Find http and www
    app.findGrepPreferences.findWhat = "(?i)(http|www)\\S+[\\l\\u|\\d]"
    var myFound1 = myDoc.findGrep();
    count = 0
    for(k=0; k<myFound1.length; k++)
        var myFind = myFound1[k];
        var myHyperlinkSource = app.activeDocument.hyperlinkTextSources.add(myFind)
        var myHyperlinkURLDestination = app.activeDocument.hyperlinkURLDestinations.add(myFind.contents)
        var myHyperlink = app.activeDocument.hyperlinks.add(myHyperlinkSource, myHyperlinkURLDestination, {name: myFind.contents})
    //    var myHyperlink = app.activeDocument.hyperlinks.add(myHyperlinkSource, myHyperlinkURLDestination, {name: myFind.contents+count++})
    Please find the screenshot for your more references.
    Please help to find the solution.
    Thanks in advance
    Beginner_X

    I solved this problem by adding an incrementing number in round brackets if a hyperlink name is already taken.
    Another (simpler) solution is to put "add hyperlink" line into try-catch block, but in this case you'll have a default name if the error occurs.
    Here's the function:
    function MakeHyperlink(text, url) {
        if (url.match(/https?:\/\//) == null) {
            url = "http://" + url;
        url = url.replace(/\.$/, "");
        var name = text.contents;
        var oriName = name;
        if (doc.hyperlinks.itemByName(name) != null) {
            var increment = 1;
            while (doc.hyperlinks.itemByName(name) != null) {
                name = oriName + " (" + increment++ + ")";
        try {
            var dest = doc.hyperlinkURLDestinations.itemByName(name);
            if (!dest.isValid) {
                dest = doc.hyperlinkURLDestinations.add(url , {hidden: true});
            var source = doc.hyperlinkTextSources.add(text);
            var hyperlink = doc.hyperlinks.add(source, dest, {highlight: HyperlinkAppearanceHighlight.NONE, visible: false});
            try {
                hyperlink.name = name;
            catch(err) {
                //$.writeln(err.message + ", line: " + err.line);
            if (hyperlink.isValid) {
                hypCount++;
                if (set.tempColors) source.sourceText.fillColor = swatchOK;
                if (set.charStyle) source.appliedCharacterStyle = charStyle;
        catch(err) {
            errorsCount++;
            var swatchProblem = MakeSwatch("===== PROBLEM =====", {
                model : ColorModel.PROCESS,
                space : ColorSpace.RGB,
                colorValue : [255, 0, 0]
            text.fillColor = swatchProblem;
            //$.writeln("Error message: " + err.message + ", Line: " + err.line + ", URL: " + url);
            arr.push("Error message: " + err.message + ", Line: " + err.line + ", URL: " + url);       

  • Creating hyperlinks to pdf docs on a CD. Anyone experienced in doing this?

    Need to create hyperlinks to pdf documents in a CD. The pdf docs were created using an older version of Adobe and I am trying to follow a YOuTube instructing me how to create hyperlinks in the Table of Contents on the CD. The instructions on the YoTube do not match what is in the document for creating a hyperlink. Do I need to send and save all documents as NEW adobe pdf.s??? Thanks!!!

    [discussion moved to Creating, Editing & Exporting PDFs forum]

  • Garbled text when creating hyperlinks

    I have a user who is creating hyperlinks in the Table of Contents of a 500 page PDF to pages within the PDF. After 10-15 hyperlinks, she gets strange characters and garbled text on some of the pages. If she saves and closes the document and reopens, she can go back to working but it will reoccur soon again. She is using Acrobat 9 Professional on Windows 7 Enterprise. She has the latest updates for Acrobat. Any thoughts?
    thanks

    Most of the document was converted from Microsoft Excel 2007 documents. The Table of Contents was converted from Microsoft Word 2007 document.

  • Already create hyperlink in MSWord file. same link how can i import in indesign?

    Dear All,
    Already create hyperlink in MSWord file. same link how can i import in indesign?

    I'm not having an issue as shown below:

  • Creating hyperlinks in form region

    How can I create hyperlinks in the form region.when clicked on hyperlink it should take to a different page.Thanks in advance.

    Jari,Thanks for your help.
    The form is not a tabular one. For exapmle I have couple of items say username and password. Below the username I would like to place a hyperlink.Similerly I would like to place another hyperlink below the password. how can I do that?
    I tried to create a text below the username filed using the display item.How can I hyperlink the text so that it can take to another page?

  • How to create hyperlink for the messages in oneorder documents

    Hi ,
    I want to create hyperlink for the error messages that are raised for a payment request, so that i can navigate to that particular object ID mentioned in the message.

    Hi Paparao,
    But we can find the same functionality for trade promotions overlap, the messages raised when two or more tradepromotions overlap, provide us with hyperlink through which we can navigate to that particular object id.
    Regards
    Tejarshi
    Edited by: tejarshi vadduri on Apr 17, 2009 6:55 AM

  • Robohelp 11 - Creating hyperlinks within a topic

    Hi community,
    Just a quick question, tried to figure it out but can't seem to see how.
    I'd like to create hyperlinks in a specific topic that the user will be able to click on and it will jump the user to a specific place in the same topic (Ex: in section 2.1, in the middle of some explanation, refer to the heading of section 2.2).
    I looked it up, but can only seem to be able to configure hyperlinks to other topics or something outside of RoboHelp.
    Could someone help me with that ?
    Tks in advance

    You first need to create a bookmark in the topic you want to jump to. Place your text cursor at the jump location (don't select any text) and select Insert > Bookmark. Enter a name without spaces. On the topic you want to jump from, create a hyperlink like you are used to. Instead of choosing the topic, choose the topic with the text #bookmarkname attached. (Bookmarkname will be the text you inserted on creating a bookmark.)
    Kind regards,
    Willam

Maybe you are looking for

  • Abap code not working  - deleting based on master data table information

    Hi, I wrote a piece of code earlier which is working and during test we found out that it will be hard for the support guys to maintain because it was hard coded and there is possibility that users will include more code nums in the future sample cod

  • Image not showing in Links

    Somehow a few images in my document, which previously showed in the links, now do not. The image is visible, just not the link in the panel. What may have happened, and how to I find it? The preflight indicates no missing link, but it's clearly not t

  • Oracle NACHA payment format - CR/LF after 94 characters?

    Trying to update the standard Oracle Payables APXNACHA.rdf to throw a CR/LF after each 94 characters, but as far as I can see from the layout, it should be doing that anyway. Somehow, the developer has managed to get the fields from the various repea

  • I am going to an apple store and...

    me and my family are going on a vacation soon and the place we are staying is close to an apple store (the one in the oxmoor center in Kentucky.) i was wondering if you have to schedule an appointment for a genius, and can i ask them anything? can th

  • Express card slim card

    Hello all - I'm trying to find a slim (hides inside) USB express card for my MacBook Pro. I've found several that fit and extend outside the computer. Any help would be greatly appreciated!! Thanks, Joe