package com.onaro.util.jfc.browser; import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JLabel; import javax.swing.SwingConstants; import com.onaro.util.jfc.DataField; import com.onaro.util.jfc.Highlighter; import com.onaro.util.jfc.ISummaryField; import com.onaro.util.jfc.JComponentHtmlBuilder; import com.onaro.util.jfc.Messages; import com.onaro.util.jfc.Resources; import com.onaro.util.jfc.TextComponentFactory; import com.onaro.util.jfc.TextComponentFactory.LabelFont; import com.onaro.util.launch.LaunchUrl; /** * An {@link ISummaryField} component that looks like a web link. * Clicking it opens a web browser with the given URL. */ public class UrlField extends JLabel implements ISummaryField { private static final long serialVersionUID = 1L; private String url = null; /** * Creates a {@link UrlField}. */ public UrlField() { super(Resources.INSTANCE.getExternalLinkIcon()); setHorizontalTextPosition(SwingConstants.LEADING);// Put icon to the right of the text addMouseListener (new LinkHandler()); } /** * Creates a {@link DataField} * @param name of the field, for testing purposes */ public UrlField (String name) { this(); setName (name); } /** * Creates a {@link DataField} * @param name of the field, for testing purposes * @param font {@link LabelFont} */ public UrlField (String name, LabelFont font) { this (name); setFont (font.getFont()); } /** * Defines the text this component will display and the * URL that will be visited when the component * is clicked. * * @param url a URL string */ public void setLink (String url) { setLink (url, url); } /** * Defines the text this component will display and the * URL that will be visited when the component * is clicked. * * @param url a URL string * @param text displayed by the component */ public void setLink (String url, String text) { this.url = url; if (url == null) { clear(); } else { setText (new JComponentHtmlBuilder() .append (JComponentHtmlBuilder.anchor (text)) .getText()); setToolTipText (Messages.INSTANCE.getLinkFieldDescription (text)); setCursor (Cursor.getPredefinedCursor (Cursor.HAND_CURSOR)); } } /** * Gets the URL. * @return URL string */ public String getUrl() { return url; } /** * Clears and disables the field. */ @Override public void clear() { url = null; setText (null); setCursor (null); setEnabled (false); } @Override public boolean isHighlighted() { return Highlighter.isHighlighted (this); } @Override public void setHighlight (boolean doHighlight) { Highlighter.setHighlighted (this, doHighlight); TextComponentFactory.renderHighlight (this, doHighlight); } private class LinkHandler extends MouseAdapter { @Override public void mouseClicked (MouseEvent evt) { LaunchUrl.launch (url); } } }