Java Swing phần 8 docx

99 353 0
Java Swing phần 8 docx

Đ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 - 694 - } } Figure 21.7. JTextPane containing JButtons and ImageIcons 21.1.12.6 Other Public Method public void replaceSelection(String content) Inserts, removes, or replaces text. If there is any currently selected text, it is removed. Then, any new text is inserted in its place. If no text is passed in, this is essentially a remove operation. If no text is selected, the given text will be inserted at the current cursor position. Any new text will have the attributes currently defined for new given text (inputAttributes). 21.1.12.7 Protected Methods The following protected methods are defined in JTextPane: protected final StyledEditorKit getStyledEditorKit() Casts the result of getEditorKit() to a StyledEditorKit. protected EditorKit createDefaultEditorKit() Returns a new StyledEditorKit. This is the method called by JEditorPane.getEditorKit(), if it is called before a kit has been set for the pane. 21.1 Style If you've ever worked with a reasonably powerful word processor, you're probably already familiar with the concept of a style. A style is basically just a collection of attributes that describes how something should look. For example, as I sit here writing this book, the text I'm entering into my word processor looks a certain way because of the paragraph style (Body) and character style (Default) I have selected. To produce the heading just before this paragraph, I could have typed "Style," selected the text, changed the font to Bodoni BT, changed the font size to 18, and toggled on the italics button. Thankfully (believe me!), I didn't have to do all that. All I had to do was click somewhere within the text and use a menu to select the HeadA style, which encapsulates all of the properties described above (not to mention more interesting things, like the fact that the next paragraph should be a Body paragraph). Providing this type of functionality in your own programs would be a lot of work if you had to do it all yourself. Fortunately, you don't. The Swing text package builds on the document model Java Swing - O’Reilly - 695 - described in the last chapter to provide a powerful range of support for working with text styles. The new classes and interfaces involved in providing style capabilities (along with some of the ones from the last chapter that are directly related) are shown in Figure 21.1. Figure 21.1. Style class diagram Over the next few pages, we'll give a brief overview of the new classes and interfaces shown in this diagram, as well as an explanation of the relationships between them. Style This interface, an extension of MutableAttributeSet, adds two things not provided by its super-interface. The first is a name—every Style may (optionally) be given a name. The second is the ability to add and remove ChangeListeners. These listeners should be notified when changes are made to the definition of a Style. StyledDocument This interface, an extension of Document, adds a variety of methods for working with Styles and defines methods to provide access to the set of Style objects that describe the Document. New methods include setLogicalStyle(), to define the Style for the paragraph containing a given offset, addStyle(), to create a new Style, and many more. StyleContext Java Swing - O’Reilly - 696 - This implementation of AbstractDocument.AttributeContext provides an efficient mechanism for managing attributes and Styles shared by multiple Elements or Documents. It actually stores the Styles it manages as attributes in an instance of an inner class called NamedStyle. In addition, this class is responsible for the creation of new Style objects, which are always created as new NamedStyle objects. StyleContext.NamedStyle This public inner class implements the Style interface using its enclosing StyleContext for efficient management of attributes. Its resolving parent is always another Style. StyleConstants This class contains definitions for a wide variety of pre-defined attributes used to define Styles. It also contains many convenient static methods to extract specific attributes from a given AttributeSet, e.g., isBold() is a static method that takes an AttributeSet, checks to see if the StyleConstants.Bold key is in the set, and returns its value (or false if it's not in the set). DefaultStyledDocument This is the class used by text components like JTextPane that want to show text using a variety of textual styles. It uses a StyleContext to manage its Styles. It also uses several inner classes, defined below. DefaultStyledDocument.ElementBuffer This public inner class is used to manage changes to the Element structure of a DefaultStyledDocument. DefaultStyledDocument.ElementSpec This public inner class is used to provide a specification of an Element to be created. ElementSpecs are created by DefaultStyledDocument (e.g., in insertUpdate()) and passed to an ElementBuffer, which uses them to determine how the Element structure needs to be updated. [1] [1] Note that a containment relation should be shown from DefaultStyledDocument.ElementSpec to AttributeSet (one of the things that makes up an ElementSpec is a set of attributes), but was omitted to keep the diagram as readable as possible. DefaultStyledDocument.SectionElement This protected inner class is an extension of AbstractDocument. BranchElement, used to provide an additional level of nesting in the DefaultStyledDocument Element structure. An instance of this class serves as the document's root Element. In the next part of this chapter, we'll take a closer look at each of these new classes and interfaces. Once they've all been covered, we'll look at a detailed example that shows how to use Styles to create a Style-based text editor. Java Swing - O’Reilly - 697 - 21.1.1 The Style Interface The Style interface is a simple extension of MutableAttributeSet, which allows a set of attributes to be given a name. This just defines a common identifier for the Style, allowing it to be easily referenced (e.g., by StyledDocument's getStyle() method, which takes a single String and returns the matching Style). This name is also typically used to populate a menu in the user interface, allowing the user to select a named Style for some portion of text. In addition, Style adds support for registering change listeners to be notified whenever the attributes that define a Style are modified. 21.1.1.1 Property Table 21.1 shows the property defined by the Style interface. The only property added by Style is the name property. It is valid for a Style to be unnamed, in which case the accessor should simply return null. Table 21.1, Style Property Property Data Type get is set bound Default Value name String See also properties from the MutableAttributeSet interface (Table 20.9). 21.1.1.2 Events When a change is made to the attributes that make up a Style, listeners registered for change events will be notified. The style interface specifies the following standard methods for registering change listeners: public void addChangeListener(ChangeListener l) public void removeChangeListener(ChangeListener l) 21.1.2 The StyleConstants Class Many of the attributes used to describe text are very common. If each program had to choose a key (i.e., a name or symbolic constant) to represent each of these attributes, there would be little hope for consistency. In defining a key for the "bold" attribute, one developer might use the String "bold", another might use the String "BoldText", and yet another might use an Integer object that maps to some globally defined constant. For many common attributes, this confusion can be avoided by using the StyleConstants class. This class defines a large number of type-safe constant values, intended to be used as attribute keys. This allows us to refer to the "bold" attribute as simply StyleConstants.Bold. In addition to defining constants, StyleConstants also defines static methods that allow you to set the value for certain attributes. Using these methods allows you to replace a call like this: myMutableAttrSet.addAttribute(StyleConstants.Bold, new Boolean(true)); with a call like this: StyleConstants.setBold(myMutableAttrSet, true); Java Swing - O’Reilly - 698 - 21.1.2.1 StyleConstants Inner Classes StyleConstants groups its constants using the four inner classes described next. Note the different (empty) interfaces from AttributeSet implemented by each class. These allow you to determine the type of an attribute using the instanceof operator. For example: if (someAttr instanceof AttributeSet.ParagraphAttribute) doSomething(); Here are the definitions of the different inner classes. public static class CharacterConstants implements AttributeSet.CharacterAttribute Defines constants for attributes typically applied to character content, including those defined in FontConstants and ColorConstants. public static class ColorConstants implements AttributeSet.ColorAttribute, AttributeSet.CharacterAttribute Defines constants for foreground and background color. public static class FontConstants implements AttributeSet.FontAttribute, AttributeSet.CharacterAttribute Defines constants related to font definition. public static class ParagraphConstants implements AttributeSet.ParagraphAttribute Defines constants used to describe an entire paragraph, such as alignment and spacing. You don't need to worry about these inner classes, because all of the constants defined in them are also defined in the outer class, StyleConstants. This means that, for example, all of the following are valid (and equivalent): StyleConstants.FontSize StyleConstants.CharacterConstants.Size StyleConstants.FontConstants.Size Consistently using the first of these formats will make your code simpler to understand. 21.1.2.2 Attribute Constants Table 21.2 shows all of the attribute constants defined by StyleConstants. Regardless of their actual type, which is always one of the StyleConstants inner classes, all of these constants are defined as type Object. The Value Type column indicates the type of value that should be associated with each attribute key, and the Default column shows the value that will be returned by the static accessor methods (described later) if the attribute is not found in a set. [2] [2] This is fairly important. When you create a new JTextPane, for example, it is these default values that define what the text will look like if you don't specify attributes for the text. This is because a default Style is in use that contains no attributes, so these defaults will be returned when the Style is examined using the static StyleConstants methods. Table 21.2, StyleConstants Attribute Name Constants [3] Java Swing - O’Reilly - 699 - Constant Category Value Type Default Description Alignment Paragraph Integer ALIGN_LEFT Alignment for a paragraph (see Table 21.4 for valid values) Background Char, Color Color Color.black Background color BidiLevel Character Integer 0 Bidirectional level according to the Unicode bidi algorithm Bold Char, Font Boolean false Bold text ComponentAttribute [4] Character Component null Allows an Element to represent a Component, instead of text FirstLineIndent Paragraph Float 0 Number of points to indent first line FontFamily Char, Font String "Monospaced" Name of the font family FontSize Char, Font Integer 12 Size of the font Foreground Char, Color Color black Foreground color IconAttribute Character Icon null Used to allow an Element to represent a Icon, instead of text Italic Char, Font Boolean false Italic text LeftIndent Paragraph Float 0 Number of points to indent from the left margin LineSpacing Paragraph Float 0 Number of points between lines Orientation [5] Paragraph undefined undefined Orientation of the paragraph RightIndent Paragraph Float 0 Number of points to indent from the right margin SpaceAbove Paragraph Float 0 Number of points above each line SpaceBelow Paragraph Float 0 Number of points below each line TabSet Paragraph TabSet [6] null Set of TabStops Underline Character Boolean false Underlined text [3] The attribute names FontFamily and FontSize are shortened to Family and Size within the FontConstants inner class. All other attribute names are the same within their respective inner classes. [4] The ComponentAttribute and IconAttribute constants can be used to indicate that an element should be displayed as a component or icon rather than as text. For more information, see the example later in the chapter. There is no additional significance to the "Attribute" suffix of these constants. [5] As of JDK 1.2 beta 4, no static convenience methods are defined for this constant. [6] The TabSet and TabStop classes are described after this section. 21.1.2.3 Other Attribute Constants Table 21.3 shows constants used to store special information in an AttributeSet. The first constant shown here, ComposedTextAttribute , is intended to be used to hold an AttributedString (a new JDK 1.2 class defined in the java.text package). This constant is currently unused. The last two constants in the table are used as attribute keys to define the set's name (used for named Styles) and the set's resolving parent. Table 21.3, StyleConstants Special Attribute Key Constants Name Data Type Value Type Description ComposedTextAttribute Object java.text.At- tributedString An attributed string describing the set's attributes (JDK 1.2 only) NameAttribute Object String The name of the attribute set ResolveAttribute Object AttributeSet Attribute set's resolving parent Java Swing - O’Reilly - 700 - 21.1.2.4 Alignment Value Constants StyleConstants also defines four attribute values for the Alignment attribute, shown in Table 21.4. Table 21.4, StyleConstants.Alignment Attribute Value Constants Name Data Type Description ALIGN_CENTER int Align text to the center with equal whitespace on the left and right. ALIGN_JUSTIFIED int Align text such that all whitespace is spread out, leaving text aligned on both the left and right margins. The last line should have left alignment. ALIGN_LEFT int Align text to the left with whitespace on the right. ALIGN_RIGHT int Align text to the right with whitespace on the left. 21.1.2.5 Element Name Constants AbstractDocument defines a constant called ElementNameAttribute , used as a key to store the name of an Element in its AttributeSet (see Table 21.5). StyleConstants defines two possible values for this attribute, used when the Element does not contain textual data. This attribute is not limited to these two values; these are just constants for special case Element names. Table 21.5, AbstractDocument.ElementNameAttribute Value Constants Name Data Type Description ComponentElementName String Used when the Element contains a Component instead of text. IconElementName String Used when the Element contains an Icon instead of text. 21.1.2.6 Lookup and Update Methods StyleConstants defines static methods to access and set each of the attributes for which it defines constant keys. Each accessor method takes an AttributeSet, while the update methods require a MutableAttributeSet as input. These methods handle the conversions between Java primitive types and the wrapper classes Float, Integer, and Boolean (remember, all attribute values are of type Object, so primitive attribute values must be wrapped in objects), so that all interfaces are able to use the primitive types. public static int getAlignment(AttributeSet a) public static Color getBackground(AttributeSet a) public static int getBidiLevel(AttribuetSet a) public static boolean isBold(AttributeSet a) public static Component getComponent(AttributeSet a) public static float getFirstLineIndent(AttributeSet a) public static String getFontFamily(AttributeSet a) public static int getFontSize(AttributeSet a) public static Color getForeground(AttributeSet a) public static Icon getIcon(AttributeSet a) public static boolean isItalic(AttributeSet a) public static float getLeftIndent(AttributeSet a) public static float getLineSpacing(AttributeSet a) public static float getRightIndent(AttributeSet a) public static float getSpaceAbove(AttributeSet a) public static float getSpaceBelow(AttributeSet a) public static TabSet getTabSet(AttributeSet a) Java Swing - O’Reilly - 701 - public static boolean isUnderline(AttributeSet a) These methods return the value found in the given set, if there is one. If the key is not found, the default values shown in Table 21.2 are returned. public static void setAlignment(MutableAttributeSet a, int align) public static void setBackground(MutableAttributeSet a, Color bg) public static void setBidiLevel(MutableAttributeSet a, int 0) public static void setBold(MutableAttributeSet a, boolean b) public static void setFirstLineIndent(MutableAttributeSet a, float i) public static void setFontFamily(MutableAttributeSet a, String fam) public static void setFontSize(MutableAttributeSet a, int s) public static void setForeground(MutableAttributeSet a, Color fg) public static void setItalic(MutableAttributeSet a, boolean b) public static void setLeftIndent(MutableAttributeSet a, float i) public static void setLineSpacing(MutableAttributeSet a, float i) public static void setRightIndent(MutableAttributeSet a, float i) public static void setSpaceAbove(MutableAttributeSet a, float i) public static void setSpaceBelow(MutableAttributeSet a, float i) public static void setTabSet(MutableAttributeSet a, TabSet tabs) public static void setUnderline(MutableAttributeSet a, boolean b) These methods add the appropriate attribute to the given set, replacing the existing value if there is one. The next two methods actually set two properties. In addition to setting ComponentAttribute or IconAttribute, they also set the AbstractDocument.Ele-mentNameAttribute. The values used for this property were shown back in Table 21.5. public static void setComponent(MutableAttributeSet a, Component c) public static void setIcon(MutableAttributeSet a, Icon c) 21.1.3 The TabStop Class In the last section, we came across TabSet and TabStop. Now, we'll take quick detour from our discussion of style to examine them. TabStop, as you might guess, is used to describe a tab position. This information is used by the text view classes to correctly handle the display of tabs encountered in the document model. 21.1.3.1 Properties The TabStop class defines the properties listed in Table 21.6. The alignment property specifies how the text following a tab should be positioned relative to the tab position. The legal values for this property are shown in Table 21.7. The leader property describes what should be displayed leading up to the tab. Legal values for this property are shown in Table 21.6. Currently, none of the Swing text views use the leader property. The position property indicates where the tab should appear (in pixels). Table 21.6, TabStop Properties Property Data Type get is set bound Default Value alignment int ALIGN_LEFT leader int LEAD_NONE Java Swing - O’Reilly - 702 - position float from constructor 21.1.3.2 Alignment Constants Table 21.7 shows the constants used to enumerate the possible ways that text following a tab can be aligned. Table 21.7, TabStop Alignment Constants Name Data Type Description ALIGN_BAR int Text after the tab should start at the tab position (currently the same as ALIGN_LEFT) ALIGN_CENTER int Text after the tab should be centered over the tab's position ALIGN_DECIMAL int Text after the tab should be aligned so that the next decimal, tab, or newline is located at the tab position ALIGN_LEFT int Text after the tab should start at the tab position ALIGN_RIGHT int Text after the tab should end at the tab position Here's an example that shows the effect of each of these alignment values: // TabStopExample.java // import javax.swing.text.*; import javax.swing.*; // Show how the different TabStop alignment values work. public class TabStopExample { public static void main(String[] args) { // Create TabStops with the different alignments TabStop bar = new TabStop(100, TabStop.ALIGN_BAR, TabStop.LEAD_NONE); TabStop center = new TabStop(100, TabStop.ALIGN_CENTER, TabStop.LEAD_NONE); TabStop decimal= new TabStop(100, TabStop.ALIGN_DECIMAL, TabStop.LEAD_NONE); TabStop left = new TabStop(100, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); TabStop right = new TabStop(100, TabStop.ALIGN_RIGHT, TabStop.LEAD_NONE); // Create a JTextPane to show tabs in JTextPane tp = new JTextPane(); StyledDocument doc = tp.getStyledDocument(); SimpleAttributeSet a = new SimpleAttributeSet(); TabSet tabs; int offset; // Insert text with each TabStop value try { offset = doc.getLength(); doc.insertString(doc.getLength(), "\tBar\n", null); tabs = new TabSet(new TabStop[] {bar}); StyleConstants.setTabSet(a, tabs); doc.setParagraphAttributes(offset, 1, a, false); offset = doc.getLength(); Java Swing - O’Reilly - 703 - doc.insertString(offset, "\tCentered\n", null); tabs = new TabSet(new TabStop[] {center}); StyleConstants.setTabSet(a, tabs); doc.setParagraphAttributes(offset, 1, a, false); offset = doc.getLength(); doc.insertString(doc.getLength(), "\t1234.99\n", null); tabs = new TabSet(new TabStop[] {decimal}); StyleConstants.setTabSet(a, tabs); doc.setParagraphAttributes(offset, 1, a, false); offset = doc.getLength(); doc.insertString(doc.getLength(), "\tLeft\n", null); tabs = new TabSet(new TabStop[] {left}); StyleConstants.setTabSet(a, tabs); doc.setParagraphAttributes(offset, 1, a, false); offset = doc.getLength(); doc.insertString(doc.getLength(), "\tRight\n", null); tabs = new TabSet(new TabStop[] {right}); StyleConstants.setTabSet(a, tabs); doc.setParagraphAttributes(offset, 1, a, false); } catch (BadLocationException ex) {} // Display it JFrame f = new JFrame(); f.addWindowListener(new BasicWindowMonitor()); f.setSize(200, 110); f.setContentPane(tp); f.setVisible(true); } } In this example, we simply created five TabStop objects, one with each of the different alignment values. For each TabStop, we added a line of text, starting with a tab ("\t") and set its TabSet (described next) to a set containing the single TabStop. Figure 21.2 shows how these values are displayed. Figure 21.2. TabStop alignment 21.1.3.3 Leader Constants Table 21.8 shows constants that enumerate the possible ways the space before a tab should be filled. These constants are legal values for the leader property. Currently, changing this property's value has no effect. Table 21.8, TabStop Leading Constants [...]... JTextPane and two buttons: one inserts an Icon, and the second inserts a JButton Figure 21.7 shows a display after playing with the editor a little bit // IconAndComp .java // import javax .swing. *; import javax .swing. text.*; import java. awt.*; import java. awt.event.*; // Shows that Icons and Components can be added to a JTextPane public class IconAndComp { public static void main(String[] args) { final JTextPane... Content object is specified (4096) 21.1 .8. 3 Constructors public DefaultStyledDocument() Calls the last constructor, passing it a new StringContent set to the default size, and a new StyleContext public DefaultStyledDocument(StyleContext styles) Calls the last constructor, passing it a new StringContent set to the default size, and the given StyleContext - 7 18 - Java Swing - O’Reilly public DefaultStyledDocument(AbstractDocument.Content... fireUndoableEditUpdate() are called to notify listeners of the changes The replace parameter indicates whether the given attributes should replace any existing paragraph attributes or merge with them - 720 - Java Swing - O’Reilly 21.1 .8. 8 Element Structure Methods The following methods can be used by subclasses to make bulk changes to a document The idea is to be able to load the document data (from a file, for example)... DefaultStyledDocument(); SimpleAttributeSet set1 = new SimpleAttributeSet(); StyleConstants.setBold(set1, false); StyleConstants.setItalic(set1, true); - 721 - Java Swing - O’Reilly plainDoc.insertString(0, "Swing is cool", set1); // IGNORED! styledDoc.insertString(0, "Swing is cool", set1); // BEFORE (see Figure 21.6) SimpleAttributeSet set2 = new SimpleAttributeSet(); StyleConstants.setBold(set2, true); plainDoc.insertString(9,... JoinNextDirection short The Element should be joined with the next one OriginateDirection short A new Element should be created 21.1.10.3 Type Constants - 723 - Java Swing - O’Reilly Table 21. 18 shows the valid values for the type property Table 21. 18, DefaultStyledDocument.ElementSpec Type Constants Name contentType Data Type short Description ElementSpec represents the content of an Element endTagType... returned Once the sets get too large, it is more efficient to use different sets, since matching all attributes in a large set would become too time consuming // StyleContextExample .java // import javax .swing. text.*; import java. awt.*; public class StyleContextExample { public static void main(String[] args) { StyleContext con = new StyleContext(); // Create two different attribute sets SimpleAttributeSet... more about how all of this fits together over the next few pages 21.1.7.1 Properties StyledDocument inherits its properties from the document interface. [8] [8] logicalStyle, characterElement, and paragraphElement appear (by strict interpretation of the JavaBeans specification) to be indexed properties of StyledDocument The index, however, is a character index into the document, not a simple array index... show that the sets returned by addAttribute() match until we exceed the threshold, when we get separate set objects, even though they still contain the same key/value pairs 21.1.5.6 A Look Inside - 7 08 - Java Swing - O’Reilly Before looking at the methods related to managing Style objects, we'll take a quick detour to look at how the StyleContext manages Styles internally Figure 21.3 shows an object structure... space being inserted into the document This space is represented by a single Element with attributes set to indicate that the space represents the given Component public void insertIcon(Icon c) - 7 28 - Java Swing - O’Reilly Inserts an Icon into the document, replacing anything currently selected If there is no selection, the icon is inserted at the current cursor position Inserting an Icon results in... getStyle(String nm) Returns a Style for the given name If no Style has been added with the specified name, it returns null public void removeStyle(String nm) - 709 - Java Swing - O’Reilly Removes the named Style from the context 21.1.5 .8 Font Management Methods These methods are used to manage Font objects An Element's Font is not typically stored as a single attribute, so it's nice to have an easy . effect of each of these alignment values: // TabStopExample .java // import javax .swing. text.*; import javax .swing. *; // Show how the different TabStop alignment values work. public. large set would become too time consuming. // StyleContextExample .java // import javax .swing. text.*; import java. awt.*; public class StyleContextExample { public static void main(String[]. if you had to do it all yourself. Fortunately, you don't. The Swing text package builds on the document model Java Swing - O’Reilly - 695 - described in the last chapter to provide

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