KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > text > html > FormView


1 /*
2  * @(#)FormView.java 1.28 05/05/27
3  *
4  * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing.text.html;
8
9 import java.net.*;
10 import java.io.*;
11 import java.awt.*;
12 import java.awt.event.*;
13 import java.util.*;
14 import javax.swing.*;
15 import javax.swing.event.*;
16 import javax.swing.text.*;
17
18 /**
19  * Component decorator that implements the view interface
20  * for form elements, <input>, <textarea>,
21  * and <select>. The model for the component is stored
22  * as an attribute of the the element (using StyleConstants.ModelAttribute),
23  * and is used to build the component of the view. The type
24  * of the model is assumed to of the type that would be set by
25  * <code>HTMLDocument.HTMLReader.FormAction</code>. If there are
26  * multiple views mapped over the document, they will share the
27  * embedded component models.
28  * <p>
29  * The following table shows what components get built
30  * by this view.
31  * <table summary="shows what components get built by this view">
32  * <tr>
33  * <th>Element Type</th>
34  * <th>Component built</th>
35  * </tr>
36  * <tr>
37  * <td>input, type button</td>
38  * <td>JButton</td>
39  * </tr>
40  * <tr>
41  * <td>input, type checkbox</td>
42  * <td>JCheckBox</td>
43  * </tr>
44  * <tr>
45  * <td>input, type image</td>
46  * <td>JButton</td>
47  * </tr>
48  * <tr>
49  * <td>input, type password</td>
50  * <td>JPasswordField</td>
51  * </tr>
52  * <tr>
53  * <td>input, type radio</td>
54  * <td>JRadioButton</td>
55  * </tr>
56  * <tr>
57  * <td>input, type reset</td>
58  * <td>JButton</td>
59  * </tr>
60  * <tr>
61  * <td>input, type submit</td>
62  * <td>JButton</td>
63  * </tr>
64  * <tr>
65  * <td>input, type text</td>
66  * <td>JTextField</td>
67  * </tr>
68  * <tr>
69  * <td>select, size &gt; 1 or multiple attribute defined</td>
70  * <td>JList in a JScrollPane</td>
71  * </tr>
72  * <tr>
73  * <td>select, size unspecified or 1</td>
74  * <td>JComboBox</td>
75  * </tr>
76  * <tr>
77  * <td>textarea</td>
78  * <td>JTextArea in a JScrollPane</td>
79  * </tr>
80  * <tr>
81  * <td>input, type file</td>
82  * <td>JTextField</td>
83  * </tr>
84  * </table>
85  *
86  * @author Timothy Prinzing
87  * @author Sunita Mani
88  * @version 1.28 05/27/05
89  */

90 public class FormView extends ComponentView implements ActionListener {
91
92     /**
93      * If a value attribute is not specified for a FORM input element
94      * of type "submit", then this default string is used.
95      *
96      * @deprecated As of 1.3, value now comes from UIManager property
97      * FormView.submitButtonText
98      */

99     @Deprecated JavaDoc
100     public static final String JavaDoc SUBMIT = new String JavaDoc("Submit Query");
101     /**
102      * If a value attribute is not specified for a FORM input element
103      * of type "reset", then this default string is used.
104      *
105      * @deprecated As of 1.3, value comes from UIManager UIManager property
106      * FormView.resetButtonText
107      */

108     @Deprecated JavaDoc
109     public static final String JavaDoc RESET = new String JavaDoc("Reset");
110
111     /**
112      * Used to indicate if the maximum span should be the same as the
113      * preferred span. This is used so that the Component's size doesn't
114      * change if there is extra room on a line. The first bit is used for
115      * the X direction, and the second for the y direction.
116      */

117     private short maxIsPreferred;
118
119     /**
120      * Creates a new FormView object.
121      *
122      * @param elem the element to decorate
123      */

124     public FormView(Element elem) {
125     super(elem);
126     }
127
128     /**
129      * Create the component. This is basically a
130      * big switch statement based upon the tag type
131      * and html attributes of the associated element.
132      */

133     protected Component createComponent() {
134     AttributeSet attr = getElement().getAttributes();
135     HTML.Tag JavaDoc t = (HTML.Tag JavaDoc)
136         attr.getAttribute(StyleConstants.NameAttribute);
137     JComponent c = null;
138     Object JavaDoc model = attr.getAttribute(StyleConstants.ModelAttribute);
139     if (t == HTML.Tag.INPUT) {
140         c = createInputComponent(attr, model);
141     } else if (t == HTML.Tag.SELECT) {
142
143         if (model instanceof OptionListModel JavaDoc) {
144
145         JList list = new JList((ListModel) model);
146         int size = HTML.getIntegerAttributeValue(attr,
147                              HTML.Attribute.SIZE,
148                              1);
149         list.setVisibleRowCount(size);
150         list.setSelectionModel((ListSelectionModel)model);
151         c = new JScrollPane(list);
152         } else {
153         c = new JComboBox((ComboBoxModel) model);
154                 maxIsPreferred = 3;
155         }
156     } else if (t == HTML.Tag.TEXTAREA) {
157         JTextArea area = new JTextArea((Document) model);
158         int rows = HTML.getIntegerAttributeValue(attr,
159                              HTML.Attribute.ROWS,
160                              1);
161         area.setRows(rows);
162         int cols = HTML.getIntegerAttributeValue(attr,
163                              HTML.Attribute.COLS,
164                              20);
165             maxIsPreferred = 3;
166         area.setColumns(cols);
167         c = new JScrollPane(area,
168                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
169                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
170     }
171
172     if (c != null) {
173         c.setAlignmentY(1.0f);
174     }
175     return c;
176     }
177
178
179     /**
180      * Creates a component for an &lt;INPUT&gt; element based on the
181      * value of the "type" attribute.
182      *
183      * @param set of attributes associated with the &lt;INPUT&gt; element.
184      * @param model the value of the StyleConstants.ModelAttribute
185      * @return the component.
186      */

187     private JComponent createInputComponent(AttributeSet attr, Object JavaDoc model) {
188     JComponent c = null;
189     String JavaDoc type = (String JavaDoc) attr.getAttribute(HTML.Attribute.TYPE);
190
191     if (type.equals("submit") || type.equals("reset")) {
192         String JavaDoc value = (String JavaDoc)
193         attr.getAttribute(HTML.Attribute.VALUE);
194         if (value == null) {
195         if (type.equals("submit")) {
196             value = UIManager.getString("FormView.submitButtonText");
197         } else {
198             value = UIManager.getString("FormView.resetButtonText");
199         }
200         }
201         JButton button = new JButton(value);
202         if (model != null) {
203         button.setModel((ButtonModel)model);
204         button.addActionListener(this);
205         }
206         c = button;
207             maxIsPreferred = 3;
208     } else if (type.equals("image")) {
209         String JavaDoc srcAtt = (String JavaDoc) attr.getAttribute(HTML.Attribute.SRC);
210         JButton button;
211         try {
212         URL base = ((HTMLDocument JavaDoc)getElement().getDocument()).getBase();
213         URL srcURL = new URL(base, srcAtt);
214         Icon icon = new ImageIcon(srcURL);
215         button = new JButton(icon);
216         } catch (MalformedURLException e) {
217         button = new JButton(srcAtt);
218         }
219         if (model != null) {
220         button.setModel((ButtonModel)model);
221         button.addMouseListener(new MouseEventListener());
222         }
223         c = button;
224             maxIsPreferred = 3;
225     } else if (type.equals("checkbox")) {
226         c = new JCheckBox();
227         if (model != null) {
228         ((JCheckBox)c).setModel((JToggleButton.ToggleButtonModel) model);
229         }
230             maxIsPreferred = 3;
231     } else if (type.equals("radio")) {
232         c = new JRadioButton();
233         if (model != null) {
234         ((JRadioButton)c).setModel((JToggleButton.ToggleButtonModel)model);
235         }
236             maxIsPreferred = 3;
237     } else if (type.equals("text")) {
238         int size = HTML.getIntegerAttributeValue(attr,
239                              HTML.Attribute.SIZE,
240                              -1);
241         JTextField field;
242         if (size > 0) {
243         field = new JTextField();
244         field.setColumns(size);
245         }
246         else {
247         field = new JTextField();
248         field.setColumns(20);
249         }
250         c = field;
251         if (model != null) {
252         field.setDocument((Document) model);
253         }
254         field.addActionListener(this);
255             maxIsPreferred = 3;
256     } else if (type.equals("password")) {
257         JPasswordField field = new JPasswordField();
258         c = field;
259         if (model != null) {
260         field.setDocument((Document) model);
261         }
262         int size = HTML.getIntegerAttributeValue(attr,
263                              HTML.Attribute.SIZE,
264                              -1);
265             field.setColumns((size > 0) ? size : 20);
266         field.addActionListener(this);
267             maxIsPreferred = 3;
268     } else if (type.equals("file")) {
269             JTextField field = new JTextField();
270         if (model != null) {
271         field.setDocument((Document)model);
272         }
273         int size = HTML.getIntegerAttributeValue(attr, HTML.Attribute.SIZE,
274                              -1);
275             field.setColumns((size > 0) ? size : 20);
276             JButton browseButton = new JButton(UIManager.getString
277                                            ("FormView.browseFileButtonText"));
278             Box box = Box.createHorizontalBox();
279             box.add(field);
280             box.add(Box.createHorizontalStrut(5));
281             box.add(browseButton);
282             browseButton.addActionListener(new BrowseFileAction(
283                                            attr, (Document)model));
284             c = box;
285             maxIsPreferred = 3;
286         }
287     return c;
288     }
289
290
291     /**
292      * Determines the maximum span for this view along an
293      * axis. For certain components, the maximum and preferred span are the
294      * same. For others this will return the value
295      * returned by Component.getMaximumSize along the
296      * axis of interest.
297      *
298      * @param axis may be either View.X_AXIS or View.Y_AXIS
299      * @return the span the view would like to be rendered into >= 0.
300      * Typically the view is told to render into the span
301      * that is returned, although there is no guarantee.
302      * The parent may choose to resize or break the view.
303      * @exception IllegalArgumentException for an invalid axis
304      */

305     public float getMaximumSpan(int axis) {
306         switch (axis) {
307         case View.X_AXIS:
308             if ((maxIsPreferred & 1) == 1) {
309                 super.getMaximumSpan(axis);
310                 return getPreferredSpan(axis);
311             }
312             return super.getMaximumSpan(axis);
313         case View.Y_AXIS:
314             if ((maxIsPreferred & 2) == 2) {
315                 super.getMaximumSpan(axis);
316                 return getPreferredSpan(axis);
317             }
318             return super.getMaximumSpan(axis);
319         default:
320             break;
321         }
322         return super.getMaximumSpan(axis);
323     }
324
325
326     /**
327      * Responsible for processeing the ActionEvent.
328      * If the element associated with the FormView,
329      * has a type of "submit", "reset", "text" or "password"
330      * then the action is processed. In the case of a "submit"
331      * the form is submitted. In the case of a "reset"
332      * the form is reset to its original state.
333      * In the case of "text" or "password", if the
334      * element is the last one of type "text" or "password",
335      * the form is submitted. Otherwise, focus is transferred
336      * to the next component in the form.
337      *
338      * @param evt the ActionEvent.
339      */

340     public void actionPerformed(ActionEvent evt) {
341     Element element = getElement();
342     StringBuffer JavaDoc dataBuffer = new StringBuffer JavaDoc();
343     HTMLDocument JavaDoc doc = (HTMLDocument JavaDoc)getDocument();
344     AttributeSet attr = element.getAttributes();
345     
346     String JavaDoc type = (String JavaDoc) attr.getAttribute(HTML.Attribute.TYPE);
347
348     if (type.equals("submit")) {
349         getFormData(dataBuffer);
350         submitData(dataBuffer.toString());
351     } else if (type.equals("reset")) {
352         resetForm();
353     } else if (type.equals("text") || type.equals("password")) {
354         if (isLastTextOrPasswordField()) {
355         getFormData(dataBuffer);
356         submitData(dataBuffer.toString());
357         } else {
358         getComponent().transferFocus();
359         }
360     }
361     }
362
363
364     /**
365      * This method is responsible for submitting the form data.
366      * A thread is forked to undertake the submission.
367      */

368     protected void submitData(String JavaDoc data) {
369     //System.err.println("data ->"+data+"<-");
370
SubmitThread dataThread = new SubmitThread(getElement(), data);
371     dataThread.start();
372     }
373
374
375     /**
376      * The SubmitThread is responsible for submitting the form.
377      * It performs a POST or GET based on the value of method
378      * attribute associated with HTML.Tag.FORM. In addition to
379      * submitting, it is also responsible for display the
380      * results of the form submission.
381      */

382     class SubmitThread extends Thread JavaDoc {
383
384     String JavaDoc data;
385     HTMLDocument JavaDoc hdoc;
386     AttributeSet formAttr;
387     URL url;
388     String JavaDoc method;
389     String JavaDoc target;
390     URL actionURL;
391
392     public SubmitThread(Element elem, String JavaDoc data) {
393         this.data = data;
394         hdoc = (HTMLDocument JavaDoc)elem.getDocument();
395             Element formE = getFormElement();
396             if (formE != null) {
397                 formAttr = formE.getAttributes();
398             }
399
400         method = getMethod();
401
402         try {
403         
404         String JavaDoc action = getAction();
405         method = getMethod();
406         target = getTarget();
407         
408         /* if action is null use the base url and ensure that
409            the file name excludes any parameters that may be attached */

410         URL baseURL = hdoc.getBase();
411         if (action == null) {
412             
413             String JavaDoc file = baseURL.getFile();
414             actionURL = new URL(baseURL.getProtocol(),
415                     baseURL.getHost(),
416                     baseURL.getPort(),
417                     file);
418         } else {
419             actionURL = new URL(baseURL, action);
420         }
421         } catch (MalformedURLException m) {
422         actionURL = null;
423         }
424     }
425
426
427     /**
428      * This method is responsible for extracting the
429      * method and action attributes associated with the
430      * &lt;FORM&gt; and using those to determine how (POST or GET)
431      * and where (URL) to submit the form. If action is
432      * not specified, the base url of the existing document is
433      * used. Also, if method is not specified, the default is
434      * GET. Once form submission is done, run uses the
435      * SwingUtilities.invokeLater() method, to load the results
436      * of the form submission into the current JEditorPane.
437      */

438     public void run() {
439
440         if (data.length() > 0) {
441
442         try {
443
444             URLConnection connection;
445
446             // safe assumption since we are in an html document
447
JEditorPane c = (JEditorPane)getContainer();
448                     HTMLEditorKit JavaDoc kit = (HTMLEditorKit JavaDoc)c.getEditorKit();
449                     if (kit.isAutoFormSubmission()) {
450                         if ("post".equals(method)) {
451                             url = actionURL;
452                             connection = url.openConnection();
453                             postData(connection, data);
454                         } else {
455                             /* the default, GET */
456                             url = new URL(actionURL+"?"+data);
457                         }
458         
459                         Runnable JavaDoc callLoadDocument = new Runnable JavaDoc() {
460                             public void run() {
461                 JEditorPane c = (JEditorPane)getContainer();
462                                 if (hdoc.isFrameDocument()) {
463                                     c.fireHyperlinkUpdate(createFormSubmitEvent());
464                                 } else {
465                                     try {
466                                         c.setPage(url);
467                                     } catch (IOException e) {
468                                     }
469                                 }
470                             }
471                         };
472                         SwingUtilities.invokeLater(callLoadDocument);
473                     } else {
474                         c.fireHyperlinkUpdate(createFormSubmitEvent());
475                     }
476                 } catch (MalformedURLException m) {
477                     // REMIND how do we deal with exceptions ??
478
} catch (IOException e) {
479                     // REMIND how do we deal with exceptions ??
480
}
481         }
482     }
483
484     /**
485      * Create an event that notifies about form submission
486      */

487     private FormSubmitEvent JavaDoc createFormSubmitEvent() {
488         FormSubmitEvent.MethodType JavaDoc formMethod =
489         "post".equals(method) ? FormSubmitEvent.MethodType.POST :
490                                         FormSubmitEvent.MethodType.GET;
491         return new FormSubmitEvent JavaDoc(FormView.this,
492                        HyperlinkEvent.EventType.ACTIVATED,
493                        actionURL,
494                        getElement(),
495                        target,
496                        formMethod,
497                        data);
498     }
499
500     /**
501      * Get the value of the target attribute.
502      */

503     private String JavaDoc getTarget() {
504         if (formAttr != null) {
505         String JavaDoc target = (String JavaDoc)formAttr.getAttribute(HTML.Attribute.TARGET);
506         if (target != null) {
507             return target.toLowerCase();
508         }
509         }
510         return "_self";
511     }
512     
513     /**
514      * Get the value of the action attribute.
515      */

516     public String JavaDoc getAction() {
517         if (formAttr == null) {
518         return null;
519         }
520         return (String JavaDoc)formAttr.getAttribute(HTML.Attribute.ACTION);
521     }
522     
523     /**
524      * Get the form's method parameter.
525      */

526     String JavaDoc getMethod() {
527         if (formAttr != null) {
528         String JavaDoc method = (String JavaDoc)formAttr.getAttribute(HTML.Attribute.METHOD);
529         if (method != null) {
530             return method.toLowerCase();
531         }
532         }
533         return null;
534     }
535
536
537     /**
538      * This method is responsible for writing out the form submission
539      * data when the method is POST.
540      *
541      * @param connection to use.
542      * @param data to write.
543      */

544     public void postData(URLConnection connection, String JavaDoc data) {
545         connection.setDoOutput(true);
546         PrintWriter out = null;
547         try {
548         out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
549         out.print(data);
550         out.flush();
551         } catch (IOException e) {
552         // REMIND: should do something reasonable!
553
} finally {
554         if (out != null) {
555             out.close();
556         }
557         }
558     }
559     }
560
561     /**
562      * MouseEventListener class to handle form submissions when
563      * an input with type equal to image is clicked on.
564      * A MouseListener is necessary since along with the image
565      * data the coordinates associated with the mouse click
566      * need to be submitted.
567      */

568     protected class MouseEventListener extends MouseAdapter {
569
570     public void mouseReleased(MouseEvent evt) {
571         String JavaDoc imageData = getImageData(evt.getPoint());
572         imageSubmit(imageData);
573     }
574     }
575
576     /**
577      * This method is called to submit a form in response
578      * to a click on an image -- an &lt;INPUT&gt; form
579      * element of type "image".
580      *
581      * @param imageData the mouse click coordinates.
582      */

583     protected void imageSubmit(String JavaDoc imageData) {
584
585     StringBuffer JavaDoc dataBuffer = new StringBuffer JavaDoc();
586     Element elem = getElement();
587     HTMLDocument JavaDoc hdoc = (HTMLDocument JavaDoc)elem.getDocument();
588     getFormData(dataBuffer);
589     if (dataBuffer.length() > 0) {
590         dataBuffer.append('&');
591     }
592     dataBuffer.append(imageData);
593     submitData(dataBuffer.toString());
594     return;
595     }
596
597     /**
598      * Extracts the value of the name attribute
599      * associated with the input element of type
600      * image. If name is defined it is encoded using
601      * the URLEncoder.encode() method and the
602      * image data is returned in the following format:
603      * name + ".x" +"="+ x +"&"+ name +".y"+"="+ y
604      * otherwise,
605      * "x="+ x +"&y="+ y
606      *
607      * @param point associated with the mouse click.
608      * @return the image data.
609      */

610     private String JavaDoc getImageData(Point point) {
611         
612     String JavaDoc mouseCoords = point.x + ":" + point.y;
613     int sep = mouseCoords.indexOf(':');
614     String JavaDoc x = mouseCoords.substring(0, sep);
615     String JavaDoc y = mouseCoords.substring(++sep);
616     String JavaDoc name = (String JavaDoc) getElement().getAttributes().getAttribute(HTML.Attribute.NAME);
617     
618     String JavaDoc data;
619     if (name == null || name.equals("")) {
620         data = "x="+ x +"&y="+ y;
621     } else {
622         name = URLEncoder.encode(name);
623         data = name + ".x" +"="+ x +"&"+ name +".y"+"="+ y;
624     }
625     return data;
626     }
627
628
629     /**
630      * The following methods provide functionality required to
631      * iterate over a the elements of the form and in the case
632      * of a form submission, extract the data from each model
633      * that is associated with each form element, and in the
634      * case of reset, reinitialize the each model to its
635      * initial state.
636      */

637
638
639     /**
640      * Returns the Element representing the <code>FORM</code>.
641      */

642     private Element getFormElement() {
643         Element elem = getElement();
644         while (elem != null) {
645             if (elem.getAttributes().getAttribute
646                 (StyleConstants.NameAttribute) == HTML.Tag.FORM) {
647                 return elem;
648             }
649             elem = elem.getParentElement();
650         }
651         return null;
652     }
653
654     /**
655      * Iterates over the
656      * element hierarchy, extracting data from the
657      * models associated with the relevant form elements.
658      * "Relevant" means the form elements that are part
659      * of the same form whose element triggered the submit
660      * action.
661      *
662      * @param buffer the buffer that contains that data to submit
663      * @param targetElement the element that triggered the
664      * form submission
665      */

666     void getFormData(StringBuffer JavaDoc buffer) {
667         Element formE = getFormElement();
668         if (formE != null) {
669             ElementIterator it = new ElementIterator(formE);
670             Element next;
671
672             while ((next = it.next()) != null) {
673                 if (isControl(next)) {
674                     String JavaDoc type = (String JavaDoc)next.getAttributes().getAttribute
675                                        (HTML.Attribute.TYPE);
676
677                     if (type != null && type.equals("submit") &&
678                         next != getElement()) {
679                         // do nothing - this submit isnt the trigger
680
} else if (type == null || !type.equals("image")) {
681                         // images only result in data if they triggered
682
// the submit and they require that the mouse click
683
// coords be appended to the data. Hence its
684
// processing is handled by the view.
685
loadElementDataIntoBuffer(next, buffer);
686                     }
687                 }
688             }
689         }
690     }
691
692     /**
693      * Loads the data
694      * associated with the element into the buffer.
695      * The format in which data is appended depends
696      * on the type of the form element. Essentially
697      * data is loaded in name/value pairs.
698      *
699      */

700     private void loadElementDataIntoBuffer(Element elem, StringBuffer JavaDoc buffer) {
701
702     AttributeSet attr = elem.getAttributes();
703     String JavaDoc name = (String JavaDoc)attr.getAttribute(HTML.Attribute.NAME);
704     if (name == null) {
705         return;
706     }
707     String JavaDoc value = null;
708     HTML.Tag JavaDoc tag = (HTML.Tag JavaDoc)elem.getAttributes().getAttribute
709                                   (StyleConstants.NameAttribute);
710
711     if (tag == HTML.Tag.INPUT) {
712         value = getInputElementData(attr);
713     } else if (tag == HTML.Tag.TEXTAREA) {
714         value = getTextAreaData(attr);
715     } else if (tag == HTML.Tag.SELECT) {
716         loadSelectData(attr, buffer);
717     }
718     
719     if (name != null && value != null) {
720         appendBuffer(buffer, name, value);
721     }
722     }
723
724
725     /**
726      * Returns the data associated with an &lt;INPUT&gt; form
727      * element. The value of "type" attributes is
728      * used to determine the type of the model associated
729      * with the element and then the relevant data is
730      * extracted.
731      */

732     private String JavaDoc getInputElementData(AttributeSet attr) {
733     
734     Object JavaDoc model = attr.getAttribute(StyleConstants.ModelAttribute);
735     String JavaDoc type = (String JavaDoc) attr.getAttribute(HTML.Attribute.TYPE);
736     String JavaDoc value = null;
737     
738     if (type.equals("text") || type.equals("password")) {
739         Document doc = (Document)model;
740         try {
741         value = doc.getText(0, doc.getLength());
742         } catch (BadLocationException e) {
743         value = null;
744         }
745     } else if (type.equals("submit") || type.equals("hidden")) {
746         value = (String JavaDoc) attr.getAttribute(HTML.Attribute.VALUE);
747         if (value == null) {
748         value = "";
749         }
750     } else if (type.equals("radio") || type.equals("checkbox")) {
751         ButtonModel m = (ButtonModel)model;
752         if (m.isSelected()) {
753         value = (String JavaDoc) attr.getAttribute(HTML.Attribute.VALUE);
754         if (value == null) {
755             value = "on";
756         }
757         }
758     } else if (type.equals("file")) {
759         Document doc = (Document)model;
760             String JavaDoc path;
761
762         try {
763         path = doc.getText(0, doc.getLength());
764         } catch (BadLocationException e) {
765         path = null;
766         }
767             if (path != null && path.length() > 0) {
768                 value = path;
769 /*
770
771                 try {
772                     Reader reader = new BufferedReader(new FileReader(path));
773                     StringBuffer buffer = new StringBuffer();
774                     char[] cBuff = new char[1024];
775                     int read;
776
777                     try {
778                         while ((read = reader.read(cBuff)) != -1) {
779                             buffer.append(cBuff, 0, read);
780                         }
781                     } catch (IOException ioe) {
782                         buffer = null;
783                     }
784                     try {
785                         reader.close();
786                     } catch (IOException ioe) {}
787                     if (buffer != null) {
788                         value = buffer.toString();
789                     }
790                 } catch (IOException ioe) {}
791 */

792             }
793         }
794     return value;
795     }
796
797     /**
798      * Returns the data associated with the &lt;TEXTAREA&gt; form
799      * element. This is done by getting the text stored in the
800      * Document model.
801      */

802     private String JavaDoc getTextAreaData(AttributeSet attr) {
803     Document doc = (Document)attr.getAttribute(StyleConstants.ModelAttribute);
804     try {
805         return doc.getText(0, doc.getLength());
806     } catch (BadLocationException e) {
807         return null;
808     }
809     }
810
811
812     /**
813      * Loads the buffer with the data associated with the Select
814      * form element. Basically, only items that are selected
815      * and have their name attribute set are added to the buffer.
816      */

817     private void loadSelectData(AttributeSet attr, StringBuffer JavaDoc buffer) {
818
819     String JavaDoc name = (String JavaDoc)attr.getAttribute(HTML.Attribute.NAME);
820     if (name == null) {
821         return;
822     }
823     Object JavaDoc m = attr.getAttribute(StyleConstants.ModelAttribute);
824     if (m instanceof OptionListModel JavaDoc) {
825         OptionListModel JavaDoc model = (OptionListModel JavaDoc)m;
826         
827         for (int i = 0; i < model.getSize(); i++) {
828         if (model.isSelectedIndex(i)) {
829             Option JavaDoc option = (Option JavaDoc) model.getElementAt(i);
830             appendBuffer(buffer, name, option.getValue());
831         }
832         }
833     } else if (m instanceof ComboBoxModel) {
834         ComboBoxModel model = (ComboBoxModel)m;
835         Option JavaDoc option = (Option JavaDoc)model.getSelectedItem();
836         if (option != null) {
837         appendBuffer(buffer, name, option.getValue());
838         }
839     }
840     }
841
842     /**
843      * Appends name / value pairs into the
844      * buffer. Both names and values are encoded using the
845      * URLEncoder.encode() method before being added to the
846      * buffer.
847      */

848     private void appendBuffer(StringBuffer JavaDoc buffer, String JavaDoc name, String JavaDoc value) {
849     if (buffer.length() > 0) {
850         buffer.append('&');
851     }
852     String JavaDoc encodedName = URLEncoder.encode(name);
853     buffer.append(encodedName);
854     buffer.append('=');
855     String JavaDoc encodedValue = URLEncoder.encode(value);
856     buffer.append(encodedValue);
857     }
858
859     /**
860      * Returns true if the Element <code>elem</code> represents a control.
861      */

862     private boolean isControl(Element elem) {
863         return elem.isLeaf();
864     }
865
866     /**
867      * Iterates over the element hierarchy to determine if
868      * the element parameter, which is assumed to be an
869      * &lt;INPUT&gt; element of type password or text, is the last
870      * one of either kind, in the form to which it belongs.
871      */

872     boolean isLastTextOrPasswordField() {
873         Element parent = getFormElement();
874         Element elem = getElement();
875
876         if (parent != null) {
877             ElementIterator it = new ElementIterator(parent);
878             Element next;
879             boolean found = false;
880
881             while ((next = it.next()) != null) {
882                 if (next == elem) {
883                     found = true;
884                 }
885                 else if (found && isControl(next)) {
886                     AttributeSet elemAttr = next.getAttributes();
887
888                     if (HTMLDocument.matchNameAttribute
889                                      (elemAttr, HTML.Tag.INPUT)) {
890                         String JavaDoc type = (String JavaDoc)elemAttr.getAttribute
891                                                   (HTML.Attribute.TYPE);
892
893                         if ("text".equals(type) || "password".equals(type)) {
894                             return false;
895                         }
896                     }
897                 }
898             }
899         }
900         return true;
901     }
902
903     /**
904      * Resets the form
905      * to its initial state by reinitializing the models
906      * associated with each form element to their initial
907      * values.
908      *
909      * param elem the element that triggered the reset
910      */

911     void resetForm() {
912         Element parent = getFormElement();
913
914         if (parent != null) {
915             ElementIterator it = new ElementIterator(parent);
916             Element next;
917
918             while((next = it.next()) != null) {
919                 if (isControl(next)) {
920                     AttributeSet elemAttr = next.getAttributes();
921                     Object JavaDoc m = elemAttr.getAttribute(StyleConstants.
922                                                      ModelAttribute);
923                     if (m instanceof TextAreaDocument JavaDoc) {
924                         TextAreaDocument JavaDoc doc = (TextAreaDocument JavaDoc)m;
925                         doc.reset();
926                     } else if (m instanceof PlainDocument) {
927                         try {
928                             PlainDocument doc = (PlainDocument)m;
929                             doc.remove(0, doc.getLength());
930                             if (HTMLDocument.matchNameAttribute
931                                              (elemAttr, HTML.Tag.INPUT)) {
932                                 String JavaDoc value = (String JavaDoc)elemAttr.
933                                            getAttribute(HTML.Attribute.VALUE);
934                                 if (value != null) {
935                                     doc.insertString(0, value, null);
936                                 }
937                             }
938                         } catch (BadLocationException e) {
939                         }
940                     } else if (m instanceof OptionListModel JavaDoc) {
941                         OptionListModel JavaDoc model = (OptionListModel JavaDoc) m;
942                         int size = model.getSize();
943                         for (int i = 0; i < size; i++) {
944                             model.removeIndexInterval(i, i);
945                         }
946                         BitSet selectionRange = model.getInitialSelection();
947                         for (int i = 0; i < selectionRange.size(); i++) {
948                             if (selectionRange.get(i)) {
949                                 model.addSelectionInterval(i, i);
950                             }
951                         }
952                     } else if (m instanceof OptionComboBoxModel JavaDoc) {
953                         OptionComboBoxModel JavaDoc model = (OptionComboBoxModel JavaDoc) m;
954                         Option JavaDoc option = model.getInitialSelection();
955                         if (option != null) {
956                             model.setSelectedItem(option);
957                         }
958                     } else if (m instanceof JToggleButton.ToggleButtonModel) {
959                         boolean checked = ((String JavaDoc)elemAttr.getAttribute
960                                            (HTML.Attribute.CHECKED) != null);
961                         JToggleButton.ToggleButtonModel model =
962                                         (JToggleButton.ToggleButtonModel)m;
963                         model.setSelected(checked);
964                     }
965                 }
966             }
967         }
968     }
969
970
971     /**
972      * BrowseFileAction is used for input type == file. When the user
973      * clicks the button a JFileChooser is brought up allowing the user
974      * to select a file in the file system. The resulting path to the selected
975      * file is set in the text field (actually an instance of Document).
976      */

977     private class BrowseFileAction implements ActionListener {
978         private AttributeSet attrs;
979         private Document model;
980
981         BrowseFileAction(AttributeSet attrs, Document model) {
982             this.attrs = attrs;
983             this.model = model;
984         }
985
986         public void actionPerformed(ActionEvent ae) {
987             // PENDING: When mime support is added to JFileChooser use the
988
// accept value of attrs.
989
JFileChooser fc = new JFileChooser();
990             fc.setMultiSelectionEnabled(false);
991             if (fc.showOpenDialog(getContainer()) ==
992                   JFileChooser.APPROVE_OPTION) {
993                 File selected = fc.getSelectedFile();
994
995                 if (selected != null) {
996                     try {
997                         if (model.getLength() > 0) {
998                             model.remove(0, model.getLength());
999                         }
1000                        model.insertString(0, selected.getPath(), null);
1001                    } catch (BadLocationException ble) {}
1002                }
1003            }
1004        }
1005    }
1006}
1007
Popular Tags