Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend


Hyperlinks connect web pages to other web pages: Click a hyperlink and a new web page appears. Because they’re so useful, you might think that Swing provides a hyperlink component for embedding hyperlinks in GUIs. This isn’t the case, however. Fortunately, SwingX’s org.jdesktop.swingx.JXHyperlink class lets you create hyperlink components that introduce hyperlinks in your GUIs.

Call the public JXHyperlink() and public JXHyperlink(Action action) constructors to create hyperlink components. The constructors differ in how you register actions (objects whose classes implement the javax.swing.Action interface) with the components: Call the inherited method public void setAction(Action a) (first constructor) or pass an argument (second constructor).

Subclass javax.swing.AbstractAction to create actions. The constructor saves the hyperlink’s text in the action’s NAME property (the hyperlink component shows NAME’s contents) and the actual hyperlink in the action’s SHORT_DESCRIPTION property (the tool tip shows the hyperlink). The public void actionPerformed(ActionEvent e) method executes whenever you click the hyperlink:

private class LinkAction extends AbstractAction
 LinkAction (String linkText, String link)
  // Save the link’s text and the actual link for later recall when the
  // user clicks the hyperlink.

  putValue (Action.NAME, linkText);
  putValue (Action.SHORT_DESCRIPTION, link);

 public void actionPerformed (ActionEvent e)
  // Retrieve the actual link and output link to the console (for test
  // purposes).

  String link = (String) getValue (Action.SHORT_DESCRIPTION);
  System.out.println (link);

  // Launch the default Web browser and have the Web browser display the
  // Web page associated with the link.

  BareBonesBrowserLaunch.openURL (link);

After creating the action and registering it with the hyperlink component, JXHyperlink hyperlink = new JXHyperlink (new LinkAction (linkText, link));, for example, you can customize the component’s unclicked color by calling public void setUnclickedColor(Color color). The current unclicked color can be obtained by calling public Color getUnclickedColor().

I’ve created an HLDemo application that uses JXHyperlink to embed a hyperlink in an About dialog box. When a user clicks the hyperlink, the default web browser starts running and takes the user to my web site. (This shows you the value of using a hyperlink to promote your business,) Before I present this application’s source code, examine Figure 3, which shows the About dialog box and its hyperlink.

Figure 3

Figure 3 The text is underlined when the mouse pointer moves over the hyperlink. The mouse pointer would have changed to a hand if the About dialog box had a parent window.

I excerpted the previous LinkAction class from HLDemo. Listing 3 places this class in the context of HLDemo’s source code.

Listing 3 HLDemo.java.

// HLDemo.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;

import org.jdesktop.swingx.JXHyperlink;

public class HLDemo
 public static void main (String [] args)
  // Establish a look and feel for this application’s about dialog box.

  setLookAndFeel ();

  // Construct a modal about dialog box with a title, a message, and link
  // information.

  AboutDialog ad = new AboutDialog (null,
          "HLDemo 1.0",
          "by Jeff Friesen",

  // Present the about dialog box to the user. Because the about dialog box
  // is modal, the thread executing the main() method will not exit this
  // method until the dialog box is disposed.

  ad.setVisible (true);

 static void setLookAndFeel ()
   // Return the name of the LookAndFeel class that implements the
   // native OS look and feel. If there is no such look and feel, return
   // the name of the default cross platform LookAndFeel class.

   String slafcn = UIManager.getSystemLookAndFeelClassName ();

   // Set the current look and feel to the look and feel identified by
   // the LookAndFeel class name.

   UIManager.setLookAndFeel (slafcn);
  catch(Exception e)

class AboutDialog extends JDialog
 AboutDialog (JFrame parent, String title, String message, String linkText,
    String link)
  // Assign title to the dialog box’s title bar and make sure dialog box is
  // modal.

  super (parent, title, true);

  // Tell dialog box to automatically hide and dispose itself when the user
  // selects the Close menu item from the dialog box’s system menu.

  setDefaultCloseOperation (DISPOSE_ON_CLOSE);

  // Establish the dialog box’s border area. A compound border establishes
  // a beveled outer border with an empty inner border, which is used as a
  // margin.

  Border border = BorderFactory.createBevelBorder (BevelBorder.LOWERED);
  Border margin = BorderFactory.createEmptyBorder (10, 10, 10, 10);
  Border cborder = BorderFactory.createCompoundBorder (border, margin);
  getRootPane ().setBorder (cborder);

  // Use a vertical Box as the dialog box’s content pane, to simplify
  // layout.

  Box box = Box.createVerticalBox ();
  setContentPane (box);

  // Add a message (typically identifying the program) label to the box’s
  // top. This label is horizontally centered within the box.

  JLabel label = new JLabel (message);
  label.setAlignmentX (0.5f);
  box.add (label);

  // Add a 30-pixel vertical blank space below the message label to the box
  // (for aesthetic purposes).

  box.add (Box.createVerticalStrut (30));

  // Add a hyperlink to the box’s middle. This hyperlink is horizontally
  // centered within the box.

  JXHyperlink hyperlink;
  hyperlink = new JXHyperlink (new LinkAction (linkText, link));
  hyperlink.setAlignmentX (0.5f);
  box.add (hyperlink);

  // Add a 30-pixel vertical blank space below the hyperlink to the box
  // (for aesthetic purposes).

  box.add (Box.createVerticalStrut (30));

  // Add an OK button to the box’s bottom. This button is horizontally
  // centered within the box. Assign an action listener to hide and dispose
  // the dialog box (when the button is clicked).

  JButton button = new JButton ("OK");
  button.setAlignmentX (0.5f);
  button.addActionListener (new ActionListener ()
         public void actionPerformed (ActionEvent e)
          dispose ();
  box.add (button);

  // Size dialog box to fit the preferred size and layouts of its
  // components.

  pack ();

  // Center the dialog box (when displayed) relative to its parent window.
  // If the parent window is not showing, the dialog box is centered on the
  // screen.

  setLocationRelativeTo (parent);

  // Give input focus to the button.

  button.requestFocusInWindow ();

 private class LinkAction extends AbstractAction
  LinkAction (String linkText, String link)
   // Save the link’s text and the actual link for later recall when the
   // user clicks the hyperlink.

   putValue (Action.NAME, linkText);
   putValue (Action.SHORT_DESCRIPTION, link);

  public void actionPerformed (ActionEvent e)
   // Retrieve the actual link and output link to the console (for test
   // purposes).

   String link = (String) getValue (Action.SHORT_DESCRIPTION);
   System.out.println (link);

   // Launch the default Web browser and have the Web browser display the
   // Web page associated with the link.

   BareBonesBrowserLaunch.openURL (link);

HLDemo depends on an external BareBonesBrowserLaunch class for launching the default web browser. Although I’ve included a copy of this public domain class’s source file with this article’s code, the Bare Bones Browser Launch for Java site provides more information about this class.

Earlier, I mentioned that Swing doesn’t have a hyperlink component. This is unfortunate for those situations in which you cannot use SwingX. (Perhaps you’re using a version of Java prior to J2SE 5.0, for example.) However, it’s not hard to create this component. Subclassing javax.swing.JButton is a good place to start, because JXHyperlink subclasses JButton.

Why does JXHyperlink subclass JButton? A JButton’s visual appearance is text surrounded by a border. By replacing this border with either a matte border (which consists of a single colored line appearing under the button’s text) or an empty border (which removes the colored line by painting background pixels), we end up with a hyperlink. This is demonstrated by my custom Hyperlink class:

class Hyperlink extends JButton
 // Hyperlink color.

 private static final Color LINK_COLOR = Color.blue;

 // This border erases the single underline from the HOVER_BORDER.

 private static final Border LINK_BORDER =
  BorderFactory.createEmptyBorder (0, 0, 1, 0);

 // This border presents a single underline in the LINK_COLOR.

 private static final Border HOVER_BORDER =
  BorderFactory.createMatteBorder (0, 0, 1, 0, LINK_COLOR);

 Hyperlink (final Action action)
  // Replace the default button border with a LINK_BORDER. This border
  // results in no border being displayed. (Borders give buttons their
  // distinctive appearance.)

  setBorder (LINK_BORDER);

  // Do not paint button background in J2SE 5.0’s new Metal Look and Feel.
  // This also applies to Windows XP and other look and feels.

  setContentAreaFilled (false);

  // If this component has a JFrame ancestor, change the mouse pointer to a
  // hand when it is positioned over the button’s text.

  setCursor (Cursor.getPredefinedCursor (Cursor.HAND_CURSOR));

  // Do not paint a focus rectangle (which will not have the correct size
  // anyway) on the button when the button has the focus.

  setFocusPainted (false);

  // The button’s text appears in the color specified by LINK_COLOR.

  setForeground (LINK_COLOR);

  // Establish an action listener to invoke the action’s actionPerformed()
  // method when the user selects the button (or we can think about this as
  // the user selecting a hyperlink).

  addActionListener (new ActionListener ()
        public void actionPerformed (ActionEvent e)
        action.actionPerformed (e);

  // Install a focus listener that underlines the button text when the
  // button receives focus and removes this underline when focus is lost.

  addFocusListener (new LinkFocusListener ());

  // Install a mouse listener that causes focus to shift to the button when
  // the mouse enters the button.

  addMouseListener (new LinkMouseListener ());

  // Obtain the contents of the action’s NAME property as the button’s
  // text. This is the link’s text.

  setText ((String) action.getValue (Action.NAME));

  // Obtain the contents of the action’s SHORT_DESCRIPTION property as the
  // button’s tooltip text. This is the link.

  setToolTipText ((String) action.getValue (Action.SHORT_DESCRIPTION));

 private class LinkFocusListener extends FocusAdapter
  public void focusGained (FocusEvent e)
   ((JComponent) e.getComponent ()).setBorder (HOVER_BORDER);

  public void focusLost (FocusEvent e)
   ((JComponent) e.getComponent ()).setBorder (LINK_BORDER);

 private class LinkMouseListener extends MouseAdapter
  public void mouseEntered (MouseEvent e)
   ((JComponent) e.getComponent ()).requestFocusInWindow ();

SwingX implements its hyperlink component as a specialized button, so when is it appropriate to use either component in a GUI? Here’s a rule that will help you choose the appropriate component: Hyperlinks take you places and buttons perform behaviors (begin a search, for example). However, where space is at a premium (such as in table cells), it’s okay to use hyperlinks to perform behaviors.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020