1 /*
2  * Copyright 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 package com.google.gwt.sample.showcase.client.content.i18n;
17 
18 import com.google.gwt.core.client.GWT;
19 import com.google.gwt.core.client.RunAsyncCallback;
20 import com.google.gwt.event.dom.client.ChangeEvent;
21 import com.google.gwt.event.dom.client.ChangeHandler;
22 import com.google.gwt.event.dom.client.KeyUpEvent;
23 import com.google.gwt.event.dom.client.KeyUpHandler;
24 import com.google.gwt.i18n.client.Constants;
25 import com.google.gwt.i18n.client.NumberFormat;
26 import com.google.gwt.sample.showcase.client.ContentWidget;
27 import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseData;
28 import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseSource;
29 import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseStyle;
30 import com.google.gwt.user.client.rpc.AsyncCallback;
31 import com.google.gwt.user.client.ui.Grid;
32 import com.google.gwt.user.client.ui.Label;
33 import com.google.gwt.user.client.ui.ListBox;
34 import com.google.gwt.user.client.ui.TextBox;
35 import com.google.gwt.user.client.ui.Widget;
36 
37 /**
38  * Example file.
39  */
40 @ShowcaseStyle(".cw-RedText")
41 public class CwNumberFormat extends ContentWidget {
42   /**
43    * The constants used in this Content Widget.
44    */
45   @ShowcaseSource
46   public static interface CwConstants extends Constants {
cwNumberFormatDescription()47     String cwNumberFormatDescription();
48 
cwNumberFormatFailedToParseInput()49     String cwNumberFormatFailedToParseInput();
50 
cwNumberFormatFormattedLabel()51     String cwNumberFormatFormattedLabel();
52 
cwNumberFormatInvalidPattern()53     String cwNumberFormatInvalidPattern();
54 
cwNumberFormatName()55     String cwNumberFormatName();
56 
cwNumberFormatPatternLabel()57     String cwNumberFormatPatternLabel();
58 
cwNumberFormatPatterns()59     String[] cwNumberFormatPatterns();
60 
cwNumberFormatValueLabel()61     String cwNumberFormatValueLabel();
62   }
63 
64   /**
65    * The {@link NumberFormat} that is currently being applied.
66    */
67   private NumberFormat activeFormat = null;
68 
69   /**
70    * An instance of the constants.
71    */
72   @ShowcaseData
73   private final CwConstants constants;
74 
75   /**
76    * The {@link Label} where the formatted value is displayed.
77    */
78   @ShowcaseData
79   private Label formattedBox = null;
80 
81   /**
82    * The {@link TextBox} that displays the current pattern.
83    */
84   @ShowcaseData
85   private TextBox patternBox = null;
86 
87   /**
88    * The {@link ListBox} that holds the patterns.
89    */
90   @ShowcaseData
91   private ListBox patternList = null;
92 
93   /**
94    * The {@link TextBox} where the user enters a value.
95    */
96   @ShowcaseData
97   private TextBox valueBox = null;
98 
99   /**
100    * Constructor.
101    *
102    * @param constants the constants
103    */
CwNumberFormat(CwConstants constants)104   public CwNumberFormat(CwConstants constants) {
105     super(constants.cwNumberFormatName(), constants.cwNumberFormatDescription(),
106         true);
107     this.constants = constants;
108   }
109 
110   /**
111    * Initialize this example.
112    */
113   @ShowcaseSource
114   @Override
onInitialize()115   public Widget onInitialize() {
116     // Use a Grid to layout the content
117     Grid layout = new Grid(4, 2);
118     layout.setCellSpacing(5);
119 
120     // Add a field to select the pattern
121     patternList = new ListBox();
122     patternList.setWidth("17em");
123     String[] patterns = constants.cwNumberFormatPatterns();
124     for (String pattern : patterns) {
125       patternList.addItem(pattern);
126     }
127     patternList.addChangeHandler(new ChangeHandler() {
128       public void onChange(ChangeEvent event) {
129         updatePattern();
130       }
131     });
132     layout.setHTML(0, 0, constants.cwNumberFormatPatternLabel());
133     layout.setWidget(0, 1, patternList);
134 
135     // Add a field to display the pattern
136     patternBox = new TextBox();
137     patternBox.setWidth("17em");
138     patternBox.addKeyUpHandler(new KeyUpHandler() {
139       public void onKeyUp(KeyUpEvent event) {
140         updatePattern();
141       }
142     });
143     layout.setWidget(1, 1, patternBox);
144 
145     // Add a field to set the value
146     valueBox = new TextBox();
147     valueBox.setWidth("17em");
148     valueBox.setText("31415926535.897932");
149     valueBox.addKeyUpHandler(new KeyUpHandler() {
150       public void onKeyUp(KeyUpEvent event) {
151         updateFormattedValue();
152       }
153     });
154     layout.setHTML(2, 0, constants.cwNumberFormatValueLabel());
155     layout.setWidget(2, 1, valueBox);
156 
157     // Add a field to display the formatted value
158     formattedBox = new Label();
159     formattedBox.setWidth("17em");
160     layout.setHTML(3, 0, constants.cwNumberFormatFormattedLabel());
161     layout.setWidget(3, 1, formattedBox);
162 
163     // Return the layout Widget
164     updatePattern();
165     return layout;
166   }
167 
168   @Override
asyncOnInitialize(final AsyncCallback<Widget> callback)169   protected void asyncOnInitialize(final AsyncCallback<Widget> callback) {
170     GWT.runAsync(CwNumberFormat.class, new RunAsyncCallback() {
171 
172       public void onFailure(Throwable caught) {
173         callback.onFailure(caught);
174       }
175 
176       public void onSuccess() {
177         callback.onSuccess(onInitialize());
178       }
179     });
180   }
181 
182   /**
183    * Show an error message. Pass in null to clear the error message.
184    *
185    * @param errorMsg the error message
186    */
187   @ShowcaseSource
showErrorMessage(String errorMsg)188   private void showErrorMessage(String errorMsg) {
189     if (errorMsg == null) {
190       formattedBox.removeStyleName("cw-RedText");
191     } else {
192       formattedBox.setText(errorMsg);
193       formattedBox.addStyleName("cw-RedText");
194     }
195   }
196 
197   /**
198    * Update the formatted value based on the user entered value and pattern.
199    */
200   @ShowcaseSource
updateFormattedValue()201   private void updateFormattedValue() {
202     String sValue = valueBox.getText();
203     if (!sValue.equals("")) {
204       try {
205         double value = Double.parseDouble(sValue);
206         String formattedValue = activeFormat.format(value);
207         formattedBox.setText(formattedValue);
208         showErrorMessage(null);
209       } catch (NumberFormatException e) {
210         showErrorMessage(constants.cwNumberFormatFailedToParseInput());
211       }
212     } else {
213       formattedBox.setText("<None>");
214     }
215   }
216 
217   /**
218    * Update the selected pattern based on the pattern in the list.
219    */
220   @ShowcaseSource
updatePattern()221   private void updatePattern() {
222     switch (patternList.getSelectedIndex()) {
223       case 0:
224         activeFormat = NumberFormat.getDecimalFormat();
225         patternBox.setText(activeFormat.getPattern());
226         patternBox.setEnabled(false);
227         break;
228       case 1:
229         activeFormat = NumberFormat.getCurrencyFormat();
230         patternBox.setText(activeFormat.getPattern());
231         patternBox.setEnabled(false);
232         break;
233       case 2:
234         activeFormat = NumberFormat.getScientificFormat();
235         patternBox.setText(activeFormat.getPattern());
236         patternBox.setEnabled(false);
237         break;
238       case 3:
239         activeFormat = NumberFormat.getPercentFormat();
240         patternBox.setText(activeFormat.getPattern());
241         patternBox.setEnabled(false);
242         break;
243       case 4:
244         patternBox.setEnabled(true);
245         String pattern = patternBox.getText();
246         try {
247           activeFormat = NumberFormat.getFormat(pattern);
248         } catch (IllegalArgumentException e) {
249           showErrorMessage(constants.cwNumberFormatInvalidPattern());
250           return;
251         }
252         break;
253     }
254 
255     // Update the formatted value
256     updateFormattedValue();
257   }
258 }
259