JTextPane with hyperlinks

Hi,
I?m building a little IRC client. I?m using a swing JtextPane but my problem is that I can?t insert hyperlinks into it.
The JtextPane is based on a DefaultStyledDocument, I have created a Style called Hyperlink.
Style style4 = myStylePane.addStyle("Hyperlink", defstyle);
StyleConstants.setUnderline(style4,true);
doc.insertString(doc.getLength(),"Http://www.Java.Sun.com",style4);
The problem is that I can?t find a proper method how I can make the text a click-able hyperlink.
I have tried already the following:
Style style4 = myStylePane.addStyle("Hyperlink-Jlabel", defstyle);
StyleConstants.setComponent(style4, new Jurl("http://www.Java.sun.com"))
doc.insertString(doc.getLength(),"Ignore text",style4);
The class Jurl extends of Jlabel, plus I have implemented the event mouseclicked that opens the url in a blank browser window.
But the problem here is that Jlabel breaks out of the visible rectangle of my JtextPane (right side break). So it is possible that I see for example http://www.Java.su here ends my JtextPane. The JtextPane does no take a new line to display the JLabel.
Thanks in advance and,
Have a nice day.
Pieter Pareit

Here, you should be able to adapt this;-import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.applet.*;
public class linkIt extends Applet {
   Panel  back = new Panel();
   public linkIt(){
      super();
      setLayout(new BorderLayout());
      add("Center",back);
      back.setLayout(null);
      Olink link1 = new Olink(this,"Go to google and search ","http://www.google.com");
      back.add(link1);
      link1.setBounds(10,10,100,25);
      Olink link2 = new Olink(this,"Answer for programmers ","http://forum.java.sun.com");
      back.add(link2);
      link2.setBounds(10,40,100,25);
   public void init(){
      setVisible(true);
   public class Olink extends Label implements MouseListener {
      Applet  applet;
      Color   fcolor = Color.blue;
      Color   lcolor = Color.magenta;
      String  text;
      String  wadd;
   public Olink(Applet ap, String s, String s1){
      super(s);
         this.applet = ap;
         this.text   = s;
         this.wadd   = s1;
         addMouseListener(this);
      setForeground(fcolor);
   public void paint(Graphics g){
   super.paint(g);
      if (getForeground() == lcolor){
         Dimension d = getSize();
         g.fillRect(1,d.height-5,d.width,1);
   public void update(Graphics g){paint(g);}
   public void mouseClicked(MouseEvent e){
      try{
         URL url = new URL(wadd);
         applet.getAppletContext().showDocument(url,"_self");
      catch(MalformedURLException er){ }
   public void mouseEntered(MouseEvent e){
      setForeground(lcolor);
      setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      repaint();
   public void mouseExited(MouseEvent e){
      setForeground(fcolor);
      setCursor(Cursor.getDefaultCursor());
      repaint();
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
   public static void main (String[] args){
      new linkIt(); 
}

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.

  • Sorting not working in a report with hyperlinks

    I have a report with hyperlinks for one column and I noticed that sorting is no longer working on that report. If I use another version of the same report witout hyperlinks; sorting does work fine.
    I was wondering if anyone has encountered this issue before and what would be the solution.
    Thanks!

    I didn't remove the sorts and was trying to sort again on another column.
    So this is resolved.
    Now another issue; when viewing this report in Interactive mode; the column with hyperlinks doesn't have the sort option when I right click on that column. The sort option does show up but it's grayed out (disabled). When I go to Edit mode; it does allow me to sort on that column.
    Anyone has noticed this?

  • How to place an indesign page with hyperlinks in another indesign file, such that the links work?

    I have a page of text with hyperlinks in a master indesign file.
    I place that file into another indesign file.
    (It is like an html include file for a webpage.In this way i only have to update the file in one place.)
    But when i export the indesign file to pdf, the hyperlinks fail to work.
    They work in the original but not in the second.
    Does anyone have any suggestions?
    Abby Eagle

    My apologies. My tests were done using URLs. They function in Acrobat regardless of their state in InDesign.
    Aside to Bob: Since I had just made a PDF that worked, I mistook your "Since when" to mean since when won't a placed ID file work? I guess I was blind sided by the fact that the only hyperlinks I ever come into contact with are full URLs.
    If Abbey's situation is as I envisioned -- that the placed files are more akin to smaller graphics within the layout of a page rather than discreet pages at all -- then is this not a insolvable problem given how InDesign works now?

  • I saved a word document with hyperlinks in it as a pdf.  When following the links in the pdf, i can't the browser to go back to the pdf.  Help ..

    I saved a word document with hyperlinks in it as a pdf.  When following the links in the pdf, i can't the browser to go back to the pdf.  Help ..

    You cannot save word files to pdf using reader. When you click a link (in Reader or in the browser using the Reader plugin) you open the url in your browser (what browser)? We need detailed information to help.

  • I created a word document with hyperlinks. When my default browser is Chrome the hyper links work. When the default browser is Safari, the hyperlinks bring to pages that just lines and lines of symbols. I need these links to work in both browsers.

    I created a word document with hyperlinks. When my default browser is Chrome the hyper links work. When the default browser is Safari, the hyperlinks bring to pages that just lines and lines of symbols. I need these links to work in both browsers. Any ideas?

    version 10.6.8

  • Insert a spreadsheet and word docs into a PDF with hyperlinks

    I have a spreadsheet index with hyperlinks to 455 single page word docs. I want to make a single pdf by inserting the spreadsheet followed by the word docs.
    Is there a way of having the hyperlinks recognize the inserted word docs pages inside the pdf via the original hyperlinks, or do I need to remove the hyperlinks before inserting the spreadsheet and then do bookmarks for all 455 pages? Or some other method?

    James,
    I doubt that will work. But it should be easy enough to find out. If you
    print to pdf from ID, I guarantee is will not work. If you export from
    ID, I doubt it will work, but ask in the ID forum, since the creation
    does not depend upon Acrobat.
    Mike

  • How to get the UIDRef of Text frame associated with hyperlink?

    Hi,
    I have a document which contains Text hyperlinks . I am able to get the number of hyperlinks present in document using "IHyperlinkTable" and text range to which hyperlink is associated using interface "IHyperlink".
    InterfacePtr<IHyperlink> hyperlink(tableDb, table->GetNthHyperlink(i), IID_IHYPERLINK);
    if(hyperlink)
           hyperlink->GetName(&sHyperlinkName); //sHyperlinkName is text to which hyperlink is associated
    now I need to find the UIDRef of Text frame with which hyperlink is associated.
    I can get the UIDRef of "Image frame" using interface "IHyperlinkPageItemSourceData".
    InterfacePtr<IHyperlinkPageItemSourceData> sourceHyperLink (tableDb, hyperlink->GetSourceUID(), UseDefaultIID());
    if (sourceHyperLink)
            UID sourceHyperLinkUID  = sourceHyperLink->GetSourceUID();
    but this interface may be not helpful in case of text in the frame (word/words) associated with hyperlink.
    If anyone has done this please do let me know.
    Thank you all in advance.
    Priyanka

    Hi All,
    I am still unable to get the solution of this issue. If anyone has done this please help me to find the solution.
    Thanks in advance.
    Priyanka

  • Interactive pdf in indesign with hyperlinks warning

    create adverts that are interactive pdf in indesign with hyperlinks and mail to links and now we are assembling the document back together in the form of a book but on importing the pdf back into indesign we are getting the
    warning: “this file may contain newer extensions or information than this viewer can support. it may not open of display correctly and cannot be changed.”
    when the pdf imports the hyperlinks on the text work but the hyperlinks on the images are gone?
    Using version cs5 v7.0.4

    @Steve – I'm not so sure about that.
    At least the OP could experiment with Acrobat Pro's "Import as Layer" function.
    With "Import as Layer" you could import another PDF to a new layer.
    But I don't know if all the interactivity will stay in place and will be working.
    Did not test that yet.
    See the screen where I did layer two different PDFs together. A German version and an English version of the same document:
    "Import as Layer" is an option in the Layers at the sidebar of Acrobat Pro.
    As you can see there are some options for positioning with "Manual positioning".
    Acrobat Pro's Layers with options:
    Uwe

  • Problem with Hyperlink  in JEditorPane!!

    hi all!
    I have some problem.
    I create html page with hyperlink to myProgram.jar and when i open this html page in JEditorPane and click on hyperlink i have the some text but my program don't run.
    How write HyperlinkListener for run the my program and setUrl for open other html pages.
    thanks!

    In the future, Swing related questions should be posted in the Swing forum.
    But, there is no need to repost the question because you can just read the JEditorPane API to find an example of how to write a HyperlinkListener.

  • Email pdf with hyperlink

    Hi,
    I am trying to email an optimized pdf file with hyperlinks. The links work and show up when I am in Acrobat (version - Prof. 9.0), but when i email the pdf they do not show up in the email. My ultimate goal is for the entire pdf page to show up in the email (so u don't have to actually open any programs) with the links active, so when reading the email you can move your cursor over it and the link will show as active. Hope that makes sense, in essence it's basically an email blast, but for some reason my links aren't showing up in the final email. I would appreciate any help.
    Thanks

    >My ultimate goal is for the entire pdf page to show up in the email
    Impossible to assure that with all users. Many may have their email client set to show it as an attachment only.

  • Merging pages in C# with Hyperlinks (destinations empty)

    Hi all,
    I tried to merge PDF documents with CAcroPDDoc InsertPages. It works well. Now I have hyperlinks in my documents. After merging the documents the list of destinations is empty and the links are dead.
    Does anyone know a solution to this problem?
    With four your help
    ctNoSpec

    It's a bug/limitation of the COM APIs for page insertion.
    Use the JSObject bridge to get to the JavaScript version and be sure to pass the right values for the insertFlags.
    From: ctNoSpec <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Mon, 27 Feb 2012 06:05:55 -0800
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: Merging pages in C# with Hyperlinks (destinations empty)
    Re: Merging pages in C# with Hyperlinks (destinations empty)
    created by ctNoSpec<http://forums.adobe.com/people/ctNoSpec> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/4231932#4231932

  • Embed Quicktime export with hyperlinks in web page

    I've got a project I exported from Keynote with hyperlinks -- forward, back, return to menu, etc.
    The links work fine in the Quicktime export playing in the player. They work fine if I open the file directly in a web browser.
    If I embed the file in a web page, however, the link functionality goes away, and it ends up as a 'click-to-advance' movie. Does anyone know if there's a parameter I need to include in the embed code to enable hyperlinks? I couldn't find any likely candidates in Apple's official list...

    My apologies; something must have gone wrong with my export. Tried again, and it works fine!

  • How I creatat text with hyperlink in application

    hi all,
    I want to creat some text with hyperlink (it mean when I click to text, it invoke other panel or web...). My program is Application. Can any one tell me how I do it. Pls help me!!!.
    Thank you verry much

    Is this text HTML? If so, just go to any of the 350,000 sites on the Internet that describe basic HTML. Otherwise, just output the URL as text.
    However my guess is that your bigger problems are (a) how to notice the hyperlink is clicked and (b) how to invoke whatever it links to. Right?

  • Problems with Hyperlinks when exporting to EPUB

    I've been trying to export a CS5 indd to Epub (using corEpub script -http://www.teusdejong.nl/indesign/-), but there seems to be some kind of conflict with Hyperlinks (there's 6000 of them): when they are near to a footnote reference, the text of hyperlinks (and some text surrounding it, don't know the criteria) just disappear and the reference doesn't work. Any ideas about what could be happening?
    (Sorry for my english)

    I just came across this same problem -- similar but not exactly the same.
    Text in a table does not print properly when text is superscripted.
    This is a problem since we have a French invoice that has a fair bit of superscript. I tried to work around by decreasing the font size and increasing the baseline, but this did not work.
    I'm using Pages 5.1 and Mavericks.
    Anyone have any ideas????

Maybe you are looking for

  • Cannot login to network accounts from client computer

    Hi. I'm setting up my first OS X Server setup for home use...I'm not creating a very complicated setup, but I've been working through the setup one step at a time. Right now, I'm just running the DNS, File Sharing, and Open Directory services. I setu

  • [Solved?] VLC won't play audio -- cannot set buffer duration

    I can't play sound in VLC. I have tried the default and the ALSA outputs. I know ALSA works, because mpg123, speaker-test, and rdesktop's sound all work. (Saying that, I can't tell if mpg123 uses alsa or not - rdesktop does though) Attempting to play

  • WDA Human Task does not complete/close

    Hi experts, I'm still struggling to flex web dynpro abap and BPM together. After embedding a wda chip as human task within my process, I face the next problem: The event defined as outport in my wda chip does not close the task when fired from my wda

  • Why is Aperture 3 sooooo slow?

    Let me first say I just started using Aperture 3 after using Photoshop/Lightroom for years and so far over all I LOVE it. However I'm finding it to be extremely slow at processing images. I made a default preset in adjustments that I would like to us

  • How do i clear my apps...ios6 used to double click home button

    Need help...i just upgraded to IOS7.  In teh past i used to be able to double click by ipad home button then keep my finger on the app and it would move/shake to allow me to X out of the program and clear the game(but not delete).  Any idea how to do