Goal
Given a simple implementation of a WEB browser, using java Swing components and AWT event handling, add to the WEB browser the following
functionalities:
- redirection to home page - Home JButton
- redirection to the previous page - Back JButton
- redirection to the next page - Forward JButton
JEditorPane
JEditorPane is sort of a text
area that can display text derived from different file formats. The built-in
version supports HTML and RTF (Rich Text Format) only, but you can build "editor
kits" to handle special purpose applications. In principle, you choose the type
of document you want to display by calling
setContentType and
specify a custom editor kit via
setEditorKit. Note that unless you
extend it, legal choices are "text/html" (the default), "text/plain" (which is
also what you get if you supply an unknow type), and "text/rtf".
In practice, however,
JEditorPane is almost always used for
displaying HTML. If you have plain text, you might as well use
JTextField. RTF support is pretty primitive. You put content into
the
JEditorPane one of four ways:
- The most common way to build a JEditorPane is via the
constructor, where you supply either a URL object or a
String corresponding to a URL (which, in applications, could be a
file: URL to read off the local disk). Note that this throws
IOException, so needs to be in a
try/catch block.
- Secondly, you can use setPage on a JEditorPane
instance that was created via the empty constructor. The setPage
method also takes either a URL object or a String,
and also throws IOException. This is generally used when the
content is determined at run-time by some user action.
- Thirdly, you can use setText on a JEditorPane
instance, supplying a String that is the actual content,
- Fourthly, but only occasionally, you use read, supplying an
InputStream and an HTMLDocument object.
In
principle, a
JEditorPane can be editable, but in practice it tends
to look pretty poor, so it is most often used simply to display HTML, and you
call
setEditable(false) on it. Finally, as with all Swing
components, scrolling is realized by dropping it in a
JScrollPane.
Hypertext Links
In most cases, you use a non-editable
JEditorPane to display HTML text. In such a case, you can detect
when the user selects a link, can determine which link was selected, and can
replace the contents of the
JEditorPane with the document at the
specified URL (by using setPage). To do this, attach a
HyperlinkListener (notice that it is
HyperlinkListener, not
HyperLinkListener) via
addHyperlinkListener,
and implement the
hyperlinkUpdate method to catch events. Once you
get the event, you need to look up its specific type via
getEventType and compare that to
HyperlinkEvent.EventType.ACTIVATED. This last point was not needed
in early releases of Swing, but as of Java 1.2, if you neglect it, then the link
will be followed whenever the mouse simple
moves over the link.