Introduction to Swing Text Components
A JEditorPane displays a page when a program calls setPage with a URL, and that call can throw an exception that the program should handle.
Predicting What Happens When a Page Fails
A JEditorPane is a Swing component that can display a page when a program gives it a URL. A small web browser can be built from very little code when the display component is a JEditorPane. The sample program SimpleWebBrowser.java follows this pattern: the user types a URL, and the program tries to fetch and show the page at that address. The interesting question for a programmer is not how much code the browser needs, but what happens at each step when something goes wrong.
What do you think happens?
The program calls setPage with a URL that cannot be fetched, so setPage throws an exception. What do you think the user sees in the pane?
Reveal answer
A readable plain-text message that includes the exception
The handler catches the exception rather than letting it escape. It switches the pane to plain-text mode and places a message into it that includes the exception itself, so the user sees a human-readable sentence along with the technical reason.
What One setPage Call Hides
Before reading the code, pause on the central call. If editPane is a JEditorPane and url is a URL object, the statement below is enough to load the page and display it.
This single call hides three jobs. It fetches data from a location, works out what kind of data came back, and renders it. Because fetching can fail, the call is able to throw an exception, and a well-written program wraps it in a method that handles that possibility.
Content Types the Pane Can Handle
A JEditorPane does not render every kind of document. It can handle three content types, and the content type controls how the pane presents what it holds. The three are text/plain, text/html, and text/rtf. The first is unstyled text. The second is HTML, the markup language used for ordinary web pages. The third stands for rich text format, which holds styled text.
| Content type | What it holds | How the pane presents it |
|---|---|---|
| text/plain | Unstyled text | As plain text with no styling |
| text/html | HTML markup, the language of ordinary web pages | As a page interpreted from its markup |
| text/rtf | Styled text, sometimes called rich text | As text that keeps its styling |
The three content types a JEditorPane can handle, as described in the source material
Following the Failure Path Step by Step
Failure is the part of the page-loading code that is easiest to read past. The sample program places the setPage call inside a method named loadURL. Work through the code path as a learner would. The try block contains the one call that may fail. If it succeeds, the catch block never runs and the page appears. If it fails, control jumps to the catch block, which does two things in order: it switches the pane into plain-text mode, and then it places a readable message into the pane. The order matters, because the message is displayed in whatever content type the pane is using at that moment.
private void loadURL(URL url) {
try {
editPane.setPage(url);
} catch (Exception e) {
editPane.setContentType("text/plain");
editPane.setText("Could not load " + url + "\n\n" + e);
}
}- 1Line 2 opens the try block around the one risky call.
- 2Line 3 asks the pane to fetch and display the page at url.
- 3Line 4 begins the catch block, which runs only if line 3 throws an exception.
- 4Line 5 switches the content type to text/plain so the message is shown as plain text.
- 5Line 6 builds the message from the URL and the exception, then displays it in place of the page.
- The try block holds the single call that can fail.
- The catch block runs only when
setPagethrows an exception. setContentTypeswitches the pane into plain-text mode before the message is added.setTextplaces the readable message, including the exception text, into the pane.
On success: the fetched page appears in the pane.
On failure: the pane shows plain text such as: Could not load http://example.com/missing\n\njava.io.IOException: ...The code above is an illustration of the pattern described in the source, not a copy of the sample program's exact listing. Notice that the fallback is not an extra attempt to fetch anything. It only changes what the pane shows. There is no third outcome in this design: a load either finishes and displays the page, or it throws and the handler shows the message.
When a Clicked Link Reaches Your Listener
An HTML page often contains links to other pages, and a browser is expected to follow them. A JEditorPane does not follow links by itself. Instead, when the user clicks a link in a non-editable pane, the pane generates an event of type HyperLinkEvent. The class is spelled HyperlinkEvent in Java's javax.swing.event package. This event is a notification, not a navigation. It tells the program that a link was activated and carries the information the program needs to act on it.
The sequence separates the parts of the job. The user's click is picked up by the pane, which reports it as an event. The program's listener receives that report and makes the decision. Only the third message changes the displayed page, and it is sent by the program rather than the pane. This division explains why a browser built on JEditorPane does nothing with a link until the programmer writes a listener for it.
The source states that a program can register a listener for this event and respond by loading the new page. It does not print a full listener, so the code below is an original illustration of that idea using the standard Swing listener interface. It registers the listener on the pane, checks that the event represents an activated link, and then asks the pane to load the target.
editPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
loadURL(e.getURL());
}
}
});- 1Line 1 registers an anonymous listener on the pane so the program hears about link events.
- 2Line 2 defines the method the pane calls when a hyperlink event happens.
- 3Line 3 checks that the event represents a link that was activated.
- 4Line 4 passes the target URL to loadURL, which calls
setPageand handles any failure. - 5Lines 5 to 7 close the if block, the method, and the listener registration.
addHyperlinkListenerregisters the program's listener with the pane.- The ACTIVATED check ignores other kinds of hyperlink events.
- loadURL reuses the failure-handling method from the previous section.
Clicking a link in the pane causes loadURL to run with the link's target address, which loads the new page or shows the readable error message.Mistakes Beginners Make with Page Loading
Common mistake Assuming the pane follows links on its own
What it looks likeA user clicks a link and nothing happens, even though the page contains a valid link.
Why it failsThe source states that a
JEditorPanedoes not follow links automatically. A click produces aHyperLinkEvent, and the program must act on it.Do this insteadRegister a HyperlinkListener and call setPage with the activated URL inside it.
Common mistake Expecting the catch block to try a second fetch
What it looks likeA programmer assumes that after setPage fails, the handler retries the URL.
Why it failsThe failure handler does not make an extra attempt to fetch anything. It only changes what the pane shows.
Do this insteadIf a retry is wanted, write it explicitly. The handler described in the source only replaces the displayed content with the message.
Common mistake Reading the error message as the page content
What it looks likeA user sees a message beginning with a sentence about the document and concludes the site returned that text.
Why it failsThe message is built by the handler after
setPagethrew an exception. It is not content from the remote page.Do this insteadTreat the message as a sign that the call threw, then read the exception text it includes to find the cause.
Common mistake Forgetting that the content type affects presentation, so an HTML document shown as text/plain looks like raw markup
Locating a Departure from the Expected Route
When a page does not appear as expected, the useful question is where the code path left the expected route. Start at the setPage call. If the page appears, the call succeeded, and the problem is somewhere after loading, perhaps in how the content is interpreted. If the readable message appears instead, the call threw an exception, and the cause is recorded in the error text the handler appends.
A student's browser shows a message reading 'Could not load' followed by an exception description, and the page never appears. Another student's browser loads a page but shows its HTML tags as literal text. Using the code path, identify the branch each program took: which one left the expected success route, and at what decision point did that departure happen?
Hints
- Ask first whether the
setPagecall returned normally or threw an exception. - The readable message is only produced by the catch block.
- Plain-text display of HTML tags points to the content type the pane was using, not to a failed fetch.
Key Takeaways
- A
JEditorPanedisplays a page when a program callssetPagewith a URL, and that single call can throw an exception that the program should handle. - The pane handles text/plain, text/html, and text/rtf, and the content type controls how the content is presented.
- A failed load is caught in a catch block, which switches the pane to plain-text mode and shows a readable message that includes the exception.
- A
JEditorPanedoes not follow links automatically; a click produces aHyperLinkEvent, and a listener must callsetPageto load the new page. - To find where a page-loading program went wrong, trace the code path from
setPageand check whether the try block completed or the catch block ran.