_chapter 10.htm
来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,361 行 · 第 1/4 页
HTM
1,361 行
25. check box.
26. */
27. class DateFormatFrame extends JFrame
28. {
29. public DateFormatFrame()
30. {
31. setSize(WIDTH, HEIGHT);
32. setTitle("DateFormatTest");
33.
34. getContentPane().setLayout(new GridBagLayout());
35. GridBagConstraints gbc = new GridBagConstraints();
36. gbc.fill = GridBagConstraints.NONE;
37. gbc.anchor = GridBagConstraints.EAST;
38. add(new JLabel("Locale"), gbc, 0, 0, 1, 1);
39. add(new JLabel("Date style"), gbc, 0, 1, 1, 1);
40. add(new JLabel("Time style"), gbc, 2, 1, 1, 1);
41. add(new JLabel("Date"), gbc, 0, 2, 1, 1);
42. add(new JLabel("Time"), gbc, 0, 3, 1, 1);
43. gbc.anchor = GridBagConstraints.WEST;
44. add(localeCombo, gbc, 1, 0, 2, 1);
45. add(dateStyleCombo, gbc, 1, 1, 1, 1);
46. add(timeStyleCombo, gbc, 3, 1, 1, 1);
47. add(dateParseButton, gbc, 3, 2, 1, 1);
48. add(timeParseButton, gbc, 3, 3, 1, 1);
49. add(lenientCheckbox, gbc, 0, 4, 2, 1);
50. gbc.fill = GridBagConstraints.HORIZONTAL;
51. add(dateText, gbc, 1, 2, 2, 1);
52. add(timeText, gbc, 1, 3, 2, 1);
53.
54. locales = DateFormat.getAvailableLocales();
55. for (int i = 0; i < locales.length; i++)
56. localeCombo.addItem(locales[i].getDisplayName());
57. localeCombo.setSelectedItem(
58. Locale.getDefault().getDisplayName());
59. currentDate = new Date();
60. currentTime = new Date();
61. updateDisplay();
62.
63. ActionListener listener = new
64. ActionListener()
65. {
66. public void actionPerformed(ActionEvent event)
67. {
68. updateDisplay();
69. }
70. };
71.
72. localeCombo.addActionListener(listener);
73. dateStyleCombo.addActionListener(listener);
74. timeStyleCombo.addActionListener(listener);
75.
76. dateParseButton.addActionListener(new
77. ActionListener()
78. {
79. public void actionPerformed(ActionEvent event)
80. {
81. String d = dateText.getText();
82. try
83. {
84. currentDateFormat.setLenient
85. (lenientCheckbox.isSelected());
86. Date date = currentDateFormat.parse(d);
87. currentDate = date;
88. updateDisplay();
89. }
90. catch(ParseException e)
91. {
92. dateText.setText("Parse error: " + d);
93. }
94. catch(IllegalArgumentException e)
95. {
96. dateText.setText("Argument error: " + d);
97. }
98. }
99. });
100.
101. timeParseButton.addActionListener(new
102. ActionListener()
103. {
104. public void actionPerformed(ActionEvent event)
105. {
106. String t = timeText.getText();
107. try
108. {
109. currentDateFormat.setLenient
110. (lenientCheckbox.isSelected());
111. Date date = currentTimeFormat.parse(t);
112. currentTime = date;
113. updateDisplay();
114. }
115. catch(ParseException e)
116. {
117. timeText.setText("Parse error: " + t);
118. }
119. catch(IllegalArgumentException e)
120. {
121. timeText.setText("Argument error: " + t);
122. }
123. }
124. });
125. }
126.
127. /**
128. A convenience method to add a component to given grid bag
129. layout locations.
130. @param c the component to add
131. @param gbc the grid bag constraints to use
132. @param x the x grid position
133. @param y the y grid position
134. @param w the grid width
135. @param h the grid height
136. */
137. public void add(Component c, GridBagConstraints gbc,
138. int x, int y, int w, int h)
139. {
140. gbc.gridx = x;
141. gbc.gridy = y;
142. gbc.gridwidth = w;
143. gbc.gridheight = h;
144. getContentPane().add(c, gbc);
145. }
146.
147. /**
148. Updates the display and formats the date according
149. to the user settings.
150. */
151. public void updateDisplay()
152. {
153. Locale currentLocale = locales[
154. localeCombo.getSelectedIndex()];
155. int dateStyle = dateStyleCombo.getValue();
156. currentDateFormat
157. = DateFormat.getDateInstance(dateStyle,
158. currentLocale);
159. String d = currentDateFormat.format(currentDate);
160. dateText.setText(d);
161. int timeStyle = timeStyleCombo.getValue();
162. currentTimeFormat
163. = DateFormat.getTimeInstance(timeStyle,
164. currentLocale);
165. String t = currentTimeFormat.format(currentTime);
166. timeText.setText(t);
167. }
168.
169. private Locale[] locales;
170.
171. private Date currentDate;
172. private Date currentTime;
173. private DateFormat currentDateFormat;
174. private DateFormat currentTimeFormat;
175.
176. private JComboBox localeCombo = new JComboBox();
177. private EnumCombo dateStyleCombo
178. = new EnumCombo(DateFormat.class,
179. new String[] { "Default", "Full", "Long",
180. "Medium", "Short" });
181. private EnumCombo timeStyleCombo
182. = new EnumCombo(DateFormat.class,
183. new String[] { "Default", "Full", "Long",
184. "Medium", "Short" });
185. private JButton dateParseButton = new JButton("Parse date");
186. private JButton timeParseButton = new JButton("Parse time");
187. private JTextField dateText = new JTextField(30);
188. private JTextField timeText = new JTextField(30);
189. private JTextField parseText = new JTextField(30);
190. private JCheckBox lenientCheckbox
191. = new JCheckBox("Parse lenient", true);
192. private static final int WIDTH = 400;
193. private static final int HEIGHT = 200;
194. }
195.
196. /**
197. A combo box that lets users choose from among static field
198. values whose names are given in the constructor.
199.*/
200.class EnumCombo extends JComboBox
201.{
202. /**
203. Constructs an EnumCombo.
204. @param cl a class
205. @param labels an array of static field names of cl
206. */
207. public EnumCombo(Class cl, String[] labels)
208. {
209. for (int i = 0; i < labels.length; i++)
210. {
211. String label = labels[i];
212. String name = label.toUpperCase().replace(' ', '_');
213. int value = 0;
214. try
215. {
216. java.lang.reflect.Field f = cl.getField(name);
217. value = f.getInt(cl);
218. }
219. catch(Exception e)
220. {
221. label = "(" + label + ")";
222. }
223. table.put(label, new Integer(value));
224. addItem(label);
225. }
226. setSelectedItem(labels[0]);
227. }
228.
229. /**
230. Returns the value of the field that the user selected.
231. @return the static field value
232. */
233. public int getValue()
234. {
235. return ((Integer)table.get(getSelectedItem())).intValue();
236. }
237.
238. private Map table = new HashMap();
239.}
</pre>
<h4 class="docSection2Title" id="ch10lev2sec3"><tt>java.text.DateFormat</tt></h4>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<ul>
<li>
<p class="docList"><tt>static Locale[] getAvailableLocales()</tt></p>
<p class="docList">returns an array of <tt>Locale</tt> objects for which <tt>
DateFormat</tt> formatters are available.</li>
<li>
<p class="docList"><tt>static DateFormat getDateInstance(int dateStyle)</tt></li>
<li>
<p class="docList"><tt>static DateFormat getDateInstance(int dateStyle, Locale
l)</tt></li>
<li>
<p class="docList"><tt>static DateFormat getTimeInstance(int timeStyle)</tt></li>
<li>
<p class="docList"><tt>static DateFormat getTimeInstance(int timeStyle, Locale
l)</tt></li>
<li>
<p class="docList"><tt>static DateFormat getDateTimeInstance(int dateStyle,
int timeStyle)</tt></li>
<li>
<p class="docList"><tt>static DateFormat getDateTimeInstance(int dateStyle,
int timeStyle, Locale l)</tt></p>
<p class="docList">return a formatter for date, time, or date and time for the
default locale or the given locale.</p>
<table cellSpacing="0" cellPadding="1" width="93%" border="1">
<colgroup span="3" align="left">
</colgroup>
<tr>
<td class="docTableCell" vAlign="top"><span class="docEmphasis">
Parameters:</span></td>
<td class="docTableCell" vAlign="top"><tt>dateStyle</tt>, <tt>timeStyle</tt></td>
<td class="docTableCell" vAlign="top">one of <tt>DEFAULT</tt>, <tt>FULL</tt>,
<tt>LONG</tt>, <tt>MEDIUM</tt>, <tt>SHORT</tt></td>
</tr>
</table>
<p> </li>
<li>
<p class="docList"><tt>String format(Date d)</tt></p>
<p class="docList">returns the string resulting from formatting the given
date/time.</li>
<li>
<p class="docList"><tt>Date parse(String s)</tt></p>
<p class="docList">parses the given string and returns the date/time described
in it. The beginning of the string must contain a date or time; no leading
white space is allowed. The date can be followed by other characters, which
are ignored. Throws a <tt>ParseException</tt> if parsing was not successful.</li>
<li>
<p class="docList"><tt>void setLenient(boolean b)</tt></li>
<li>
<p class="docList"><tt>boolean isLenient()</tt></p>
<p class="docList">set or get a flag to indicate whether parsing should be
lenient or strict. In lenient mode, dates such as <tt>February 30, 1999</tt>
will be automatically converted to <tt>March 2, 1999</tt>. The default is
lenient mode.</li>
<li>
<p class="docList"><tt>void setCalendar(Calendar cal)</tt></li>
<li>
<p class="docList"><tt>Calendar getCalendar()</tt></p>
<p class="docList">set or get the calendar object used for extracting year,
month, day, hour, minute, and second from the <tt>Date</tt> object. Use this
method if you do not want to use the default calendar for the locale (usually
the Gregorian calendar).</li>
<li>
<p class="docList"><tt>void setTimeZone(TimeZone tz)</tt></li>
<li>
<p class="docList"><tt>TimeZone getTimeZone()</tt></p>
<p class="docList">set or get the time zone object used for formatting the
time. Use this method if you do not want to use the default time zone for the
locale. The default time zone is the time zone of the default locale, as
obtained from the operating system. For the other locales, it is the preferred
time zone in the geographical location.</li>
<li>
<p class="docList"><tt>void setNumberFormat(NumberFormat f)</tt></li>
<li>
<p class="docList"><tt>NumberFormat getNumberFormat()</tt></p>
<p class="docList">set or get the number format used for formatting the
numbers used for representing year, month, day, hour, minute, and second.</li>
</ul>
<h3 class="docSection1Title" id="c10s4">Text</h3>
<p class="docText">There are many localization issues to deal with when you
display even the simplest text in an internationalized application. In this
section, we work on the presentation and manipulation of text strings. For
example, the sorting order for strings is clearly locale specific. Obviously,
you also need to localize the text itself: directions, labels, and messages will
all need to be translated. (Later in this chapter, you'll see how to build
<span class="docEmphasis">resource bundles.</span> These let you collect a set
of message strings that work for a particular language.)</p>
<h4 class="docSection2Title" id="ch10lev2sec4">Collation (Ordering)</h4>
<p class="docText">Sorting strings in alphabetical order is easy when the
strings are made up of only English ASCII characters. You just compare the
strings with the <tt>compareTo</tt> method of the <tt>String</tt> class. The
value of</p>
<pre>a.compareTo(b)
</pre>
<p class="docText">is a negative number if <tt>a</tt> is lexicographically less
than <tt>b</tt>, 0 if they are identical, and positive otherwise.</p>
<p class="docText">Unfortunately, unless all your words are in uppercase English
ASCII characters, this method is useless. The problem is that the <tt>compareTo</tt>
method in the Java programming language uses the values of the Unicode character
to determine the ordering. For example, lowercase characters have a higher
Unicode value than do uppercase characters, and accented characters have even
higher values. This leads to absurd results; for example, the following five
strings are ordered according to the <tt>compareTo</tt> method:</p>
<pre>America
Zulu
ant
zebra
舗gstrom
</pre>
<p class="docText">For dictionary ordering, you want to consider upper case and
lower case to be equivalent. To an English speaker, the sample list of words
would be ordered as</p>
<pre>America
舗gstrom
ant
zebra
Zulu
</pre>
<p class="docText">However, that order would not be acceptable to a Danish user.
In Danish, the letter
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?