Java Reference
In-Depth Information
Example 10•20: ComponentTree.java (continued)
" height: " + c.getHeight());
}
else {
msgline.setText("component is not showing");
}
}
});
// Now that we've set up the tree, add it to the scrollpane
scrollpane.setViewportView(tree);
// Finally, set the size of the main window, and pop it up.
frame.setSize(600, 400);
frame.setVisible(true);
}
}
A Simple Web Browser
The two previous examples have shown us the powerful JTable and JTree com-
ponents. A third powerful Swing component is javax.swing.text.JTextComponent
and its various subclasses, which include JTextField , JTextArea , and JEditor-
Pane . JEditorPane is a particularly interesting component that makes it easy to dis-
play (or edit) HTML text.
As an aside, it is worth noting here that you do not have to create a JEditorPane
to display static HTML text. In Java 1.2.2 and later, the JLabel , JButton , and other
similar components can all display multiline, multifont formatted HTML labels. The
trick is to begin the label with the string “<html>”. This tells the component to
treat the rest of the label string as formatted HTML text and display it (using an
internal JTextComponent ) in that way. You can experiment with the feature using
the ShowComponent program; use it to create a JButton component and set the
text property to a value that begins with “<html>”.
Example 10-21 is a listing of WebBr owser.java ,a JFrame subclass that implements
the simple web browser shown in Figure 10-17. The WebBrowser class uses the
power of the java.net.URL class to download HTML documents from the Web
and the JEditorPane component to display the contents of those documents.
Although defined as a reusable component, the WebBrowser class includes a
main() method so that it can be run as a standalone application.
Example 10-21 is intended as a demonstration of the power of the JEditorPane
component. The truth is, however, that using JEditorPane is quite trivial: simply
pass a URL to the setPage() method or a string of HTML text to the setText()
method. So, when you study the code for this example, don't focus too much on
the JEditorPane . You should instead look at WebBrowser as an example of pulling
together many Swing components and programming techniques to create a fairly
substantial GUI. Points of interest include the enabling and disabling of Action
objects and the use of the JFileChooser component. The example also uses a
JLabel as an application message line, with a javax.swing.Timer that performs a
simple text-based animation in that message line.
Search WWH ::




Custom Search