Java Swing phần 7 pps

99 217 0
Java Swing phần 7 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Java Swing - O’Reilly - 595 - public JPasswordField() Creates a new password field with zero columns. public JPasswordField(String text) Creates a new text field displaying the input text (using the echo character). public JPasswordField(int columns) Creates a new text field with the requested number of columns. public JPasswordField(String text, int columns) Creates a new text field with the specified number of columns, displaying the input text (using the echo character). public JPasswordField(Document doc, String text, int columns) This constructor (called by all the others) creates a new text field that uses the specified document model, displays the specified string of text (using the echo character), and contains the requested number of columns. The echo character is set to "*" by this constructor. 19.1.4.3 Data Protection Methods public void cut() public void copy() These methods are overridden to disable cut and copy behavior in password fields. They simply call getToolkit().beep(). If these methods were not overridden, it would be possible for hidden passwords to be copied from password fields and pasted into nonhidden fields. public string getText(int offs, int len) throws BadLocationException Defined in this class only for the purpose of being marked as deprecated. The getPassword() method should be used instead. 19.1.4.4 Miscellaneous Methods public boolean echoCharIsSet() Indicates whether or not an echo character has been set. Note that a default echo character (*) is defined, so this method always returns true unless the echo character is explicitly set to "\u0000." 19.1.5 The JTextArea Class The JTextArea class is modeled after AWT's TextArea, providing much of the same functionality. Generally, it is used to allow the user to enter a textual message, or to display textual information to the user. Figure 19.7 shows a JTextArea. Java Swing - O’Reilly - 596 - Figure 19.7. JTextArea One significant change from the AWT TextArea is that JTextArea does not directly support scrolling. However, adding the ability to scroll the contents of a JTextArea is very simple; just add the JTextArea to the viewport of a JScrollPane (JScrollPanes are described in more detail in Chapter 11). JTextArea implements Scrollable, so a scroll pane can be intelligent about scrolling it. 19.1.5.1 Properties JTextArea defines properties shown in Table 19.6. The document property defaults to a new PlainDocument. AccessibleJTextArea extends the JTextComponent.AccessibleJTextComponent class. Table 19.6, JTextArea Properties Property Data Type get is set bound Default Value document* Document PlainDocument UIClassID* String "TextAreaUI" accessibleContext* AccessibleContext AccessibleJTextArea columns int 0 font* Font From superclass lineCount int From document lineWrap boolean false managingFocus* boolean true minimumSize* Dimension Preferred size (if columns or rows !=0) or super.minimumSize preferredScrollableViewportSize* Dimension See comments below preferredSize* Dimension See comments below rows int 0 scrollableTracksViewportWidth* boolean see comments below tabSize int 8 wrapStyleWord boolean false See also properties from the javax.swing.text.JTextComponent class (Table 19.1) The columns attribute specifies the number of columns to be displayed by the component. For variable-width fonts, the width of each column is based on the width of the lowercase character m. The font property is listed here because getFont() has been overridden to revalidate the component, allowing it to resize based on the size of the new font. lineCount provides access to the number of lines contained by the text area's document. What constitutes a "line" is document- dependent, but typically a line is a sequence of characters that end with a \n. This is not the same as rows, which is simply the number of rows of text displayed by the component. The lineWrap property indicates whether or not text should wrap around to the next line when the end of a line is reached. This should be set to true when using a nonscrollable JTextArea (otherwise, text which runs off the edge of the component cannot be seen) and set to false when Java Swing - O’Reilly - 597 - horizontal scrolling is enabled. Remember that scrolling is enabled by placing the text area in a JScrollPane. The wrapStyleWord property allows you to specify how the text should be broken up if lineWrap is true. By default, wrapStyleWord is set to false, so lines are broken on character boundaries. If set to true, lines are only broken on word boundaries. Figure 19.8 shows a JTextArea with wrapStyleWord set to true. Figure 19.8. JTextArea with wrapStyleWord set to true The managingFocus property is always true. This indicates that pressing the TAB key does not cause focus to be moved to the next component (it just inserts a tab). If you want to be able to use the TAB key to exit the text area, you'll need to subclass JTextArea and override isManagingFocus() to return false. The minimumSize property is returned as the preferredSize if either rows or columns is nonzero. Otherwise, it is as defined in the superclass. preferredScrollableViewportSize reflects the preferred size of the component if used in a JScrollPane. It is returned as the column width times the number of columns and the row height times the number of rows. If either of these values is zero, the value returned by the superclass method is used. The preferredSize property uses the superclass implementation, but adjusts the width and height if the columns and rows properties are set. The scrollableTracksViewportWidth property will be true if lineWrap is true. If not, its value is determined by the superclass. The tabSize property specifies the number of characters that a tab character should expand to. 19.1.5.2 Events JTextArea does not fire any new event types. It fires PropertyChangeEvents when its lineWrap, tabSize, or wrapStyleWord properties change. The names of the properties fired by this class do not follow the standard property naming convention. The names used are "LineWrap," "TabSize," and "WrapStyleWord." 19.1.5.3 Constructors public JTextArea() Creates a default text area. public JTextArea(Document doc) Creates a text area using the input document. public JTextArea(int rows, int columns) Creates a text area with the specified number of rows and columns. Java Swing - O’Reilly - 598 - public JTextArea(String text) Creates a text area displaying the specified text. public JTextArea(String text, int rows, int columns) Creates a text area with the specified number of rows and columns displaying the given text. public JTextArea(Document doc, String text, int rows, int columns) Uses the given Document, populated with the given text to create a text area of the specified size. All of the other constructors use this one. 19.1.5.4 Text Manipulation Methods The following convenience methods make it easy to modify the contents of the text area's document model. public void append(String str) Appends the given text to the end of the document. public void insert(String str, int pos) Inserts the specified text at the given position (offset from the beginning of the document). To insert text at the beginning of the document, use a value of 0 for the second argument. public void replaceRange(String str, int start, int end) Uses the input text to replace a section of the document, beginning with the character at the start position and ending with the character at the end position. 19.1.5.5 Line Transformation Methods These methods can be used to find the character offset of a given line (see the distinction between line and row in the Properties section earlier in the chapter) and vice-versa. Note that the first line of the document is line 0. public int getLineEndOffset(int line) throws BadLocationException Returns the character offset (from the beginning of the document) which marks the end of the specified line. This is actually the offset of the first character of the next line. public int getLineOfOffset(int offset) throws BadLocationException Returns the line number that contains the given character offset (from the beginning of the document). public int getLineStartOffset(int line) throws BadLocationException Returns the character offset (from the beginning of the document) that marks the beginning of the specified line. Java Swing - O’Reilly - 599 - The following example shows how these three methods work: // OffsetTest.java // import javax.swing.*; import javax.swing.text.*; public class OffsetTest { public static void main(String[] args) { // Create a JTextField with three lines of text JTextArea ta = new JTextArea(); ta.setLineWrap(true); ta.append("The first line.\n"); ta.append("Line Two!\n"); ta.append("This is the 3rd line of the document."); // Print some results . . . try { System.out.println(ta.getLineEndOffset(0) + " (end of line 0)"); System.out.println(ta.getLineStartOffset(1) + " (start of line 1)"); System.out.println(ta.getLineOfOffset(20) + " (line containing position 20)"); int theEnd = ta.getLineEndOffset(2); System.out.println(theEnd + " (end of last line)"); System.out.println(ta.getText(ta.getLineEndOffset(2), 2)); } catch (BadLocationException ex) { System.out.println("BAD!"); } // Layout . . . JFrame f = new JFrame(); f.addWindowListener(new BasicWindowMonitor()); f.setContentPane(ta); f.setSize(150, 150); f.setVisible(true); } } When run, this little program produces the following output, along with the frame shown in Figure 19.9. Note that the `\n' counts as a character in the document. Figure 19.9. OffsetTest frame 16 (end of line 0) 16 (start of line 1) 1 (line containing position 20) 64 (end of last line) BAD! Java Swing - O’Reilly - 600 - The last line of output shows that getLineEndOffset() returns an index of the character after the last character in the specified line. When called on the last line, this offset is not a valid document offset. 19.1.5.6 Protected Methods protected Document createDefaultModel() Creates a default model object to be used if one is not provided as a constructor argument. The default object created by JTextArea is a PlainDocument. protected int getColumnWidth() Returns the width (in pixels) of a single column. The default implementation returns the width of the character m in the current font. It's important to realize that unless you are using a fixed-width font (e.g., Courier), this method is only useful for determining a maximum column width. protected int getRowHeight() Returns the height (in pixels) of each row. This is defined by the height of the current font. protected String paramString() Returns the parameter string used to represent this text area as a string. This is the result of super.paramString() with the number of rows and columns in the component appended to the string. 19.1.5.7 Understanding JTextArea Sizing The following code produces a result you might not expect: // UnstableTA.java // import javax.swing.*; import java.awt.*; public class UnstableTA { public static void main(String[] args) { JTextArea area = new JTextArea(3, 10); JFrame f = new JFrame(); f.addWindowListener(new BasicWindowMonitor()); f.getContentPane().setLayout(new FlowLayout()); f.getContentPane().add(area); f.setSize(200, 110); f.setVisible(true); } } Java Swing - O’Reilly - 601 - At first glance, this looks fine. [3] However, things start getting a little strange if you enter text into the area. Figure 19.10 shows the display when it's first displayed and then after adding some data to the text area. [3] Prior to the Swing 1.0.2 release, this example would have produced a tiny 1x1 character text area. Figure 19.10. Unstable JTextArea—size changes after adding data The text area expanded both horizontally and vertically to accommodate the text we entered. Chances are this is not the behavior you'd like. Fortunately, there are several strategies we can use to get more usable results. They include: • Place the JTextArea in a JScrollPane. • Explicitly specify the preferredSize of the JTextArea. • Use a layout manager that doesn't use the preferredSize of its components. The first strategy is useful when you want to fix the size of the displayed area without restricting the total amount of text the user can enter. A simple change to our previous example accomplishes this goal. Just replace the old add() call with: f.getContentPane().add(new JScrollPane(area)); The second strategy gives you complete control over the size of the text area. If you just want the size to reflect the dimensions you supplied in the constructor, you can use the preferredScrollableViewportSize , which uses the rows and columns you specified, and add in the text area's insets. Adding the following lines to our example is one way to make this change: Dimension d = area.getPreferredScrollableViewportSize(); Insets in = area.getInsets(); d.width = d.width + in.left + in.right; d.height = d.height + in.top + in.bottom; area.setPreferredSize(d); The last strategy allows the text area to fill the available space. Note that using this strategy does not tie the size of the text area to the specified number of rows and columns. The JTextArea grows to fill the space available in the current layout. To see an example of this strategy, change the setLayout() and add() calls from the original example to this: f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(area, BorderLayout.CENTER); Another common strategy is to combine the first and third options to create a scrollable text area that fills all available space. Java Swing - O’Reilly - 602 - 19.1.6 The JEditorPane Class JEditorPane is an extension of JTextComponent capable of displaying various types of content, such as HTML and RTF. It is not intended to be used as a full-featured web browser, but can be used to view simple HTML and is ideal for integrating online help into Java applications. JEditorPanes work closely with EditorKit objects which are plugged into the editor pane to customize it for a particular content type. Without an EditorKit telling it how to work, a JEditorPane can't function. In this chapter, we are going to ignore this complexity and just look at how we might use a JEditorPane as a very simple web browser. We'll get into the details of JEditorPane and EditorKit in Chapter 24. Figure 19.11. JEditorPane showing an HTML page Figure 19.11 shows the JEditorPane in action, displaying a portion of the old style javadoc for the JEditorPane class. Here's the code: // HTMLExample.java // import javax.swing.*; import javax.swing.event.*; import java.io.*; public class HTMLExample { public static void main(String[] args) { JEditorPane pane = null; try { Java Swing - O’Reilly - 603 - pane = new JEditorPane(args[0]); } catch (IOException ex) { ex.printStackTrace(System.err); System.exit(1); } pane.setEditable(false); // Add a hyperlink listener final JEditorPane finalPane = pane; pane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent ev) { try { if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) finalPane.setPage(ev.getURL()); } catch (IOException ex) { ex.printStackTrace(System.err); } } }); JFrame frame = new JFrame(); frame.addWindowListener(new BasicWindowMonitor()); frame.setContentPane(new JScrollPane(pane)); frame.setSize(350,400); frame.setVisible(true); } } We've created a very minimal HTML browser. [4] In a real application, you'd want to do things like change the cursor while new pages are being loaded and handle exceptions more elegantly. The anonymous inner class in this example shows a quick way to enable hyperlinks when viewing text in a JEditorPane. We'll look at the classes and methods used here in the next few pages. [4] This simple browser will not handle all HTML pages. The Swing html package is still being enhanced to provide better HTML support. However, significant progress has been made since earlier releases. 19.1.6.1 Properties Table 19.7 shows the properties defined by JEditorPane. The accessibleContext property depends on the type of EditorKit in use. If an HTMLEditorKit is installed, a special AccessibleJEditorPaneHTML object will be used. Otherwise, its superclass, AccessibleJEditorPane is used. AccessibleJEditorPane extends the JTextComponent.AccessibleJTextComponent class. Table 19.7, JEditorPane Properties Property Data Type get is set bound Default Value UIClassID* String "EditorPaneUI" accessibleContext* AccessibleContext AccessibleJEditorPane or AccessibleJEditorPaneHTML contentType String From editorKit editorKit EditorKit null managingFocus* boolean true page URL null scrollableTracksViewportWidth* boolean true Content Type Class See also properties from the javax.swing.text.JTextComponent class (Table 19.1) Java Swing - O’Reilly - 604 - The contentType property reflects the type of content displayed by the editor. This value is taken from the installed EditorKit and typically has values such as "text/plain," "text/html," and "text/rtf." The editorKit supplies everything needed to work with a particular content type. EditorKit and its default implementations are described in detail in Chapter 24. ManagingFocus is set to true for JEditorPane, reflecting the fact that using the TAB key will not cause focus to move to the next component. The page property specifies the URL of the current page being displayed. The scrollableTracksViewportWidth property is set to true in this class. 19.1.6.2 Events JEditorPane s fire a new type of event called a HyperlinkEvent. Typically, this is fired when the user clicks on a hyperlink in the currently displayed document; the program normally responds by loading a new page. To support this new event type, a new event class and listener interface are available in the javax.swing.event package. These are described briefly at the end of this section. As you'd expect, the following methods are provided for working with these events. public synchronized void addHyperlinkListener(HyperlinkListener listener) public synchronized void removeHyperlinkListener(HyperlinkListener listener) public void fireHyperlinkUpdate(HyperlinkEvent e) JEditorPane objects also fire PropertyChangeEvents when the editorKit property is changed. 19.1.6.3 Constructors The following constructors are provided. Note that the last two may throw an IOException if they are unable to load the specified URL. public JEditorPane() Creates an empty pane. public JEditorPane(String url) throws IOException public JEditorPane(URL initialPage) throws IOException Create a pane displaying the specified URL. contentType and editorKit are set based on the content type of the URLConnection created from the given URL. Because these constructors attempt to open a URL, they may throw an IOException if the URL cannot be found. 19.1.6.4 EditorKit Methods The following methods are available for managing EditorKits. You won't need to use any of these methods if you're not defining your own EditorKits for working with various content types. public EditorKit getEditorKitForContentType(String type) Returns an EditorKit for the given content type. An attempt is made to create the appropriate EditorKit if one has not already been set (via a call to [...]... the mappings shown in Table 19.8 Table 19.8, Default Content-Type Mappings Content Type application/rtf text/plain text/html text/rtf [5] Class javax .swing. text.rtf.RTFEditorKit javax .swing. JEditorPane.PlainEditorKit[5] javax .swing. text.html.HTMLEditorKit javax .swing. text.rtf.RTFEditorKit A package private subclass of DefaultEditorKit protected EditorKit createDefaultEditorKit() Called to create a default... example: [7] We use a very simple subclass of AbstractDocument called PlainDocument in this example This class will be defined later in this chapter For now, there's nothing special you need to know about this class // LockingExample .java // import javax .swing. *; import javax .swing. text.*; // Sample program showing how AbstractDocument locking works public class LockingExample { - 629 - Java Swing -... italics Name: John Elway Number: 7 Team: Denver Broncos // This came from the resolving parent Colors: java. awt.Color[r=0,g=0,b=255] & java. awt.Color[r=255,g=200,b=0] Colors Defined?: false // We get colors from res parent, but it's not defined -Contains number 8: false // containsAttribute() must match key AND value - 621 - Java Swing - O’Reilly Contains number 7: true -Copy works: true ... displaying diagnostic messages to a user Three types of messages (informational, warning, and error) are displayed using different colors and text styles // Diagnostic .java // import javax .swing. *; import javax .swing. text.*; import java. awt.*; public class Diagnostic { // Create new new Diagnostic display using a black JTextPane public Diagnostic() { pane = new JTextPane(); pane.setBackground(Color.black);... in hashtables 20.1.6 .7 Using a Resolving Parent The following example shows how a resolving parent can be used to store information applicable to multiple attribute sets The attributes in this example are not actually applied to a document The goal is only to show how to use a SimpleAttributeSet with a resolving parent // ResParentExample .java // import javax .swing. text.*; import java. awt.Color; // An... references like JComponent updateUI Note that this method only works with HTML documents 19.1 .7 The HyperlinkListener Interface This interface (found in javax .swing. event) defines a single method, used to respond to hyperlink activations public abstract void hyperlinkUpdate(HyperlinkEvent e) - 605 - Java Swing - O’Reilly Called to indicate that a hyperlink request has been made Typical implementations... offset has changed // PositionExample .java // import javax .swing. text.*; public class PositionExample { public static void main(String[] args) { try { // Create a document with some initial text PlainDocument doc = new PlainDocument(); doc.insertString(0, "One Three Four", null); // Create a Position starting at "Three" Position pos = doc.createPosition(4); - 622 - Java Swing - O’Reilly int offset = pos.getOffset();... 19.2 More to Come In this chapter, we've shown how easy it is to do simple things with the Swing text framework However, if you want to do more than we've demonstrated in this chapter, Swing has a lot to offer - 608 - Java Swing - O’Reilly Over the next five chapters, we'll examine every class and interface in the Swing text package, building many interesting and powerful sample programs as we go The... together; the element types here do not map directly to anything provided by Swing Figure 20.2 Sample Element structure Another way to understand the concept of an Element is to look at mark-up languages such as HTML or XML Documents defined by such mark-up languages can be easily represented using the - 612 - Java Swing - O’Reilly Swing Document/Element model Each "element" from the mark-up language simply... Document It could technically be used to execute any arbitrary code while holding a read lock [6] This method is called directly The Runnable is not passed to a new Thread object - 6 27 - Java Swing - O’Reilly 20.1.10 .7 Reading and Writing These methods read and write the underlying Document content The methods that modify the content must obtain a write lock before proceeding public String getText(int . Class application/rtf javax .swing. text.rtf.RTFEditorKit text/plain javax .swing. JEditorPane.PlainEditorKit [5] text/html javax .swing. text.html.HTMLEditorKit text/rtf javax .swing. text.rtf.RTFEditorKit. the old style javadoc for the JEditorPane class. Here's the code: // HTMLExample .java // import javax .swing. *; import javax .swing. event.*; import java. io.*; public. specified line. Java Swing - O’Reilly - 599 - The following example shows how these three methods work: // OffsetTest .java // import javax .swing. *; import javax .swing. text.*;

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan