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!

Similar Messages

  • I recieved the following message when I connect my device to teh computer: This Ipod cannot be used because the apple mobile device service is not started.  What's wrong?

    I recieved the following message when I connect my device to the computer: This Ipod cannot be used because the apple mobile device service is not started.  What's wrong?

    http://support.apple.com/kb/TS1567
    There have been some problems accessing pages on the Apple web site.  If the hyperlink gives you a "We're sorry" message, try again.

  • An Acrobat 11 system update was running and did not complete.  What is wrong?

    When I opened a PDF file.  A message indicated an Error: 1 had occurred and to uninstall and re-install Acrobat 11.  I uninstalled, but the reinstall will not complete.  What is wrong?

    What is your operating system?  Do you receive any error message(s)?

  • Ever since I got the new update 5.1 my iPod's been dying faster. It used to last for at least 3 hours, now it won't even last one hour and dies for no reason(even when it's in sleep mode, and not in use) What's wrong with it? Is it the update? lagging too

    Ever since I got the new update 5.1 my iPod's been dying faster, even after I charge it. It used to last for at least 3 hours, now it won't even last one hour and dies for no reason (even when it's in sleep mode, and not in use) What's wrong with it? Is it the update? It's lagging as well..

    Some Users have Reported that a  Restore as New  has helped Resolve issues...
    Backup and Set Up as New Device
    http://support.apple.com/kb/HT4137

  • My iphone 5 can not charged. What is wrong with it?

    My iphone 5 can not be charged, What is wrong with it?

    Don't know what's wrong but take it back to apple they will replace it

  • I bought a t.v show on itunes and it is not playing. What's wrong?

    I bought a t.v show on itunes and when I click to play it, it is just a black screen and the show is not playing. The show is counting down in time but there is no sound or picture. What's wrong?

    Hi Paul,
    If you are having an issue such as this with an item such as a movie purchased from the iTunes store, you may want to report it to the store. Use the steps in this article -
    Report an problem with an item you bought from the iTunes Store, App Store, Mac App Store, or iBooks Store
    Thanks for using Apple Support Communities.
    Best,
    Brett L 

  • File & folder sharing with privileges on my network does not work. What is wrong?

    My Timecapsule is creating a network between my iMac with OS 10.7.5 and my Macbook Pro Retina OS 10.9.2. I am trying to setup a folder on my iMac with controlled access privileges to work as a server for others using the Macbook as a client. I followed different tutorials to the letter, but it did not work, I could not get the connection. Then I called the Apple help line. It turns out that just setting it up with a 'sharing only' account etc. in 'sharing ' in the 'system preferences' is not enough. One also has to set up the same priviliges in the 'get info' window of the folder directly at the same time...so a double setup. They could not explain properly why and there is no mention of this whatsoever in any tutorial I found on the internet. Anyway, I tried that and it still did not work. When I add the user in the 'get info' window and press enter, suddenly the user does not show up in the privilege box with the user name but instead a line saying something like "searching for user" and something small dudeling next to it......I called Apple again. After two agonizing hours on the phone where I was treated like an imbecile it turns out one has to somehow go through the address book ??? Why, I have no clue and how, I do not remember, but suddenly it worked.
    Anyway, now two month later I had to add a new user account to my Macbook and I need to give it access to my server folder on my iMac. Well same problem again. I cannot remeber what we did 2 month ago an cannot call Apple, because my service period has expired. I tried myself and got the dudle in the folders 'get info' window again. Then by mistake I deleted myself as the only administrator account on the Imac from the access privileges to that shaered server folder. When I tried to put my account back into the folders privilege settings I got the same message and the dudeling thingy there too. Frustrated I thought it is best to just re-start the computer.......that was the end of it all: Now the startup window does not show my account name and icon anymore, just two lines to fill in the account name and password. The upper line has an arrow pointing left, the lower for the password an arrow pointing right. I filled in the account name and the password....the dudle circle comes and nothing happens, it seems to crash. When I click on the arrows the sign-in lines disappear, only the three buttons for going to sleep, re-start and turn off at the bottom are the only items left on the screen. I tried 10 times to no avail. This is turning into a nightmare!! My account is the only user account on this iMac.......
    What am I doing wrong? Or what is wrong with my iMac?
    Why is there nothing mentioned about these issues in the tutorials or anywhere else? Why do the tutorials say it is so easy, when even the staff on Apple's helpline cannot figure it out without having lengthy side conferences with their co-workers and managers???
    Does anybody know what I have to do again with the address book to add this external 'sharing only' user account to the folder's privilege settings?
    I assumme I have to re-boot my computer tomorrow and restore it from the Time Capsule. How do I do that? I cannot log in????
    With the setup I had working for the last two month there were still issues with acces conflict to new subfolders and files inside the shared folder between me and the Macbook account user. I have read that the solution is to create a group and give the group access privileges to the folder. However, I could not find any details on the exact steps to follow. I need the exact steps, otherwise this will turn into the next nightmare. Where can I find this info.
    I would really appreciate your help with answers and solutions to these complex issues
    Thank you

    check out managed datasources in the manuals

  • Just had problem with frozen up Mac computer corrected,now HP printer will not print.  Says printer not connected.  What is wrong?  Everyday a new problem., help.

    JJust had problem corrected due to frozen imac, now HP printer will not print.  Says it is not connected.  What do I do to fix it?

    To reset the printing system:
    Choose System Preferences from the Apple menu.
    Choose Print & Scan from the View menu.
    Hold down the Option key while clicking the "-" (Remove printer) button. If no printers are currently added, hold down the Control key while clicking in the box that appears above the "+" (Add printer) button, then choose Reset printing system… from the contextual menu.
    When you've done the above you'll need to re-add the printer by clicking the + (Add printer)

  • I can't play a bought video in iTunes, and VLC only plays it but no screen. And I have to athourize all the time but it does not help. What's wrong?

    Hi all.
    Just bought my first video from iTunes Store and should watch it with my son. I had to authorize, this and that for some time, but finally I got the video in my iTunes, but it was just a black screen. Nothing playing and no sound (of course). So I tried VLC and it was at least runing there, but no screen and no sound. Quick time said I had to authorize my iTunes acount first (which I had done several times before) and did it again with just the same result, nothing happening. What's wrong? I'm no geek so please help me out with this, I thought it should be easy piecy with a iMac and iTunes, well, hope it was a one in a million problem.
    Thanks

    Could be a corrupt Download.
    If you live in a Region that allows re-downloading Music...
    Delete the Song(s) and re-download...
    See Here  >  Download Past Purchases  >  http://support.apple.com/kb/HT2519
    If not... Contact iTunes Customer Service  >  Apple  Support  iTunes Store  Contact Us

  • When save as pdf, the dialog windows does not open. What is wrong?

    Working in illustrator, when saving time choose save as and click pdf, what is expect is, "the dialog box that  enable me to choose the quailty in pdf"  but it (the dialog box) does not appeared today. It still works yesterday. What went wrong? Please help.

    Your Mail is not gone. The problem you are having following the upgrade to Leopard (10.5.6) from Tiger, is probably what has been covered by the support document at the link below:
    http://support.apple.com/kb/TS2537
    If you also find any files named to include MessageSorting (which would mean you once have upgraded from a version of OSX earlier than 10.4), remove those, also, but never restore those.
    To find the correct location for the Mail folder, open a Finder window, click on the icon of a house in the Sidebar (this is known often as "Home"), click on Library in that Home user directory, and then to open the Mail folder found there.
    Ernie

  • Set up Element 10 as external editor in Lightroom 3, it does not work.  What's wrong?

    I am using Lightroom 3.  Just bought the Element 10 and set it up in Lightroom as external editor.  It does not work at all.  What's wrong?

      Make sure you are linking to the application and not a shortcut. If using Mac OSX you may need to reveal hidden folders.
    http://helpx.adobe.com/x-productkb/global/access-hidden-user-library-files.html

  • I just downloaded Photoshop Elements 13 and IMPORT is not functional.    What is wrong?

    I just downloaded Photoshop Elements 13 and IMPORT is not functional.    I reinstalled the printer /scanner and still not functional.   My computer is recognizing the printer.   What is wrong?

    I guess the first thing you now need to do is to get the latest drivers for your printer because as you say you uninstalled it from your machine and now reinstalled it again.  I don't know why you thought printer should have been uninstall;led but anyway, please reinstall the driver and then see if it is recognized by your operating system and try scanning something as a test from outside the PSE13 before going back to PSE13 and trying to scan your real image.
    Please post back so that Barbara or R_Kelly can help you as I don't use Apple Mac.

  • I have installed adobe flashplayer but it will not run. What is wrong?

    Today I downloaded adobe flashplayer 11.2.202.235 apparently successfully(so I was informed) but when I try to run a program requiring flashplayer it does not run. What can I do?

    Moving this discussion to the Installing Flash Player forum.

  • Lately pdf files from the Web do not display properly; what is wrong and how can I fix it so I don't have to use IE?

    I am a professor and frequently need to open pdfs of academic journal articles from electronic databases. Within the last two or three weeks, when I try to do this using Firefox, only the first page of the pdf displays and the rest are blank. In addition, a bar appears across the top with the message "This pdf file may not display properly." So I have had to switch to Internet Explorer to open the files and do my research. What is going on and how can I fix it so I can open pdf files from the Web in Firefox and have them display properly?

    My question is simple - why would you put an application in production that has a lot of bugs? To replace a good and steady Adobe product? My customers will believe that I put a pathetic fallible form online. They are not sophisticated on computers so I just tell them to use IE. Ugh
    I must agree with pgwebgirl!

  • I have used Firefox on my computer for several years. Today, after upgrading to the new version, I was not able to open Firefox. I have tried several times uninstalling and re-downloading Firefox. It still will not open! What is wrong?

    I have used Firefox on my computer for several years. Today, after upgrading to the new version, I was not able to open Firefox. I have tried several times uninstalling and re-downloading Firefox. It still will not open! Is the new version not compatible with Windows Vista?

    I hope that link points to mozilla.com or mozilla.org
    You will have to close firefox.exe with the Windows Task Manager from the "Processes" tab of the WTM since you don't have a widow to close.
    The best way to close Firefox is through File > Exit, for those who stuck with the "Firefox" button click on the Firefox button then Exit. It is not perfect but it is a lot better than just closing the window with the "X" in the upper right corner

Maybe you are looking for

  • Apple Device Enrolment Program

    Some months ago i saw a question about the device enrolment program.I was just wandering  if it is now available as some months have passed and i am hearing rumours. If so,has anyone in medium/large co-operations in the UK used this service to deploy

  • Setting column names in a sql statement

    hello everyone i hope someone can help me. i want a sql statement that gets the column names from a arraylist for example String sql = ("INSERT INTO Cust (and i want this part to get what is in the arraylist) values (?, ?, ?)"); is there any way i ca

  • Download 8.1.7.2

    Hello, I need to download and install 8i and apply 1.7.2 fix.. I don't know where to get them.. i could see only 9i and 10g under downloads.but not 8i. Please advise.

  • How do I get to the profile folder to change settings?

    A spammer has taken control of my email. AT&T says I need to change my firefox profile settings but I can't find the folder. How do I get to the folder. == This happened == Every time Firefox opened == Last Thursday

  • Rolling, Jumping finder file lists on OS 9 clients

    Weird. 10.4.8 Server with some Tiger clients and some OS 9 clients. On shared volumes on the OS 9 clients the files lists in finder windows roll up and down and sometimes jump. So much so that sometimes it's difficult to select a file in the list. Or