Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Hyperlinks

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",
          "HLDemo 1.0",
          "by Jeff Friesen",
          "http://www.javajeff.mb.ca");

  // 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 ()
 {
  try
  {
   // 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.

  • + Share This
  • 🔖 Save To Your Account