KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > wingset > JavaScriptListenerExample


1 /*
2  * $Id: JavaScriptListenerExample.java,v 1.8 2005/06/03 13:17:17 blueshift Exp $
3  * Copyright 2000,2005 wingS development team.
4  *
5  * This file is part of wingS (http://www.j-wings.org).
6  *
7  * wingS is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation; either version 2.1
10  * of the License, or (at your option) any later version.
11  *
12  * Please see COPYING for the complete licence.
13  */

14 package wingset;
15
16 import org.wings.*;
17 import org.wings.style.CSSProperty;
18 import org.wings.script.JavaScriptEvent;
19 import org.wings.script.JavaScriptListener;
20
21 import java.awt.*;
22 import java.awt.event.ActionEvent JavaDoc;
23 import java.awt.event.ActionListener JavaDoc;
24 import java.text.DecimalFormat JavaDoc;
25 import java.text.DecimalFormatSymbols JavaDoc;
26 import java.text.NumberFormat JavaDoc;
27 import java.util.Locale JavaDoc;
28
29 /**
30  * Create some text fields and add two listeners: a standard server side
31  * listener, that does a numerical calculation on the fields and a client
32  * side JavaScript Listener that allows to calculate these fields as well.
33  *
34  * @author <a HREF="mailto:H.Zeller@acm.org">Henner Zeller</a>
35  * @version $Revision: 1.8 $
36  */

37 public class JavaScriptListenerExample
38         extends WingSetPane {
39     /**
40      * The JavaScript code that is executed on any change of input fields.
41      * The curly braces with a number in it are replaced by the numbered
42      * SComponent argument.
43      */

44     private final static String JavaDoc JS_ADD_SCRIPT =
45             "document.getElementById('{2}').getElementsByTagName('input')[0].value" +
46             " = ((1.0 * document.getElementById('{0}').getElementsByTagName('input')[0].value)" +
47             " + (1.0 * document.getElementById('{1}').getElementsByTagName('input')[0].value));";
48
49     private final static DecimalFormatSymbols JavaDoc DSYM
50             = new DecimalFormatSymbols JavaDoc(Locale.US); // '.' as fraction separator
51

52     public SComponent createExample() {
53         SPanel p = new SPanel();
54         p.add(new SLabel("The client side can handle simple events by JavaScript listeners. In this example, numbers are added locally."));
55
56         final STextField firstField = createNumberField();
57         final STextField secondField = createNumberField();
58         final STextField sumField = createNumberField();
59         SButton serverCalcButton = new SButton("sum");
60
61         firstField.setFocusTraversalIndex(1);
62         secondField.setFocusTraversalIndex(2);
63
64         SGridLayout gridLayout = new SGridLayout(2);
65         gridLayout.setHgap(4);
66         gridLayout.setVgap(4);
67
68         SForm form = new SForm(gridLayout);
69         form.add(new SLabel("Value #1"));
70         form.add(firstField);
71         form.add(new SLabel("Value #2"));
72         form.add(secondField);
73         form.add(new SLabel("Sum"));
74         form.add(sumField);
75         form.add(new SLabel("Server calculation"));
76         form.add(serverCalcButton);
77
78         /*
79          * The server side listener
80          */

81         serverCalcButton.addActionListener(new ActionListener JavaDoc() {
82             public void actionPerformed(ActionEvent JavaDoc ev) {
83                 doCalculation(firstField, secondField, sumField);
84             }
85         });
86
87         /*
88          * add the client side script listener. The variables
89          * in curly braces are replaced by the actual IDs of the components.
90          */

91         SComponent[] jsParams = new SComponent[]{firstField, secondField,
92                                                  sumField};
93         JavaScriptListener jsListener;
94         jsListener = new JavaScriptListener(JavaScriptEvent.ON_CHANGE,
95                 JS_ADD_SCRIPT,
96                 jsParams);
97
98         firstField.addScriptListener(jsListener);
99         secondField.addScriptListener(jsListener);
100
101         // any change to the sum field: no way, recalculate from source fields
102
sumField.addScriptListener(jsListener);
103
104         p.add(form);
105         return p;
106     }
107
108     /**
109      * do the calculation and normalize the output fields.
110      */

111     private void doCalculation(STextField a, STextField b, STextField sum) {
112         double aNum = parseNumber(a);
113         double bNum = parseNumber(b);
114         if (Double.isNaN(aNum) || Double.isNaN(bNum)) {
115             sum.setBackground(Color.RED);
116             sum.setText("?");
117         } else {
118             sum.setBackground(null);
119             /*
120              * normalize the output: set the same number of decimal
121              * digits for all fields.
122              */

123             int decimalsNeeded = Math.max(fractionDecimals(aNum),
124                     fractionDecimals(bNum));
125             NumberFormat JavaDoc fmt;
126             fmt = new DecimalFormat JavaDoc("#.#", DSYM);
127             fmt.setMinimumFractionDigits(decimalsNeeded);
128
129             a.setText(fmt.format(aNum));
130             b.setText(fmt.format(bNum));
131             sum.setText(fmt.format(aNum + bNum));
132         }
133     }
134
135     /**
136      * returns the number of decimals needed to display the given
137      * number
138      */

139     private int fractionDecimals(double number) {
140         // FIXME: is there a simple and more efficient way ?
141
NumberFormat JavaDoc fmt = new DecimalFormat JavaDoc("#.########");
142         String JavaDoc fractionStr = fmt.format(Math.IEEEremainder(number, 1.0));
143         return fractionStr.length() - 2;
144     }
145
146     /**
147      * parse a number in a text field. Assume an empty text field
148      * to be '0', non-parseable values are NaN.
149      */

150     private double parseNumber(STextField field) {
151         String JavaDoc text = field.getText().trim();
152         if (text.length() == 0) {
153             text = "0";
154         }
155         double result = Double.NaN;
156         try {
157             result = Double.parseDouble(text);
158             field.setBackground(null);
159         } catch (Exception JavaDoc e) {
160             field.setBackground(Color.RED);
161         }
162         return result;
163     }
164
165     private STextField createNumberField() {
166         STextField field = new STextField();
167         field.setAttribute(CSSProperty.TEXT_ALIGN, "right");
168         return field;
169     }
170 }
171
172
173
Popular Tags