|
|
Using Swing Components |
Here's a picture of an application that shows one of each of Swing's text components.The
Try this:
- Compile and run the application. The source code is in
TextSamplerDemo.java. You will also needTextSamplerDemoHelp.html,Pig.gif,dukeWaveRed.gif, andsound.gif.
See Getting Started with Swing if you need help.- Type text in the text field and press Return. Do the same with the password field.
- Select and edit text in the text area and the text pane. Use special keyboard keys to cut, copy, and paste text.
- Try to edit the text in the editor pane, which has been made uneditable with a call to
setEditable.- Scroll the text pane to find an example of an embedded component.
TextSamplerDemoprogram is fairly basic in how it uses the text components: It simply creates each one, configures it, and adds it to the application's frame.This section shows you the code used in
TextSamplerDemoto create each text component. With the information in this short section alone, you can quickly learn everything necessary to include the various text components in a program and interact with them on a basic level. For information regarding more complex uses of the various text components, continue with the next section, General Rules for Using Text Components.This section has five parts:
- An Example of Using a Text Field
- An Example of Using a Password Field
- Using a Text Area
- Using an Editor Pane to Display Text from a URL
- An Example of Using a Text Pane
An Example of Using a Text Field
TextSamplerDemocontains a text field in the upper left corner of the main frame. Here's the code that creates theJTextField.As with buttons, you can set an action command and register an action listener on a text field. Here's theJTextField textField = new JTextField(10); textField.setActionCommand(textFieldString); textField.addActionListener(this);actionPerformedmethod implemented by the text field's action listener, which is shared with the program's password field. TheactionPerformedmethod simply copies the text field's contents to a label.For descriptions of thepublic void actionPerformed(ActionEvent e) { String prefix = "You typed \""; if (e.getActionCommand().equals(textFieldString)) { JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\""); } else { JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\""); } }JTextFieldconstructor and thegetTextmethod used by this demo, refer to How to Use Text Fields. That section also includes information and examples of customized text fields, including how to write a validated field.An Example of Using a Password Field
JPasswordFieldis a subclass ofJTextFieldthat, instead of showing the actual character the user types, shows another character such as an asterisk '*'. This type of field is useful for prompting users to enter passwords when logging in or validating their identity. Here's the code fromTextSamplerDemothat creates the password field and registers an action listener on it:This code is the similar to that used to create the text field. The password field shares the text field's action listener, which uses these three lines of code to copy the password field's content to a label:JPasswordField passwordField = new JPasswordField(10); passwordField.setActionCommand(passwordFieldString); passwordField.addActionListener(this);Notice that this code uses theString prefix = "You typed \""; ... JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\"");getPasswordmethod to get the contents of the password field instead ofgetText. Providing a Password Field explains why and provides additional information about password fields. Remember that password fields are text fields, so the information covered in How to Use Text Fields pertains to password fields as well.Using a Text Area
A text area displays multiple lines of text and allows the user to edit the text with the keyboard and mouse. Here'sTextSamplerDemo's code that creates itsJTextArea:The constructor used in this example to create the text area is similar to those used to create the text field and password field. The text area constructor requires two integer arguments: the number of rows and the number of columns in the text area. These numbers are used to calculate the text area's preferred size. As with the column parameter for fields, think of these numbers as hints.JTextArea textArea = new JTextArea(5, 10); textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setText( "This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." ); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250)); areaScrollPane.setBorder(/*...create border...*/);Next the code set the text area's font followed by the text area's initial text. As the text area's initial text says, that although a text area can display text in any font, all of the text is in the same font.
The next two statements deal with line wrapping. The first is a call to
setLineWrap, which turns line wrapping on. By default, a text area doesn't wrap lines. Instead it shows all the text on one line, and if the text area is within a scroll pane, allows itself to be scrolled horizontally. The second is a call tosetWrapStyleWord, which tells the text area to wrap lines between words.The next bit of code creates a scroll pane, puts the text area in it, sets the scroll pane's preferred size, and establishes the scroll pane's borders. A text area is typically managed by a scroll pane. If you put a text area in a scroll pane, be sure to set the scroll pane's preferred size, rather than the text area's preferred size. [PENDING: why is this so?]
This section is the only section about using a text area provided by this tutorial because
JTextAreais a straightforward class to use. If you are interested in customizing a text area, you can apply what you learn in General Rules about Using Text Components. Be sure to check the Summary of Text section for relevant API and other examples that useJTextArea.Using an Editor Pane to Display Text from a URL
JEditorPaneis the foundation for Swing's styled text components.TextSamplerDemouses an editor pane like many programs do: to display uneditable help information initialized from a URL that points to an HTML file,TextSamplerDemoHelp.html.Here's the code that creates the editor pane in
TextSamplerDemo:The code uses the default constructor to create the editor pane, then callsJEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false); ...create a URL object for the TextSamplerDemoHelp.html file... try { editorPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); }setEditable(false)so the user cannot edit the text. Next, the code creates theURLobject, and calls thesetPagemethod with it. ThesetPagemethod opens the resource pointed to by the URL and figures out the format of the text (which in the example is HTML). If the text format is known, the editor pane initializes itself with the text found at the URL.The code that creates the URL is missing from the above code sample and is interesting in and of itself. Here it is:
This code uses system properties to compute aString s = null; try { s = "file:" + System.getProperty("user.dir") + System.getProperty("file.separator") + "TextSamplerDemoHelp.html"; URL helpURL = new URL(s); /* ... use the URL to initialize the editor pane ... */ } catch (Exception e) { System.err.println("Couldn't create help URL: " + s); }fileURL for the help file. Because of the security restrictions implemented by most browsers, this code won't work in applets. Instead, use the applets codebase to compute anhttpURL.Like text areas, editor panes are typically managed by a scroll pane:
Note that the scroll pane's preferred size is set, not the editor pane's.JScrollPane editorScrollPane = new JScrollPane(editorPane); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(250, 150));This short section shows a typical and basic use of editor panes. However, many programs need to use editor panes in more sophisticated ways. To learn more, first read the next section, General Rules for Using Text Components, then proceed to How to Use Editor Panes and Text Panes.
An Example of Using a Text Pane
The final text component in our basics tour isJTextPane, which is aJEditorPanesubclass. Here's code fromTextSamplerDemothat creates and initializes a text pane.Briefly, this code hard-codes the initial text into an array and creates and hard-codes several styles--objects that represent different paragraph and character formats--into another array. Next, the code loops over the arrays, inserts the text into the text pane, and specifies the style to use for the inserted text.JTextPane textPane = new JTextPane(); String[] initString = { /* ... fill array with initial text ... */ }; String[] initStyles = { /* ... fill array with names of styles ... */ }; //Create the styles we need initStylesForTextPane(textPane); Document doc = textPane.getDocument(); //Load the text pane with styled text try { for (int i=0; i < initString.length; i++) { textPane.setCaretPosition(doc.getLength()); doc.insertString(doc.getLength(), initString[i], textPane.getStyle(initStyles[i])); textPane.setLogicalStyle(textPane.getStyle(initStyles[i])); } } catch (BadLocationException ble) { System.err.println("Couldn't insert initial text."); }Although this makes for an interesting example and concisely shows off several features of
JTextPane, "real-world" programs aren't likely to initialize aJTextPanethis way. Instead, a production-quality program would apply a bootstrapping process, whereby a basicJTextPanewould be used to create and save a document, which could then be read into theJTextPaneas the program is developed.This section showed the code used by
TextSamplerDemoto create its text pane, but doesn't describe anything. For details about text panes and useful information about when to use a text pane versus when to use an editor pane, read How to Use Editor Panes and Text Panes. (But only after you're comfortable with the information in General Rules for Using Text Components.)
|
|
Using Swing Components |