KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > awt > HtmlBrowser


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide.awt;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.Component JavaDoc;
24 import java.awt.GridBagConstraints JavaDoc;
25 import java.awt.GridBagLayout JavaDoc;
26 import java.awt.Insets JavaDoc;
27 import java.awt.event.ActionEvent JavaDoc;
28 import java.awt.event.ActionListener JavaDoc;
29 import java.beans.PropertyChangeEvent JavaDoc;
30 import java.beans.PropertyChangeListener JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.URL JavaDoc;
34 import java.util.logging.Logger JavaDoc;
35 import javax.accessibility.Accessible JavaDoc;
36 import javax.accessibility.AccessibleContext JavaDoc;
37 import javax.imageio.ImageIO JavaDoc;
38 import javax.swing.Icon JavaDoc;
39 import javax.swing.JButton JavaDoc;
40 import javax.swing.JComboBox JavaDoc;
41 import javax.swing.JComponent JavaDoc;
42 import javax.swing.JFrame JavaDoc;
43 import javax.swing.JLabel JavaDoc;
44 import javax.swing.JPanel JavaDoc;
45 import javax.swing.JScrollPane JavaDoc;
46 import javax.swing.JToolBar JavaDoc;
47 import javax.swing.ListModel JavaDoc;
48 import javax.swing.SwingUtilities JavaDoc;
49 import javax.swing.WindowConstants JavaDoc;
50 import org.openide.util.Exceptions;
51 import org.openide.util.Lookup;
52 import org.openide.util.NbBundle;
53 import org.openide.util.RequestProcessor;
54
55 /**
56 * Object that provides viewer for HTML pages.
57 * <p>If all you want to do is to show some URL, this
58 * is overkill. Just use {@link HtmlBrowser.URLDisplayer#showURL} instead. Using <code>HtmlBrowser</code>
59 * is appropriate mainly if you want to embed a web browser in some other GUI component
60 * (if the user has selected an external browser, this will fall back to a simple Swing
61 * renderer). Similarly <code>Impl</code> (coming from a <code>Factory</code>) is the lower-level
62 * renderer itself (sans toolbar).
63 * <p>Summary: for client use, try <code>URLDisplayer.showURL</code>, or for more control
64 * or where embedding is needed, create an <code>HtmlBrowser</code>. For provider use,
65 * create a <code>Factory</code> and register an instance of it to lookup.
66 */

67 public class HtmlBrowser extends JPanel JavaDoc {
68     // static ....................................................................
69

70     /** generated Serialized Version UID */
71     private static final long serialVersionUID = 2912844785502987960L;
72
73     /** Preferred width of the browser */
74     public static final int DEFAULT_WIDTH = 400;
75
76     /** Preferred height of the browser */
77     public static final int DEFAULT_HEIGHT = 600;
78
79     /** current implementation of html browser */
80     private static Factory browserFactory;
81
82     /** home page URL */
83     private static String JavaDoc homePage = null;
84
85     /** Icons for buttons. */
86     private Icon JavaDoc iBack;
87     private Icon JavaDoc iForward;
88     private Icon JavaDoc iHome;
89     private Icon JavaDoc iReload;
90     private Icon JavaDoc iStop;
91     private Icon JavaDoc iHistory;
92
93     // variables .................................................................
94

95     /** currently used implementation of browser */
96     final Impl browserImpl;
97
98     /** true = do not listen on changes of URL on cbLocation */
99     private boolean everythinkIListenInCheckBoxIsUnimportant = false;
100
101     /** toolbar visible property */
102     private boolean toolbarVisible = false;
103
104     /** status line visible property */
105     private boolean statusLineVisible = false;
106
107     /** Listens on changes in HtmlBrowser.Impl and HtmlBrowser visual components.
108     */

109     private BrowserListener browserListener;
110
111     // visual components .........................................................
112
private JButton JavaDoc bBack;
113
114     // visual components .........................................................
115
private JButton JavaDoc bForward;
116
117     // visual components .........................................................
118
private JButton JavaDoc bHome;
119
120     // visual components .........................................................
121
private JButton JavaDoc bReload;
122
123     // visual components .........................................................
124
private JButton JavaDoc bStop;
125
126     // visual components .........................................................
127
private JButton JavaDoc bHistory;
128
129     /** URL chooser */
130     private JComboBox JavaDoc cbLocation;
131     private JLabel JavaDoc cbLabel;
132     private JLabel JavaDoc lStatusLine;
133     final Component JavaDoc browserComponent;
134     private JPanel JavaDoc head;
135     private RequestProcessor rp = new RequestProcessor();
136
137     // init ......................................................................
138

139     /**
140     * Creates new html browser with toolbar and status line.
141     */

142     public HtmlBrowser() {
143         this(true, true);
144     }
145
146     /**
147     * Creates new html browser.
148      *
149      * @param toolbar visibility of toolbar
150      * @param statusLine visibility of statusLine
151     */

152     public HtmlBrowser(boolean toolbar, boolean statusLine) {
153         this(null, toolbar, statusLine);
154     }
155
156     /**
157     * Creates new html browser.
158      *
159      * @param fact Factory that is used for creation. If null is passed it searches for
160      * a factory providing displayable component.
161      * @param toolbar visibility of toolbar
162      * @param statusLine visibility of statusLine
163     */

164     public HtmlBrowser(Factory fact, boolean toolbar, boolean statusLine) {
165         init();
166
167         Impl impl = null;
168         Component JavaDoc comp = null;
169
170         try {
171             if (fact == null) {
172                 Impl[] arr = new Impl[1];
173                 comp = findComponent(arr);
174                 impl = arr[0];
175             } else {
176                 try {
177                     impl = fact.createHtmlBrowserImpl();
178                     comp = impl.getComponent();
179                 } catch (UnsupportedOperationException JavaDoc ex) {
180                     Exceptions.printStackTrace(ex);
181                     impl = new SwingBrowserImpl();
182                     comp = impl.getComponent();
183                 }
184             }
185         } catch (RuntimeException JavaDoc e) {
186             // browser was uninstlled ?
187
Exceptions.attachLocalizedMessage(e,
188                                               NbBundle.getMessage(HtmlBrowser.class,
189                                                                   "EXC_Module"));
190             Exceptions.printStackTrace(e);
191         }
192
193         browserImpl = impl;
194         browserComponent = comp;
195
196         setLayout(new BorderLayout JavaDoc(0, 2));
197
198         add((browserComponent != null) ? new JScrollPane JavaDoc(browserComponent) : new JScrollPane JavaDoc(), "Center"); // NOI18N
199

200         browserListener = new BrowserListener();
201
202         if (toolbar) {
203             initToolbar();
204         }
205
206         if (statusLine) {
207             initStatusLine();
208         }
209
210         browserImpl.addPropertyChangeListener(browserListener);
211
212         getAccessibleContext().setAccessibleName(NbBundle.getMessage(HtmlBrowser.class, "ACS_HtmlBrowser"));
213         getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(HtmlBrowser.class, "ACSD_HtmlBrowser"));
214     }
215
216     /** Sets the home page.
217     * @param u the home page
218     */

219     public static void setHomePage(String JavaDoc u) {
220         homePage = u;
221     }
222
223     /** Getter for the home page
224     * @return the home page
225     */

226     public static String JavaDoc getHomePage() {
227         if (homePage == null) {
228             return NbBundle.getMessage(HtmlBrowser.class, "PROP_HomePage");
229         }
230
231         return homePage;
232     }
233
234     /**
235     * Sets a new implementation of browser visual component
236     * for all HtmlBrowers.
237     * @deprecated Use Lookup instead to register factories
238     */

239     public static void setFactory(Factory brFactory) {
240         browserFactory = brFactory;
241     }
242
243     /** Find Impl of HtmlBrowser. Searches for registered factories in lookup folder.
244      * Tries to create Impl and check if it provides displayable component.
245      * Both Component and used Impl are returned to avoid resource consuming of new
246      * Component/Impl.
247      * </P>
248      * <P>
249      * If no browser is found then it tries to use registered factory (now deprecated method
250      * of setting browser) or it uses browser based on swing editor in the worst case.
251      *
252      * @param handle used browser implementation is in first element when method
253      * is finished
254      * @return Component for content displaying
255      */

256     private static Component JavaDoc findComponent(Impl[] handle) {
257         Lookup.Result<Factory> r = Lookup.getDefault().lookup(new Lookup.Template<Factory>(Factory.class));
258         for (Factory f: r.allInstances()) {
259
260             try {
261                 Impl impl = f.createHtmlBrowserImpl();
262                 Component JavaDoc c = (impl != null) ? impl.getComponent() : null;
263
264                 if (c != null) {
265                     handle[0] = impl;
266
267                     return c;
268                 }
269             } catch (UnsupportedOperationException JavaDoc ex) {
270                 // do nothing: thrown if browser doesn't work on given platform
271
}
272         }
273
274         // 1st fallback to our deprecated method
275
Factory f = browserFactory;
276
277         if (f != null) {
278             try {
279                 handle[0] = f.createHtmlBrowserImpl();
280
281                 return handle[0].getComponent();
282             } catch (UnsupportedOperationException JavaDoc ex) {
283                 // do nothing: thrown if browser doesn't work on given platform
284
}
285         }
286
287         // last fallback is to swing
288
handle[0] = new SwingBrowserImpl();
289
290         return handle[0].getComponent();
291     }
292
293     /**
294     * Default initializations.
295     */

296     private void init() {
297         try {
298             if (iBack != null) {
299                 return;
300             }
301             iBack = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/back.gif"))); // NOI18N
302
iForward = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/forward.gif"))); // NOI18N
303
iHome = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/home.gif"))); // NOI18N
304
iReload = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/refresh.gif"))); // NOI18N
305
iStop = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/stop.gif"))); // NOI18N
306
iHistory = new javax.swing.ImageIcon JavaDoc(ImageIO.read(org.openide.awt.HtmlBrowser.class.getResource("/org/openide/resources/html/history.gif"))); // NOI18N
307
}
308         catch (IOException JavaDoc ex) {
309             Logger.getLogger(HtmlBrowser.class.getName()).log(java.util.logging.Level.SEVERE,
310                                                              ex.getMessage(), ex);
311         }
312 }
313
314     /**
315     * Default initialization of toolbar.
316     */

317     private void initToolbar() {
318         toolbarVisible = true;
319
320         // create visual compoments .............................
321
head = new JPanel JavaDoc();
322         head.setLayout(new BorderLayout JavaDoc(11, 0));
323
324         JPanel JavaDoc p = new JPanel JavaDoc(new GridBagLayout JavaDoc());
325         p.add(bBack = new JButton JavaDoc(iBack));
326         bBack.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_Back"));
327
328         GridBagConstraints JavaDoc gbc = new GridBagConstraints JavaDoc();
329         gbc.insets = new Insets JavaDoc(0, 0, 0, 5);
330         p.add(bForward = new JButton JavaDoc(iForward), gbc);
331         bForward.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_Forward"));
332         p.add(bStop = new JButton JavaDoc(iStop));
333         bStop.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_Stop"));
334         gbc = new GridBagConstraints JavaDoc();
335         gbc.insets = new Insets JavaDoc(0, 0, 0, 5);
336         p.add(bReload = new JButton JavaDoc(iReload), gbc);
337         bReload.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_Reload"));
338         p.add(bHome = new JButton JavaDoc(iHome));
339         bHome.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_Home"));
340         gbc = new GridBagConstraints JavaDoc();
341         gbc.insets = new Insets JavaDoc(0, 0, 0, 5);
342         p.add(bHistory = new JButton JavaDoc(iHistory), gbc);
343         bHistory.setToolTipText(NbBundle.getMessage(HtmlBrowser.class, "CTL_History"));
344
345         if (browserImpl != null) {
346             bBack.setEnabled(browserImpl.isBackward());
347             bForward.setEnabled(browserImpl.isForward());
348             bHistory.setEnabled(browserImpl.isHistory());
349         }
350
351         JToolBar.Separator JavaDoc ts = new JToolBar.Separator JavaDoc();
352         gbc = new GridBagConstraints JavaDoc();
353         gbc.insets = new Insets JavaDoc(0, 0, 0, 5);
354         p.add(ts, gbc);
355         ts.updateUI();
356         p.add(cbLabel = new JLabel JavaDoc());
357         Mnemonics.setLocalizedText(cbLabel, NbBundle.getMessage(HtmlBrowser.class, "CTL_Location")); // NOI18N
358
head.add("West", p); // NOI18N
359

360         head.add("Center", cbLocation = new JComboBox JavaDoc()); // NOI18N
361
cbLocation.setEditable(true);
362         cbLabel.setLabelFor(cbLocation);
363         add(head, "North"); // NOI18N
364

365         // add listeners ..................... .............................
366
cbLocation.addActionListener(browserListener);
367         bHistory.addActionListener(browserListener);
368         bBack.addActionListener(browserListener);
369         bForward.addActionListener(browserListener);
370         bReload.addActionListener(browserListener);
371         bHome.addActionListener(browserListener);
372         bStop.addActionListener(browserListener);
373
374         bHistory.getAccessibleContext().setAccessibleName(bHistory.getToolTipText());
375         bBack.getAccessibleContext().setAccessibleName(bBack.getToolTipText());
376         bForward.getAccessibleContext().setAccessibleName(bForward.getToolTipText());
377         bReload.getAccessibleContext().setAccessibleName(bReload.getToolTipText());
378         bHome.getAccessibleContext().setAccessibleName(bHome.getToolTipText());
379         bStop.getAccessibleContext().setAccessibleName(bStop.getToolTipText());
380         cbLocation.getAccessibleContext().setAccessibleDescription(
381             NbBundle.getMessage(HtmlBrowser.class, "ACSD_HtmlBrowser_Location")
382         );
383     }
384
385     /**
386     * Default initialization of toolbar.
387     */

388     private void destroyToolbar() {
389         remove(head);
390         head = null;
391         toolbarVisible = false;
392     }
393
394     /**
395     * Default initialization of status line.
396     */

397     private void initStatusLine() {
398         statusLineVisible = true;
399         add(lStatusLine = new JLabel JavaDoc(NbBundle.getMessage(HtmlBrowser.class, "CTL_Loading")), "South" // NOI18N
400
);
401         lStatusLine.setLabelFor(this);
402     }
403
404     /**
405     * Destroyes status line.
406     */

407     private void destroyStatusLine() {
408         remove(lStatusLine);
409         lStatusLine = null;
410         statusLineVisible = false;
411     }
412
413     // public methods ............................................................
414

415     /**
416     * Sets new URL.
417     *
418     * @param str URL to show in this browser.
419     */

420     public void setURL(String JavaDoc str) {
421         URL JavaDoc URL;
422
423         try {
424             URL = new URL JavaDoc(str);
425         } catch (MalformedURLException JavaDoc ee) {
426             try {
427                 URL = new URL JavaDoc("http://" + str); // NOI18N
428
} catch (MalformedURLException JavaDoc e) {
429                 if (browserImpl instanceof SwingBrowserImpl) {
430                     ((SwingBrowserImpl) browserImpl).setStatusText(
431                         NbBundle.getMessage(SwingBrowserImpl.class, "FMT_InvalidURL", new Object JavaDoc[] { str })
432                     );
433                 } else {
434                     Exceptions.printStackTrace(ee);
435                 }
436
437                 return;
438             }
439         }
440
441         setURL(URL);
442     }
443
444     /**
445     * Sets new URL.
446     *
447     * @param url URL to show in this browser.
448     */

449     public void setURL(final URL JavaDoc url) {
450         if (url == null) {
451             return;
452         }
453
454         class URLSetter implements Runnable JavaDoc {
455             private boolean sameHosts = false;
456
457             public void run() {
458                 if (!SwingUtilities.isEventDispatchThread()) {
459                     if ("nbfs".equals(url.getProtocol())) { // NOI18N
460
sameHosts = true;
461                     } else {
462                         sameHosts = (url.getHost() != null) && (browserImpl.getURL() != null) &&
463                             (url.getHost().equals(browserImpl.getURL().getHost()));
464                     }
465
466                     SwingUtilities.invokeLater(this);
467                 } else {
468                     if (url.equals(browserImpl.getURL()) && sameHosts) { // see bug 9470
469
browserImpl.reloadDocument();
470                     } else {
471                         browserImpl.setURL(url);
472                     }
473                 }
474             }
475         }
476         rp.getDefault().post(new URLSetter());
477     }
478
479     /**
480     * Gets current document url.
481     */

482     public final URL JavaDoc getDocumentURL() {
483         return browserImpl.getURL();
484     }
485
486     /**
487     * Enables/disables Home button.
488     */

489     public final void setEnableHome(boolean b) {
490         bHome.setEnabled(b);
491         bHome.setVisible(b);
492     }
493
494     /**
495     * Enables/disables location.
496     */

497     public final void setEnableLocation(boolean b) {
498         cbLocation.setEditable(b);
499         cbLocation.setVisible(b);
500         cbLabel.setVisible(b);
501     }
502
503     /**
504     * Gets status line state.
505     */

506     public boolean isStatusLineVisible() {
507         return statusLineVisible;
508     }
509
510     /**
511     * Shows/hides status line.
512     */

513     public void setStatusLineVisible(boolean v) {
514         if (v == statusLineVisible) {
515             return;
516         }
517
518         if (v) {
519             initStatusLine();
520         } else {
521             destroyStatusLine();
522         }
523     }
524
525     /**
526     * Gets status toolbar.
527     */

528     public boolean isToolbarVisible() {
529         return toolbarVisible;
530     }
531
532     /**
533     * Shows/hides toolbar.
534     */

535     public void setToolbarVisible(boolean v) {
536         if (v == toolbarVisible) {
537             return;
538         }
539
540         if (v) {
541             initToolbar();
542         } else {
543             destroyToolbar();
544         }
545     }
546
547     /**
548      * Get the browser implementation.
549      * @return the implementation
550      * @since org.openide/1 4.27
551      */

552     public final Impl getBrowserImpl() {
553         return browserImpl;
554     }
555
556     /**
557      * Get the browser component.
558      * @return a component or null
559      * @since org.openide/1 4.27
560      */

561     public final Component JavaDoc getBrowserComponent() {
562         return browserComponent;
563     }
564
565     // helper methods .......................................................................
566

567     /**
568     * Returns preferred size.
569     */

570     public java.awt.Dimension JavaDoc getPreferredSize() {
571         java.awt.Dimension JavaDoc superPref = super.getPreferredSize();
572
573         return new java.awt.Dimension JavaDoc(
574             Math.max(DEFAULT_WIDTH, superPref.width), Math.max(DEFAULT_HEIGHT, superPref.height)
575         );
576     }
577
578     /**
579      * Show current brower's URL in the location bar combo box.
580      */

581     private void updateLocationBar() {
582         if (toolbarVisible) {
583             everythinkIListenInCheckBoxIsUnimportant = true;
584
585             URL JavaDoc url = browserImpl.getURL();
586
587             if (url != null) {
588                 cbLocation.setSelectedItem(url.toString());
589             }
590
591             everythinkIListenInCheckBoxIsUnimportant = false;
592         }
593     }
594
595     ////// Accessibility //////
596
public void requestFocus() {
597         if (browserComponent != null) {
598             boolean ownerFound = false;
599
600             if (browserComponent instanceof JComponent JavaDoc) {
601                 ownerFound = ((JComponent JavaDoc) browserComponent).requestDefaultFocus();
602             }
603
604             if (!ownerFound) {
605                 browserComponent.requestFocus();
606             }
607         } else {
608             super.requestFocus();
609         }
610     }
611
612     public boolean requestFocusInWindow() {
613         if (browserComponent != null) {
614             boolean ownerFound = false;
615
616             if (browserComponent instanceof JComponent JavaDoc) {
617                 ownerFound = ((JComponent JavaDoc) browserComponent).requestDefaultFocus();
618             }
619
620             if (!ownerFound) {
621                 return browserComponent.requestFocusInWindow();
622             } else {
623                 return true;
624             }
625         } else {
626             return super.requestFocusInWindow();
627         }
628     }
629
630     public AccessibleContext JavaDoc getAccessibleContext() {
631         if (accessibleContext == null) {
632             accessibleContext = new AccessibleHtmlBrowser();
633         }
634
635         return accessibleContext;
636     }
637
638     /**
639     * Implementation of BrowerFactory creates new instances of some Browser implementation.
640     *
641     * @see HtmlBrowser.Impl
642     */

643     public interface Factory {
644         /**
645         * Returns a new instance of BrowserImpl implementation.
646         */

647         public Impl createHtmlBrowserImpl();
648     }
649
650     // innerclasses ..............................................................
651

652     /**
653     * Listens on changes in HtmlBrowser.Impl and HtmlBrowser visual components.
654     */

655     private class BrowserListener implements ActionListener JavaDoc, PropertyChangeListener JavaDoc {
656         BrowserListener() {
657         }
658
659         /**
660         * Listens on changes in HtmlBrowser.Impl.
661         */

662         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
663             String JavaDoc property = evt.getPropertyName();
664
665             if (property == null) {
666                 return;
667             }
668
669             if (property.equals(Impl.PROP_URL) || property.equals(Impl.PROP_TITLE)) {
670                 HtmlBrowser.this.firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
671             }
672
673             if (property.equals(Impl.PROP_URL)) {
674                 updateLocationBar();
675             } else if (property.equals(Impl.PROP_STATUS_MESSAGE)) {
676                 String JavaDoc s = browserImpl.getStatusMessage();
677
678                 if ((s == null) || (s.length() < 1)) {
679                     s = NbBundle.getMessage(HtmlBrowser.class, "CTL_Document_done");
680                 }
681
682                 if (lStatusLine != null) {
683                     lStatusLine.setText(s);
684                 }
685             } else if (property.equals(Impl.PROP_FORWARD) && (bForward != null)) {
686                 bForward.setEnabled(browserImpl.isForward());
687             } else if (property.equals(Impl.PROP_BACKWARD) && (bBack != null)) {
688                 bBack.setEnabled(browserImpl.isBackward());
689             } else if (property.equals(Impl.PROP_HISTORY) && (bHistory != null)) {
690                 bHistory.setEnabled(browserImpl.isHistory());
691             }
692         }
693
694         /**
695         * Listens on changes in HtmlBrowser visual components.
696         */

697         public void actionPerformed(ActionEvent JavaDoc e) {
698             if (e.getSource() == cbLocation) {
699                 // URL manually changed
700
if (everythinkIListenInCheckBoxIsUnimportant) {
701                     return;
702                 }
703
704                 JComboBox JavaDoc cb = (JComboBox JavaDoc) e.getSource();
705                 Object JavaDoc o = cb.getSelectedItem();
706
707                 if (o == null) { // empty combo box
708

709                     return;
710                 }
711
712                 setURL((String JavaDoc) o);
713
714                 ListModel JavaDoc lm = cb.getModel();
715                 int i;
716                 int k = lm.getSize();
717
718                 for (i = 0; i < k; i++)
719                     if (o.equals(lm.getElementAt(i))) {
720                         break;
721                     }
722
723                 if (i != k) {
724                     return;
725                 }
726
727                 if (k == 20) {
728                     cb.removeItem(lm.getElementAt(k - 1));
729                 }
730
731                 cb.insertItemAt(o, 0);
732             } else
733              if (e.getSource() == bHistory) {
734                 browserImpl.showHistory();
735             } else
736              if (e.getSource() == bBack) {
737                 browserImpl.backward();
738             } else
739              if (e.getSource() == bForward) {
740                 browserImpl.forward();
741             } else
742              if (e.getSource() == bReload) {
743                 updateLocationBar();
744                 browserImpl.reloadDocument();
745             } else
746              if (e.getSource() == bHome) {
747                 setURL(getHomePage());
748             } else
749              if (e.getSource() == bStop) {
750                 browserImpl.stopLoading();
751             }
752         }
753     }
754
755     /**
756     * This interface represents an implementation of html browser used in HtmlBrowser. Each BrowserImpl
757     * implementation corresponds with some BrowserFactory implementation.
758     */

759     public static abstract class Impl {
760         /** generated Serialized Version UID */
761         static final long serialVersionUID = 2912844785502962114L;
762
763         /** The name of property representing status of html browser. */
764         public static final String JavaDoc PROP_STATUS_MESSAGE = "statusMessage"; // NOI18N
765

766         /** The name of property representing current URL. */
767         public static final String JavaDoc PROP_URL = "url"; // NOI18N
768

769         /** Title property */
770         public static final String JavaDoc PROP_TITLE = "title"; // NOI18N
771

772         /** forward property */
773         public static final String JavaDoc PROP_FORWARD = "forward"; // NOI18N
774

775         /** backward property name */
776         public static final String JavaDoc PROP_BACKWARD = "backward"; // NOI18N
777

778         /** history property name */
779         public static final String JavaDoc PROP_HISTORY = "history"; // NOI18N
780

781         /**
782         * Returns visual component of html browser.
783         *
784         * @return visual component of html browser.
785         */

786         public abstract java.awt.Component JavaDoc getComponent();
787
788         /**
789         * Reloads current html page.
790         */

791         public abstract void reloadDocument();
792
793         /**
794         * Stops loading of current html page.
795         */

796         public abstract void stopLoading();
797
798         /**
799         * Sets current URL.
800         *
801         * @param url URL to show in the browser.
802         */

803         public abstract void setURL(URL JavaDoc url);
804
805         /**
806         * Returns current URL.
807         *
808         * @return current URL.
809         */

810         public abstract URL JavaDoc getURL();
811
812         /**
813         * Returns status message representing status of html browser.
814         *
815         * @return status message.
816         */

817         public abstract String JavaDoc getStatusMessage();
818
819         /** Returns title of the displayed page.
820         * @return title
821         */

822         public abstract String JavaDoc getTitle();
823
824         /** Is forward button enabled?
825         * @return true if it is
826         */

827         public abstract boolean isForward();
828
829         /** Moves the browser forward. Failure is ignored.
830         */

831         public abstract void forward();
832
833         /** Is backward button enabled?
834         * @return true if it is
835         */

836         public abstract boolean isBackward();
837
838         /** Moves the browser forward. Failure is ignored.
839         */

840         public abstract void backward();
841
842         /** Is history button enabled?
843         * @return true if it is
844         */

845         public abstract boolean isHistory();
846
847         /** Invoked when the history button is pressed.
848         */

849         public abstract void showHistory();
850
851         /**
852         * Adds PropertyChangeListener to this browser.
853         *
854         * @param l Listener to add.
855         */

856         public abstract void addPropertyChangeListener(PropertyChangeListener JavaDoc l);
857
858         /**
859         * Removes PropertyChangeListener from this browser.
860         *
861         * @param l Listener to remove.
862         */

863         public abstract void removePropertyChangeListener(PropertyChangeListener JavaDoc l);
864     }
865
866     /** A manager class which can display URLs in the proper way.
867      * Might open a selected HTML browser, knows about embedded vs. external
868      * browsers, etc.
869      * @since 3.14
870      */

871     public static abstract class URLDisplayer {
872         /** Subclass constructor. */
873         protected URLDisplayer() {
874         }
875
876         /** Get the default URL displayer.
877          * @return the default instance from lookup
878          */

879         public static URLDisplayer getDefault() {
880             URLDisplayer dflt = (URLDisplayer) Lookup.getDefault().lookup(URLDisplayer.class);
881
882             if (dflt == null) {
883                 // Fallback.
884
dflt = new TrivialURLDisplayer();
885             }
886
887             return dflt;
888         }
889
890         /**
891          * API clients usage: Call this method to display your URL in some browser.
892          * Typically for external browsers this method is
893          * non-blocking, doesn't wait until page gets displayed. Also, failures
894          * are reported using dialog. However note that as there are other
895          * implementations of this method, actual behaviour may be different.
896          *
897          * <p>
898          * SPI clients usage: Implement this method to display given URL to the user.
899          * </p>
900          *
901          * @param u the URL to show
902          */

903         public abstract void showURL(URL JavaDoc u);
904     }
905
906     private static final class TrivialURLDisplayer extends URLDisplayer {
907         public TrivialURLDisplayer() {
908         }
909
910         public void showURL(URL JavaDoc u) {
911             HtmlBrowser browser = new HtmlBrowser();
912             browser.setURL(u);
913
914             JFrame JavaDoc frame = new JFrame JavaDoc();
915             frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
916             frame.getContentPane().add(browser);
917             frame.pack();
918             frame.setVisible(true);
919         }
920     }
921
922     private class AccessibleHtmlBrowser extends JPanel.AccessibleJPanel JavaDoc {
923         AccessibleHtmlBrowser() {
924         }
925
926         public void setAccessibleName(String JavaDoc name) {
927             super.setAccessibleName(name);
928
929             if (browserComponent instanceof Accessible JavaDoc) {
930                 browserComponent.getAccessibleContext().setAccessibleName(name);
931             }
932         }
933
934         public void setAccessibleDescription(String JavaDoc desc) {
935             super.setAccessibleDescription(desc);
936
937             if (browserComponent instanceof Accessible JavaDoc) {
938                 browserComponent.getAccessibleContext().setAccessibleDescription(desc);
939             }
940         }
941     }
942 }
943
Popular Tags