_chapter 10.htm

来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,361 行 · 第 1/4 页

HTM
1,361
字号
    <td class="docTableCell" vAlign="top"><tt>IT</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Japan </td>
    <td class="docTableCell" vAlign="top"><tt>JP</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Korea </td>
    <td class="docTableCell" vAlign="top"><tt>KR</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">The Netherlands </td>
    <td class="docTableCell" vAlign="top"><tt>NL</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Norway </td>
    <td class="docTableCell" vAlign="top"><tt>NO</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Portugal </td>
    <td class="docTableCell" vAlign="top"><tt>PT</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Spain </td>
    <td class="docTableCell" vAlign="top"><tt>ES</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Sweden </td>
    <td class="docTableCell" vAlign="top"><tt>SE</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Switzerland </td>
    <td class="docTableCell" vAlign="top"><tt>CH</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Taiwan </td>
    <td class="docTableCell" vAlign="top"><tt>TW</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">Turkey </td>
    <td class="docTableCell" vAlign="top"><tt>TR</tt> </td>
  </tr>
  <tr>
    <td class="docTableCell" vAlign="top">United States </td>
    <td class="docTableCell" vAlign="top"><tt>US</tt> </td>
  </tr>
</table>
<p class="docText">These codes do seem a bit random, especially since some of 
them are derived from local languages (German = Deutsch = <tt>de</tt>, Chinese = 
zhongwen = <tt>zh</tt>), but they are, at least, standardized.</p>
<p class="docText">To describe a locale, you concatenate the language, country 
code, and variant (if any) and pass this string to the constructor of the <tt>
Locale</tt> class. The variant is optional.</p>
<pre>Locale germanGermany = new Locale(&quot;de&quot;, &quot;DE&quot;);
Locale germanSwitzerland = new Locale(&quot;de&quot;, &quot;CH&quot;);
Locale norwegianNorwayBokm錶 = new Locale(&quot;no&quot;, &quot;NO&quot;, &quot;B&quot;);
</pre>
<p class="docText">If you want to specify a locale that describes a language 
only and not a location, use an empty string as the second argument of the 
constructor.</p>
<pre>Locale german = new Locale(&quot;de&quot;, &quot;&quot;);
</pre>
<p class="docText">These kinds of locales can be used only for 
language-dependent lookups. Since the locales do not specify the location where 
German is spoken, you cannot use them to determine local currency and date 
formatting preferences.</p>
<p class="docText">For your convenience, the SDK predefines a number of locale 
objects:</p>
<pre>Locale.CANADA
Locale.CANADA_FRENCH
Locale.CHINA
Locale.FRANCE
Locale.GERMANY
Locale.ITALY
Locale.JAPAN
Locale.KOREA
Locale.PRC
Locale.TAIWAN
Locale.UK
Locale.US
</pre>
<p class="docText">The SDK also predefines a number of language locales that 
specify just a language without a location.</p>
<pre>Locale.CHINESE
Locale.ENGLISH
Locale.FRENCH
Locale.GERMAN
Locale.ITALIAN
Locale.JAPANESE
Locale.KOREAN
Locale.SIMPLIFIED_CHINESE
Locale.TRADITIONAL_CHINESE
</pre>
<p class="docText">Besides constructing a locale or using a predefined one, you 
have two other methods for obtaining a locale object.</p>
<p class="docText">The static <tt>getDefault</tt> method of the <tt>Locale</tt> 
class gets the default locale as stored by the local operating system. 
Similarly, in an applet, the <tt>getLocale</tt> method returns the locale of the 
user viewing the applet. Finally, all locale-dependent utility classes can 
return an array of the locales they support. For example,</p>
<pre>Locale[] supportedLocales = DateFormat.getAvailableLocales();
</pre>
<p class="docText">returns all locales that the <tt>DateFormat</tt> class can 
handle. For example, at the time of this writing, the <tt>DateFormat</tt> class 
knows how to format dates in Chinese but not in Vietnamese. Therefore, the <tt>
getAvailableLocales()</tt> returns the Chinese locales but no Vietnamese ones.</p>
<div class="docNote">
  <p class="docNoteTitle">NOTE</p>
  <table cellSpacing="0" cellPadding="1" width="90%" border="0">
    <tr>
      <td vAlign="top" width="60">
      <img alt="graphics/note.gif" src="note.gif" align="left" border="0" width="54" height="53"><br>
&nbsp;</td>
      <td vAlign="top">
      <p class="docText">We do not discuss how to create new language-specific 
      elements. If you need to build a Brooklyn- or Texas-centric locale, please 
      consult the SDK documentation.</td>
    </tr>
  </table>
</div>
<p class="docText">Once you have a locale, what can you do with it? Not much, as 
it turns out. The only useful methods in the <tt>Locale</tt> class are the ones 
for identifying the language and country codes. The most important one is <tt>
getDisplayName</tt>. It returns a string describing the locale. This string does 
not contain the cryptic two-letter codes, but it is in a form that can be 
presented to a user, such as</p>
<pre>German (Switzerland)
</pre>
<p class="docText">Actually, there is a problem here. The display name is issued 
in the default locale. That may not be appropriate. If your user already 
selected German as the preferred language, you probably want to present the 
string in German. You can do just that by giving the German locale as a 
parameter: The code</p>
<pre>Locale loc = new Locale(&quot;de&quot;, &quot;CH&quot;);
System.out.println(loc.getDisplayName(Locale.GERMAN));
</pre>
<p class="docText">prints out</p>
<pre>Deutsch (Schweiz)
</pre>
<p class="docText">But the real reason you need a <tt>Locale</tt> object is to 
feed it to locale-aware methods. For example, the <tt>toLowerCase</tt> and <tt>
toUpperCase</tt> methods of the <tt>String</tt> class can take an argument of 
type <tt>Locale</tt> because the rules for forming uppercase letters differ by 
locale. In France, accents are generally dropped for uppercase letters. But in 
French-speaking Canada, they are retained. For example, the upper case of &quot;閠oile&quot; 
(star) in France would be &quot;ETOILE,&quot; but in Canada it would be &quot;蒚OILE.&quot;</p>
<pre>String star = &quot;閠oile&quot;;
String fr = star.toUpperCase(Locale.FRANCE);
// should return &quot;ETOILE&quot;
String ca = star.toUpperCase(Locale.CANADA_FRENCH);
// returns &quot;蒚OILE&quot;
</pre>
<p class="docText">Well, not quite: actually, this is the way it is
<span class="docEmphasis">supposed</span> to work, but at least up to SDK 1.4, 
the <tt>toUpperCase</tt> method does not pay attention to the French locale. 
Still, we hope we have given you an idea of what you <span class="docEmphasis">
will</span> be able to do with a <tt>Locale</tt> object. (Actually, you can give 
a <tt>Locale</tt> object to many other methods that carry out locale-specific 
tasks. You will see many examples in the following sections.)</p>
<h4 class="docSection2Title" id="ch10lev2sec1"><tt>java.util.Locale</tt></h4>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
&nbsp;</p>
<ul>
  <li>
  <p class="docList"><tt>static Locale getDefault()</tt></p>
  <p class="docList">returns the default locale.</li>
  <li>
  <p class="docList"><tt>static void setDefault(Locale l)</tt></p>
  <p class="docList">sets the default locale.</li>
  <li>
  <p class="docList"><tt>String getDisplayName()</tt></p>
  <p class="docList">returns a name describing the locale, expressed in the 
  current locale.</li>
  <li>
  <p class="docList"><tt>String getDisplayName(Locale l)</tt></p>
  <p class="docList">returns a name describing the locale, expressed in the 
  given locale.</li>
  <li>
  <p class="docList"><tt>String getLanguage()</tt></p>
  <p class="docList">returns the language code, a lowercase two-letter ISO-639 
  code.</li>
  <li>
  <p class="docList"><tt>String getDisplayLanguage()</tt></p>
  <p class="docList">returns the name of the language, expressed in the current 
  locale.</li>
  <li>
  <p class="docList"><tt>String getDisplayLanguage(Locale l)</tt></p>
  <p class="docList">returns the name of the language, expressed in the given 
  locale.</li>
  <li>
  <p class="docList"><tt>String getCountry()</tt></p>
  <p class="docList">returns the country code as an uppercase two-letter 
  ISO-3166 code.</li>
  <li>
  <p class="docList"><tt>String getDisplayCountry()</tt></p>
  <p class="docList">returns the name of the country, expressed in the current 
  locale.</li>
  <li>
  <p class="docList"><tt>String getDisplayCountry(Locale l)</tt></p>
  <p class="docList">returns the name of the country, expressed in the given 
  locale.</li>
  <li>
  <p class="docList"><tt>String getVariant()</tt></p>
  <p class="docList">returns the variant string.</li>
  <li>
  <p class="docList"><tt>String getDisplayVariant()</tt></p>
  <p class="docList">returns the name of the variant, expressed in the current 
  locale.</li>
  <li>
  <p class="docList"><tt>String getDisplayVariant(Locale l)</tt></p>
  <p class="docList">returns the name of the variant, expressed in the given 
  locale.</li>
  <li>
  <p class="docList"><tt>String toString()</tt></p>
  <p class="docList">returns a description of the locale, with the language, 
  country, and variant separated by underscores (e.g., <tt>&quot;de_CH&quot;</tt>).</li>
</ul>
<h3 class="docSection1Title" id="c10s2">Numbers and Currencies</h3>
<p class="docText">We already mentioned how number and currency formatting is 
highly locale dependent. The Java programming language supplies a collection of 
formatter objects that can format and parse numeric values in the <tt>java.text</tt> 
class. You go through the following steps to format a number for a particular 
locale.</p>
<ol class="docList">
  <li value="1">
  <p class="docList">Get the locale object, as described in the preceding 
  section.</li>
  <li value="2">
  <p class="docList">Use a &quot;factory method&quot; to obtain a formatter object.</li>
  <li value="3">
  <p class="docList">Use the formatter object for formatting and parsing.</li>
</ol>
<p class="docText">The factory methods are static methods of the <tt>
NumberFormat</tt> class that take a <tt>Locale</tt> argument. There are three 
factory methods: <tt>getNumberInstance</tt>, <tt>getCurrencyInstance</tt>, and
<tt>getPercentInstance</tt>. These methods return objects that can format and 
parse numbers, currency amounts, and percentages, respectively. For example, 
here is how you can format a currency value in German.</p>
<pre>Locale loc = new Locale(&quot;de&quot;, &quot;DE&quot;);
NumberFormat currFmt = NumberFormat.getCurrencyInstance(loc);
double amt = 123456.78;
System.out.println(currFmt.format(amt));
</pre>
<p class="docText">This code prints</p>
<pre>123.456,78 DM
</pre>
<p class="docText">Note that the currency symbol is <tt>DM</tt> and that it is 
placed at the end of the string. Also, note the reversal of decimal points and 
decimal commas.</p>
<p class="docText">Conversely, if you want to read in a number that was entered 
or stored with the conventions of a certain locale, then you use the <tt>parse</tt> 
method, which automatically uses the default locale. For example, the following 
code parses the value that the user typed into a text field. The <tt>parse</tt> 
method can deal with decimal points and commas, as well as digits in other 
languages.</p>
<pre>TextField inputField;
. . .
NumberFormat fmt = NumberFormat.getNumberInstance();
// get number formatter for default locale
Number input = fmt.parse(inputField.getText().trim());
double x = input.doubleValue();
</pre>
<p class="docText">The return type of <tt>parse</tt> is the abstract type <tt>
Number</tt>. The returned object is either a <tt>Double</tt> or a <tt>Long</tt> 
wrapper object, depending on whether the parsed number was a floating-point 
number. If you don't care about the distinction, you can simply use the <tt>
doubleValue</tt> method of the <tt>Number</tt> class to retrieve the wrapped 
number.</p>
<p class="docText">If the number is not in the correct form, the method throws a
<tt>ParseException</tt>. For example, leading white space in the string is
<span class="docEmphasis">not</span> allowed. (Call <tt>trim</tt> to remove it.) 
However, any characters that follow the number in the string are simply ignored, 
so no exception is thrown.</p>
<p class="docText">Note that the classes returned by the <tt>getXxxInstance</tt> 
factory methods are not actually of type <tt>NumberFormat</tt>. The <tt>
NumberFormat</tt> type is an abstract class, and the actual formatters belong to 
one of its subclasses.</p>
<p class="docText">The factory methods merely know how to locate the object that 
belongs to a particular locale.</p>
<p class="docText">It is quite obvious that it takes effort to produce a 
formatter object for a particular locale. Although the SDK supports only a 
limited number of localized formatters, more should follow over time, and you 
can, of course, write your own.</p>
<p class="docText">You can get a list of the currently supported locales with 
the static <tt>getAvailableLocales</tt> method. That method returns an array of 
the locales for which number formatter objects can be obtained.</p>
<p class="docText">The sample program for this section lets you experiment with 
number formatters (see <a class="docLink" href="#ch10fig01">Figure 10-1</a>). 
The combo box at the top of the figure contains all locales with number 
formatters. You can choose between number, currency, and percentage formatters. 
Each time you make another choice, the number in the text field is reformatted. 
If you go through a few locales, then you get a good impression of how many ways 
there are to format a number or currency value. You can also type a different 
number and click on the Parse button to call the <tt>parse</tt> method, which 
tries to parse what you entered. If your input is successfully parsed, then it 
is passed to <tt>format</tt> and the result is displayed. If parsing fails, then 
a &quot;Parse error&quot; message is displayed in the text field.</p>
<center>
<h5 id="ch10fig01" class="docFigureTitle">Figure 10-1. The <tt>NumberFormatTest</tt> program</h5>
<p>
<img alt="graphics/10fig01.gif" src="10fig01.gif" border="0" width="400" height="200"><br>
&nbsp;</p>
</center>
<p class="docText">The code, shown in <a class="docLink" href="#ch10list01">
Example 10-1</a>, is fairly straightforward. In the constructor, we call <tt>
NumberFormat.getAvailableLocales</tt>. For each locale, we call <tt>
getDisplayName</tt>, and we fill a combo box with the strings that the <tt>
getDisplayName</tt> method returns. Whenever the user selects another locale or 
clicks on one of the radio buttons, we create a new formatter object and update 
the text field. When the user clicks on the Parse button, we call the <tt>parse</tt> 
method to do the actual parsing, based on the locale selected.</p>
<h5 id="ch10list01" class="docExampleTitle">Example 10-1 NumberFormatTest.java</h5>
<pre>  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.text.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program demonstrates formatting numbers under
  9.    various locales.
 10. */
 11. public class NumberFormatTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new NumberFormatFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame contains radio buttons to select a number format,
 23.    a combo box to pick a locale, a text field to display
 24.    a formatted number, and a button to parse the text field
 25.    contents.
 26. */
 27. class NumberFormatFrame extends JFrame
 28.{
 29.    public NumberFormatFrame()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?