001 /*
002 * Copyright 2002-2004 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.springframework.richclient.text;
017
018 import java.net.URL;
019
020 import javax.swing.JTextPane;
021 import javax.swing.event.HyperlinkEvent;
022 import javax.swing.event.HyperlinkListener;
023
024 import org.springframework.richclient.util.BrowserLauncher;
025
026 /**
027 * An implementation of HyperlinkListener that will open a web browser
028 * when a URL is activated or, when an anchor link is activated scoll the
029 * pane to display the anchor location.
030 *
031 * @author Oliver Hutchison
032 */
033 public class DefaultHyperlinkActivationHandler implements HyperlinkListener {
034
035 /**
036 * Called when the user clicks on an anchor e.g. <br>
037 * <a href="#top">Go to Top</a>.
038 * <p>
039 * This default implementation will scroll the source pane so that the anchor
040 * target becomes visible.
041 */
042 protected void handleAnchorActivated(HyperlinkEvent e, String anchor) {
043 ((JTextPane)e.getSource()).scrollToReference(anchor);
044 }
045
046 /**
047 * Called when the user clicks on a URL link e.g. <br>
048 * <a href="http://some.site">Go to Some Site</a>.
049 * <p>
050 * This default implementation attempt to open the link in the systems
051 * default browser.
052 */
053 protected void handleUrlActivated(HyperlinkEvent e, URL url) {
054 BrowserLauncher.openURL(url);
055 }
056
057 /**
058 * Called when the user clicks on a link that is neither an anchor or URL. e.g<br>
059 * <a href="whatever">what ever</a>.
060 * <p>
061 * This default implementation does nothing.
062 */
063 protected void handleOtheActivated(HyperlinkEvent e) {
064 // do nothing
065 }
066
067 public void hyperlinkUpdate(HyperlinkEvent e) {
068 if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
069 if (e.getDescription().startsWith("#")) {
070 handleAnchorActivated(e, e.getDescription().substring(1));
071 }
072 else if (e.getURL() != null) {
073 handleUrlActivated(e, e.getURL());
074 } else {
075 handleOtheActivated(e);
076 }
077 }
078 }
079 }