Java Reference
In-Depth Information
Style myStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.
DEFAULT_STYLE);
Once a style is defined, several methods from the StyleConstants class can be
used to set various characteristics.
StyleConstants
are a collection of common
text attributes and methods, such as setBold(), setItalic(), and setUnderline().
The following code uses the
setFontFamily() method
to assign the Arial
font to a previously declared Style and the
setFontSize() method
to assign a
font size of 16.
StyleConstants.setFontFamily(myStyle, "Arial");
StyleConstants.setFontSize(myStyle, 16);
A defined Style may be used as a starting point to create additional Styles.
The
addStyle() method
uses a previously defined Style as well as a
String keyword to identify a specific attribute for use in other parts of the
program. For example, the following code assigns the word, italic, to a style
named newStyle.
Style newStyle = textPane.addStyle("italic", myStyle);
Coding the setTabsAndStyles() Method
Figure 7-22 displays the code for the setTabsAndStyles() method. The
setTabsAndStyles() method accepts a JTextPane argument and returns nothing.
Therefore, a JTextPane is passed to this method, which then formats it.
128
//method to create tab stops and set font styles
129
protected void
setTabsAndStyles
(
JTextPane textPane
)
130
{
131
//create Tab Stops
132
TabStop
[]
tabs =
new
TabStop
[
2
]
;
133
tabs
[
0
]
=
new
TabStop
(
200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE
)
;
134
tabs
[
1
]
=
new
TabStop
(
350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE
)
;
135
TabSet tabset =
new
TabSet
(
tabs
)
;
136
137
//set Tab Style
138
StyleContext tabStyle = StyleContext.getDefaultStyleContext
()
;
139
AttributeSet aset =
140
tabStyle.addAttribute
(
SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset
)
;
141
textPane.setParagraphAttributes
(
aset,
false
)
;
142
143
//set Font Style
144
Style fontStyle =
145
StyleContext.getDefaultStyleContext
()
.getStyle
(
StyleContext.DEFAULT_STYLE
)
;
146
147
Style regular = textPane.addStyle
(
"regular"
, fontStyle
)
;
148
StyleConstants.setFontFamily
(
fontStyle,
"SansSerif"
)
;
149
150
Style s = textPane.addStyle
(
"italic"
, regular
)
;
151
StyleConstants.setItalic
(
s,
true
)
;
152
153
s = textPane.addStyle
(
"bold"
, regular
)
;
154
StyleConstants.setBold
(
s,
true
)
;
155
156
s = textPane.addStyle
(
"large"
, regular
)
;
157
StyleConstants.setFontSize
(
s, 16
)
;
158
}
159
FIGURE 7-22
Search WWH ::
Custom Search