

























Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Java Internacionalización
Tipologia: Resumos
1 / 33
Esta página não é visível na pré-visualização
Não perca as partes importantes!


























36-2 Chapter 36 Internationalization
36.1 Introduction
36.2 The Locale Class
new Locale( "no" , "NO" , "B" );
Point
Key
Point
Key
36-4 Chapter 36 Internationalization
Locale.CHINESE , Locale.ENGLISH , Locale.FRENCH , Locale.GERMAN , Locale.ITALIAN , Locale.JAPANESE , Locale.KOREAN , Locale.SIMPLIFIED_CHINESE , and Locale.TRADITIONAL_CHINESE
Tip You can invoke the static method getAvailableLocales() in the Locale class to obtain all the available locales supported in the system. For example,
Locale[] availableLocales = Calendar.getAvailableLocales();
returns all the locales in an array.
Tip Your machine has a default locale. You may override it by supplying the language and region parameters when you run the program, as follows:
java –Duser.language=zh –Duser.region=CN MainClass
36.2.1 How does Java support international characters in languages like Chinese and Arabic? 36.2.2 How do you construct a Locale object? How do you get all the available locales
36.2.3 How do you create a locale for the French-speaking region of Canada? How do you
36.3 Displaying Date and Time
36.3.1 The TimeZone Class
Point
Check
Point
Key
36.3 Displaying Date and Time 36-
36.3.2 The DateFormat Class
java.text.DateFormat +format(date: Date): String +getDateInstance(): DateFormat +getDateInstance(dateStyle: int): DateFormat +getDateInstance(dateStyle: int, aLocale: Locale): DateFormat +getDateTimeInstance(): DateFormat
+getDateTimeInstance(dateStyle: int, timeStyle: int): DateFormat +getDateTimeInstance(dateStyle: int, timeStyle: int, aLocale: Locale): DateFormat +getInstance(): DateFormat
Formats a date into a date/time string. Gets the date formatter with the default formatting style for the default locale. Gets the date formatter with the given formatting style for the default locale. Gets the date formatter with the given formatting style for the given locale.
Gets the date and time formatter with the default formatting style for the default locale. Gets the date and time formatter with the given date and time formatting styles for the default locale. Gets the date and time formatter with the given formatting styles for the given locale. Gets a default date and time formatter that uses the SHORT style for both the date and the time.
GregorianCalendar calendar = new GregorianCalendar(); DateFormat formatter = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL, Locale.US); TimeZone timeZone = TimeZone.getTimeZone( "CST" ); formatter.setTimeZone(timeZone); System.out.println( "The local time is " + formatter.format(calendar.getTime()));
36.3.3 The SimpleDateFormat Class
public SimpleDateFormat(String pattern)
36.3 Displaying Date and Time 36-
WorldClockApp
+start(primaryStage: Stage) : void +main(args: String[]): void
javafx.application.Application
WorldClockControl -clock: WorldClock -cboLocales: ComboBox
WorldClock -timeZone: TimeZone -locale: Locale -clock: ClockPane -lblDigitTime: Label
+WorldClock() +setTimeZone(timeZone: TimeZone): void +setLocale(locale: Locale): void -setCurrentTime(): void
1 1 1 1
javafx.scene.layout.BorderPane javafx.scene.layout.BorderPane
lisTing 36.1 WorldClock.java
1 import java.util.Calendar; 2 import java.util.TimeZone; 3 import java.util.GregorianCalendar; 4 import java.text.*; 5 import java.util.Locale; 6 import javafx.animation.KeyFrame; 7 import javafx.animation.Timeline; 8 import javafx.event.ActionEvent; 9 import javafx.event.EventHandler; 10 import javafx.geometry.Pos; 11 import javafx.scene.control.Label;
36-8 Chapter 36 Internationalization
12 import javafx.scene.layout.BorderPane; 13 import javafx.util.Duration; 14 15 public class WorldClock extends BorderPane { 16 private TimeZone timeZone = TimeZone.getTimeZone( "EST" ); 17 private Locale locale = Locale.getDefault(); 18 private ClockPane clock = new ClockPane(); // Still clock 19 private Label lblDigitTime = new Label(); 20 21 public WorldClock() { 22 setCenter(clock); 23 setBottom(lblDigitTime); 24 BorderPane.setAlignment(lblDigitTime, Pos.CENTER); 25 26 EventHandler
lisTing 36.2 WorldClockControl.java
1 import java.util.*; 2 import javafx.geometry.Pos; 3 import javafx.scene.control.ComboBox; 4 import javafx.scene.control.Label; 5 import javafx.scene.layout.BorderPane; 6 import javafx.scene.layout.GridPane; 7 8 public class WorldClockControl extends BorderPane {
36-10 Chapter 36 Internationalization
70 cboTimeZones.getSelectionModel().selectFirst(); 71 } 72 }
lisTing 36.3 WorldClockApp.java
1 import javafx.application.Application; 2 import javafx.scene.Scene; 3 import javafx.stage.Stage; 4 5 public class WorldClockApp extends Application { 6 @Override // Override the start method in the Application class 7 public void start(Stage primaryStage) { 8 // Create a scene and place it in the stage 9 Scene scene = new Scene( new WorldClockControl(), 450 , 350 ); 10 primaryStage.setTitle( "WorldClockApp" ); // Set the stage title 11 primaryStage.setScene(scene); // Place the scene in the stage 12 primaryStage.show(); // Display the stage 13 } 14 }
36.3.6 Example: Displaying a Calendar
36.3 Displaying Date and Time 36-
lisTing 36.4 CalendarPane.java
1 import java.text.DateFormatSymbols; 2 import java.text.SimpleDateFormat; 3 import java.util.Calendar; 4 import java.util.GregorianCalendar; 5 import java.util.Locale; 6 import javafx.geometry.Pos; 7 import javafx.scene.control.Label; 8 import javafx.scene.layout.BorderPane; 9 import javafx.scene.layout.GridPane; 10 import javafx.scene.paint.Color; 11 import javafx.scene.text.TextAlignment; 12 13 public class CalendarPane extends BorderPane { 14 // The header label 15 private Label lblHeader = new Label(); 16 17 // Maximum number of labels to display day names and days 18 private Label[] lblDay = new Label[ 49 ]; 19 20 private Calendar calendar; 21 private int month; // The specified month 22 private int year; // The specified year 23 private Locale locale = Locale.CHINA; 24 25 public CalendarPane() { 26 // Create labels for displaying days 27 for ( int i = 0 ; i < 49 ; i++) { 28 lblDay[i] = new Label(); 29 lblDay[i].setTextAlignment(TextAlignment.RIGHT);
CalendarPane
-month: int -year: int -calendar: java.util.Calendar -locale: Locale
+getMonth(): int +setMonth(newMonth: int): void +getYear(): int +setYear(newYear: int): void +setLocale(newLocale: Locale): void +showHeader(): void +showDayNames(): void +showDays(): void
CalendarApp
-calendarPane: CalendarPane -cboLocale: ComboBox
+start(primaryStage: Stage): void +main(args: String[]): void
javafx.scene.layout.BorderPane javafx.application.Application
1 1
36.3 Displaying Date and Time 36-
90 lblDay[i + 7 ].setText(daysInPrecedingMonth 91 - startingDayOfMonth + 2 + i + "" ); 92 } 93 94 // Display days of this month 95 int daysInCurrentMonth = calendar.getActualMaximum( 96 Calendar.DAY_OF_MONTH); 97 for ( int i = 1 ; i <= daysInCurrentMonth; i++) { 98 lblDay[i - 2 + startingDayOfMonth + 7 ].setTextFill(Color.BLACK); 99 lblDay[i - 2 + startingDayOfMonth + 7 ].setText(i + "" ); 100 } 101 102 // Fill the calendar with the days after this month 103 int j = 1 ; 104 for ( int i = daysInCurrentMonth - 1 + startingDayOfMonth + 7 ; 105 i < 49 ; i++) { 106 lblDay[i].setTextFill(Color.LIGHTGRAY); 107 lblDay[i].setText(j++ + "" ); 108 } 109 } 110 111 /** Set the calendar to the first day of the 112 * specified month and year 113 */ 114 public void updateCalendar() { 115 calendar.set(Calendar.YEAR, year); 116 calendar.set(Calendar.MONTH, month); 117 calendar.set(Calendar.DATE, 1 ); 118 } 119 120 public int getMonth() { 121 return month; 122 } 123 124 public void setMonth( int newMonth) { 125 month = newMonth; 126 updateCalendar(); 127 showHeader(); 128 showDays(); 129 } 130 131 public int getYear() { 132 return year; 133 } 134 135 public void setYear( int newYear) { 136 year = newYear; 137 updateCalendar(); 138 showHeader(); 139 showDays(); 140 } 141 142 public void setLocale(Locale locale) { 143 this .locale = locale; 144 updateCalendar(); 145 showDayNames(); 146 showHeader(); 147 showDays(); 148 } 149 }
36-14 Chapter 36 Internationalization
lisTing 36.5 CalendarApp.java
1 import java.util.Locale; 2 import javafx.application.Application; 3 import javafx.geometry.Pos; 4 import javafx.scene.Scene; 5 import javafx.scene.control.Button; 6 import javafx.scene.control.ComboBox; 7 import javafx.scene.control.Label; 8 import javafx.scene.layout.BorderPane; 9 import javafx.scene.layout.HBox; 10 import javafx.stage.Stage; 11 12 public class CalendarApp extends Application { 13 private CalendarPane calendarPane = new CalendarPane(); 14 private Button btPrior = new Button( "Prior" ); 15 private Button btNext = new Button( "Next" ); 16 private ComboBox
36-16 Chapter 36 Internationalization
36.4 Formatting Numbers
Point
Key
java.text.NumberFormat +getInstance(): NumberFormat +getInstance(locale: Locale): NumberFormat +getIntegerInstance(): NumberFormat
+format (number: long): String
+getMaximumFractionDigits(): int
+setMaximumFractionDigits(newValue: int): void
+getMinimumFractionDigits(): int
+setMinimumFractionDigits(newValue: int): void
+getMaximumIntegerDigits(): int
+setMaximumIntegerDigits(newValue: int): void
+getMinimumIntegerDigits(): int
+setMinimumIntegerDigits(newValue: int): void +isGroupingUsed(): boolean
+setGroupingUsed(newValue: boolean): void +parse(source: String): Number +getAvailableLocales(): Locale[]
Returns a default number format for the default locale. Returns a default number format for the specified locale. Returns an integer number format for the default locale. Returns an integer number format for the specified locale.
Returns a currency format for the current default locale. Same as getInstance(). Same as getInstance(locale).
Returns a percentage format for the default locale. Returns a percentage format for the specified locale.
Formats a floating-point number.
Formats an integer.
Returns the maximum number of allowed fraction digits.
Sets the maximum number of allowed fraction digits.
Returns the minimum number of allowed fraction digits.
Sets the minimum number of allowed fraction digits.
Returns the maximum number of allowed integer digits in a fraction number.
Sets the maximum number of allowed integer digits in a fraction number.
Returns the minimum number of allowed integer digits in a fraction number.
Sets the minimum number of allowed integer digits in a fraction number. Returns true if grouping is used in this format. For example, in the English locale, with grouping on, the number 1234567 is formatted as "1,234,567". Sets whether or not grouping will be used in this format. Parses string into a number. Gets the set of locales for which NumberFormats are installed.
36.4.1 Plain Number Format
36.4 Formatting Numbers 36-
NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE); System.out.println(numberFormat.format(5000.555));
36.4.2 Currency Format
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); System.out.println(currencyFormat.format(5000.555));
36.4.3 Percent Format
NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.US); System.out.println(percentFormat.format(0.555367));
36.4.4 Parsing Numbers
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); try { Number number = currencyFormat.parse("$5,000.56"); System.out.println(number.doubleValue()); } catch (java.text.ParseException ex) { System.out.println( "Parse failed"); }
36.4 Formatting Numbers 36-
23 private TextField tfFormattedInterestRate = new TextField(); 24 private TextField tfFormattedNumberOfYears = new TextField(); 25 private TextField tfFormattedLoanAmount = new TextField(); 26 27 // Text fields for monthly payment and total payment 28 private TextField tfTotalPayment = new TextField(); 29 private TextField tfMonthlyPayment = new TextField(); 30 31 // Compute button 32 private Button btCompute = new Button( "Compute" ); 33 34 // Current locale 35 private Locale locale = Locale.getDefault(); 36 37 // Declare locales to store available locales 38 private Locale locales[] = Calendar.getAvailableLocales(); 39 40 /** Initialize the combo box */ 41 public void initializeComboBox() { 42 // Add locale names to the combo box 43 for ( int i = 0 ; i < locales.length; i++) 44 cboLocale.getItems().add(locales[i].getDisplayName()); 45 } 46 47 @Override // Override the start method in the Application class 48 public void start(Stage primaryStage) { 49 initializeComboBox(); 50 51 // Pane to hold the combo box for selecting locales 52 HBox hBox = new HBox( 5 ); 53 hBox.getChildren().addAll( 54 new Label( "Choose a Locale" ), cboLocale); 55 56 // Pane to hold the input 57 GridPane gridPane = new GridPane(); 58 gridPane.add( new Label( "Interest Rate" ), 0 , 0 ); 59 gridPane.add(tfInterestRate, 1 , 0 ); 60 gridPane.add(tfFormattedInterestRate, 2 , 0 ); 61 gridPane.add( new Label( "Number of Years" ), 0 , 1 ); 62 gridPane.add(tfNumberOfYears, 1 , 1 ); 63 gridPane.add(tfFormattedNumberOfYears, 2 , 1 ); 64 gridPane.add( new Label( "Loan Amount" ), 0 , 2 ); 65 gridPane.add(tfLoanAmount, 1 , 2 ); 66 gridPane.add(tfFormattedLoanAmount, 2 , 2 ); 67 68 // Pane to hold the output 69 GridPane gridPaneOutput = new GridPane(); 70 gridPaneOutput.add( new Label( "Monthly Payment" ), 0 , 0 ); 71 gridPaneOutput.add(tfMonthlyPayment, 1 , 0 ); 72 gridPaneOutput.add( new Label( "Total Payment" ), 0 , 1 ); 73 gridPaneOutput.add(tfTotalPayment, 1 , 1 ); 74 75 // Set text field alignment 76 tfFormattedInterestRate.setAlignment(Pos.BASELINE_RIGHT); 77 tfFormattedNumberOfYears.setAlignment(Pos.BASELINE_RIGHT); 78 tfFormattedLoanAmount.setAlignment(Pos.BASELINE_RIGHT); 79 tfTotalPayment.setAlignment(Pos.BASELINE_RIGHT); 80 tfMonthlyPayment.setAlignment(Pos.BASELINE_RIGHT); 81 82 // Set editable false 83 tfFormattedInterestRate.setEditable( false );
36-20 Chapter 36 Internationalization
84 tfFormattedNumberOfYears.setEditable( false ); 85 tfFormattedLoanAmount.setEditable( false ); 86 tfTotalPayment.setEditable( false ); 87 tfMonthlyPayment.setEditable( false ); 88 89 VBox vBox = new VBox( 5 ); 90 vBox.getChildren().addAll(hBox, 91 new Label( "Enter Annual Interest Rate, " + 92 "Number of Years, and Loan Amount" ), gridPane, 93 new Label( "Payment" ), gridPaneOutput, btCompute); 94 95 // Create a scene and place it in the stage 96 Scene scene = new Scene(vBox, 400 , 300 ); 97 primaryStage.setTitle( "NumberFormatDemo" ); // Set the stage title 98 primaryStage.setScene(scene); // Place the scene in the stage 99 primaryStage.show(); // Display the stage 100 101 // Register listeners 102 cboLocale.setOnAction(e -> { 103 locale = locales[cboLocale 104 .getSelectionModel().getSelectedIndex()]; 105 computeLoan(); 106 }); 107 108 btCompute.setOnAction(e -> computeLoan()); 109 } 110 111 /** Compute payments and display results locale-sensitive format */ 112 private void computeLoan() { 113 // Retrieve input from user 114 double loan = new Double(tfLoanAmount.getText()).doubleValue(); 115 double interestRate = 116 new Double(tfInterestRate.getText()).doubleValue() / 1240 ; 117 int numberOfYears = 118 new Integer(tfNumberOfYears.getText()).intValue(); 119 120 // Calculate payments 121 double monthlyPayment = loan * interestRate/ 122 ( 1 - (Math.pow( 1 / ( 1 + interestRate), numberOfYears * 12 ))); 123 double totalPayment = monthlyPayment * numberOfYears * 12 ; 124 125 // Get formatters 126 NumberFormat percentFormatter = 127 NumberFormat.getPercentInstance(locale); 128 NumberFormat currencyForm = 129 NumberFormat.getCurrencyInstance(locale); 130 NumberFormat numberForm = NumberFormat.getNumberInstance(locale); 131 percentFormatter.setMinimumFractionDigits( 2 ); 132 133 // Display formatted input 134 tfFormattedInterestRate.setText( 135 percentFormatter.format(interestRate * 12 )); 136 tfFormattedNumberOfYears.setText 137 (numberForm.format(numberOfYears)); 138 tfFormattedLoanAmount.setText(currencyForm.format(loan)); 139 140 // Display results in currency format 141 tfMonthlyPayment.setText(currencyForm.format(monthlyPayment)); 142 tfTotalPayment.setText(currencyForm.format(totalPayment)); 143 } 144 }