Java Reference
In-Depth Information
28.
public static void
main(String[] args){
29.
SimpleHTMLFrame shf =
new
SimpleHTMLFrame(htmlSource);
30.
shf.showIt("Simple HTML-Display");
31.
}
32.
// Later, the link listener class will be defined here.
33.
}
Program
SimpleHTMLFrame
displays a single HTML document but it does not use
the most important HTML feature: links (
HTML hyperlinks
). When clicking on a
link, nothing happens. In the next section we see how links can be followed.
■
22.2
Using HTML links
In order to trigger a reaction when clicking on a link we need a listener. In Java the
interface
HyperlinkListener
is responsible for monitoring HTML hyperlinks. It
is found in the
javax.swing.event
library and requires the implementation of a
single method:
void
hyperlinkUpdate(HyperlinkEvent hylevt)
The listener is assigned to that component which displays the HTML document, in
our case the
JEditorPanel ediPane
. The listener is assigned using the following
command:
ediPane.addHyperlinkListener(HyperlinkListener hyLis)
After the listener is assigned to the panel, it is notified by the runtime system if a
link is clicked on, i.e. its
hyperlinkUpdate
method is called. The runtime system
also generates a
HyperlinkEvent
object and passes it to
hyperlinkUpdate
as an
argument.
The programmer has to insert the code into
hyperlinkUpdate
which is to be
executed as a reaction to selecting the link. In our example we want to display that
page to which the link refers. We first check whether the event type is
ACTIVATED
,
i.e. whether the link has been selected. Other event types are
ENTERED
and
EXITED
.
This test is done by inspecting the hyperlink event object
hylevt
if
(hylevt.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
Next, we extract the URL to which the link is pointing:
URL newPage = hylevt.getURL()
Then this URL is passed to the editor pane by:
ediPanel.setPage(newPage)
The new web page is displayed in the editor pane. Methods that access web
pages can throw exceptions, therefore calls of such methods have to be embedded
into
try-catch
blocks. In our example, we write a message to the console if an
Search WWH ::
Custom Search