Text ComponentsText components are the most complex Swing components, but they are fun to use, and you need one for the assignment. The required user help is presented in one of these components, probably the JTextEditor. These are the five text components:
The following example shows how you might present user help information in HTML format. Listing 14.3 demonstrates how to display an HTML file using the JtextPane component. Listing 14.3 How to Display an HTML Fileimport javax.swing.*; import java.awt.*; public class UserHelp { public UserHelp() { JTextPane pane = new JTextPane(); JScrollPane scroller = new JScrollPane(); scroller.getViewport().add(pane); JFrame frame = new JFrame("Look-Feel"); frame.getContentPane().add(scroller, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setSize(800,500); frame.setVisible(true); String htmlDocument = "userHelp.html"; try { java.net.URL url = new java.net.URL("file:" + System.getProperty("user.dir") + System.getProperty("file.separator") + htmlDocument); pane.setPage(url); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) {} //Create the top-level container and add contents to it. UserHelp app = new UserHelp(); } } Listing 14.3 produces a simple screen. (Refer to Figure 5.1 in Chapter 5, "Documentation and Javadoc Comments.") Be aware that the JTextPane is not an advanced browser tool. It displays plain HTML fine, but doesn't do well with advanced features, such as cascading style sheets (CSS), JavaScript, or Extensible Hypertext Markup Language (XHTML). There are many interesting operations you can perform on text components. A few are shown in the following example: JTextComponent textComponent = new JTextArea("Do not act like a knucklehead."); int textLength = textComponent.getDocument().getLength(); // grab all the text String allText = textComponent.getText(); try { // grab first 5 characters text = textComponent.getText(0, 5); // grab last 5 characters text = textComponent.getText(textLength-5, 5); // delete characters textComponent.remove(3, 4); // replace characters textComponent.insertString(3, "four", null); } catch (BadLocationException ble) {} The following is another way to programmatically manipulate the String in a text component: JTextPane textPane = new JTextPane(); // grab root element Element rootDoc = textPane.getDocument().getDefaultRootElement(); // How many paragraphs? int paragraphs = rootDoc.getElementCount(); // grab each paragraph for (int i=0; i<paragraphs; i++) { Element para = section.getElement(i); int start = para.getStartOffset(); int end = para.getEndOffset(); try { String text = rootDoc.getText(start, end-start); } catch (BadLocationException ex) {} }
|