Concepts / Introduction to Swing Text Components

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.

  • Programming

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?

  • A blank pane with no message

  • The old page still showing, unchanged

  • A readable plain-text message that includes the exception

  • The program crashes and the window closes

Reveal answer
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.

java

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.

URL objectthe address the programholdssetPage callfetches the datafetched datawhat came back from thelocationcontent typetext/plain, text/html, ortext/rtfdisplayed pagewhat the user seespassed inreturns datainterpreted asrendered
How does a URL travel from the program through setPage into the JEditorPane, and what turns the fetched content into what the user sees?

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 typeWhat it holdsHow the pane presents it
text/plainUnstyled textAs plain text with no styling
text/htmlHTML markup, the language of ordinary web pagesAs a page interpreted from its markup
text/rtfStyled text, sometimes called rich textAs 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.

Code walkthrough
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);
    }
}
  1. 1
    Line 2 opens the try block around the one risky call.
  2. 2
    Line 3 asks the pane to fetch and display the page at url.
  3. 3
    Line 4 begins the catch block, which runs only if line 3 throws an exception.
  4. 4
    Line 5 switches the content type to text/plain so the message is shown as plain text.
  5. 5
    Line 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 setPage throws an exception.
  • setContentType switches the pane into plain-text mode before the message is added.
  • setText places the readable message, including the exception text, into the pane.
Output
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.

call setPageinside the try blockload succeeded?page displayedcatch block never runscatch block runsexception handledswitch to text/plainfirst step in catchreadable messageshownincludes the exceptionyesno, exception thrownfirstthen
When setPage throws an exception, which path does control take through the try/catch block, and where does the readable error message get shown instead of the page?

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.

Userclicks the linkJEditorPanereports the clickProgram listenerdecides what to doclicks linkHyperlinkEventsetPage(new URL)shows new page
After a user clicks a link, which objects send and receive the HyperLinkEvent, and in what order does the listener call setPage with the new URL?

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.

Code walkthrough
editPane.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            loadURL(e.getURL());
        }
    }
});
  1. 1
    Line 1 registers an anonymous listener on the pane so the program hears about link events.
  2. 2
    Line 2 defines the method the pane calls when a hyperlink event happens.
  3. 3
    Line 3 checks that the event represents a link that was activated.
  4. 4
    Line 4 passes the target URL to loadURL, which calls setPage and handles any failure.
  5. 5
    Lines 5 to 7 close the if block, the method, and the listener registration.
  • addHyperlinkListener registers 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.
Output
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 like

    A user clicks a link and nothing happens, even though the page contains a valid link.

    Why it fails

    The source states that a JEditorPane does not follow links automatically. A click produces a HyperLinkEvent, and the program must act on it.

    Do this instead

    Register 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 like

    A programmer assumes that after setPage fails, the handler retries the URL.

    Why it fails

    The failure handler does not make an extra attempt to fetch anything. It only changes what the pane shows.

    Do this instead

    If 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 like

    A user sees a message beginning with a sentence about the document and concludes the site returned that text.

    Why it fails

    The message is built by the handler after setPage threw an exception. It is not content from the remote page.

    Do this instead

    Treat 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.

MEDIUM

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 setPage call 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 JEditorPane displays a page when a program calls setPage with 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 JEditorPane does not follow links automatically; a click produces a HyperLinkEvent, and a listener must call setPage to load the new page.
  • To find where a page-loading program went wrong, trace the code path from setPage and check whether the try block completed or the catch block ran.