KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > plaf > basic > BasicToolBarUI


1 /*
2  * @(#)BasicToolBarUI.java 1.97 06/08/25
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package javax.swing.plaf.basic;
9
10 import javax.swing.*;
11 import javax.swing.event.*;
12 import java.awt.*;
13 import java.awt.event.*;
14
15 import java.beans.*;
16
17 import java.util.Hashtable JavaDoc;
18 import java.util.HashMap JavaDoc;
19
20 import javax.swing.border.*;
21 import javax.swing.plaf.*;
22 import sun.swing.DefaultLookup;
23 import sun.swing.UIAction;
24 import sun.swing.BorderProvider;
25
26
27 /**
28  * A Basic L&F implementation of ToolBarUI. This implementation
29  * is a "combined" view/controller.
30  * <p>
31  *
32  * @version 1.97 08/25/06
33  * @author Georges Saab
34  * @author Jeff Shapiro
35  */

36 public class BasicToolBarUI extends ToolBarUI implements SwingConstants
37 {
38     protected JToolBar toolBar;
39     private boolean floating;
40     private int floatingX;
41     private int floatingY;
42     private JFrame floatingFrame;
43     private RootPaneContainer floatingToolBar;
44     protected DragWindow dragWindow;
45     private Container dockingSource;
46     private int dockingSensitivity = 0;
47     protected int focusedCompIndex = -1;
48
49     protected Color dockingColor = null;
50     protected Color floatingColor = null;
51     protected Color dockingBorderColor = null;
52     protected Color floatingBorderColor = null;
53
54     protected MouseInputListener dockingListener;
55     protected PropertyChangeListener propertyListener;
56
57     protected ContainerListener toolBarContListener;
58     protected FocusListener toolBarFocusListener;
59     private Handler handler;
60
61     protected String JavaDoc constraintBeforeFloating = BorderLayout.NORTH;
62
63     // Rollover button implementation.
64
private static String JavaDoc IS_ROLLOVER = "JToolBar.isRollover";
65     private static Border rolloverBorder;
66     private static Border nonRolloverBorder;
67     private static Border nonRolloverToggleBorder;
68     private boolean rolloverBorders = false;
69
70     private HashMap JavaDoc borderTable = new HashMap JavaDoc();
71     private Hashtable JavaDoc rolloverTable = new Hashtable JavaDoc();
72
73
74     /**
75      * As of Java 2 platform v1.3 this previously undocumented field is no
76      * longer used.
77      * Key bindings are now defined by the LookAndFeel, please refer to
78      * the key bindings specification for further details.
79      *
80      * @deprecated As of Java 2 platform v1.3.
81      */

82     @Deprecated JavaDoc
83     protected KeyStroke upKey;
84     /**
85      * As of Java 2 platform v1.3 this previously undocumented field is no
86      * longer used.
87      * Key bindings are now defined by the LookAndFeel, please refer to
88      * the key bindings specification for further details.
89      *
90      * @deprecated As of Java 2 platform v1.3.
91      */

92     @Deprecated JavaDoc
93     protected KeyStroke downKey;
94     /**
95      * As of Java 2 platform v1.3 this previously undocumented field is no
96      * longer used.
97      * Key bindings are now defined by the LookAndFeel, please refer to
98      * the key bindings specification for further details.
99      *
100      * @deprecated As of Java 2 platform v1.3.
101      */

102     @Deprecated JavaDoc
103     protected KeyStroke leftKey;
104     /**
105      * As of Java 2 platform v1.3 this previously undocumented field is no
106      * longer used.
107      * Key bindings are now defined by the LookAndFeel, please refer to
108      * the key bindings specification for further details.
109      *
110      * @deprecated As of Java 2 platform v1.3.
111      */

112     @Deprecated JavaDoc
113     protected KeyStroke rightKey;
114
115
116     private static String JavaDoc FOCUSED_COMP_INDEX = "JToolBar.focusedCompIndex";
117
118     public static ComponentUI createUI( JComponent c )
119     {
120     return new BasicToolBarUI JavaDoc();
121     }
122
123     public void installUI( JComponent c )
124     {
125     toolBar = (JToolBar) c;
126
127     // Set defaults
128
installDefaults();
129     installComponents();
130         installListeners();
131     installKeyboardActions();
132
133         // Initialize instance vars
134
dockingSensitivity = 0;
135         floating = false;
136         floatingX = floatingY = 0;
137         floatingToolBar = null;
138
139     setOrientation( toolBar.getOrientation() );
140         LookAndFeel.installProperty(c, "opaque", Boolean.TRUE);
141
142     if ( c.getClientProperty( FOCUSED_COMP_INDEX ) != null )
143     {
144         focusedCompIndex = ( (Integer JavaDoc) ( c.getClientProperty( FOCUSED_COMP_INDEX ) ) ).intValue();
145     }
146     }
147     
148     public void uninstallUI( JComponent c )
149     {
150
151         // Clear defaults
152
uninstallDefaults();
153     uninstallComponents();
154         uninstallListeners();
155     uninstallKeyboardActions();
156
157         // Clear instance vars
158
if (isFloating() == true)
159         setFloating(false, null);
160
161         floatingToolBar = null;
162         dragWindow = null;
163         dockingSource = null;
164
165         c.putClientProperty( FOCUSED_COMP_INDEX, new Integer JavaDoc( focusedCompIndex ) );
166     }
167
168     protected void installDefaults( )
169     {
170     LookAndFeel.installBorder(toolBar,"ToolBar.border");
171     LookAndFeel.installColorsAndFont(toolBar,
172                           "ToolBar.background",
173                           "ToolBar.foreground",
174                           "ToolBar.font");
175     // Toolbar specific defaults
176
if ( dockingColor == null || dockingColor instanceof UIResource )
177         dockingColor = UIManager.getColor("ToolBar.dockingBackground");
178     if ( floatingColor == null || floatingColor instanceof UIResource )
179         floatingColor = UIManager.getColor("ToolBar.floatingBackground");
180     if ( dockingBorderColor == null ||
181          dockingBorderColor instanceof UIResource )
182         dockingBorderColor = UIManager.getColor("ToolBar.dockingForeground");
183     if ( floatingBorderColor == null ||
184          floatingBorderColor instanceof UIResource )
185         floatingBorderColor = UIManager.getColor("ToolBar.floatingForeground");
186
187     // ToolBar rollover button borders
188
Object JavaDoc rolloverProp = toolBar.getClientProperty( IS_ROLLOVER );
189         if (rolloverProp == null) {
190             rolloverProp = UIManager.get("ToolBar.isRollover");
191         }
192     if ( rolloverProp != null ) {
193         rolloverBorders = ((Boolean JavaDoc)rolloverProp).booleanValue();
194     }
195
196     if (rolloverBorder == null) {
197         rolloverBorder = createRolloverBorder();
198     }
199     if (nonRolloverBorder == null) {
200         nonRolloverBorder = createNonRolloverBorder();
201     }
202     if (nonRolloverToggleBorder == null) {
203         nonRolloverToggleBorder = createNonRolloverToggleBorder();
204     }
205
206
207     setRolloverBorders( isRolloverBorders() );
208     }
209
210     protected void uninstallDefaults( )
211     {
212     LookAndFeel.uninstallBorder(toolBar);
213         dockingColor = null;
214         floatingColor = null;
215         dockingBorderColor = null;
216         floatingBorderColor = null;
217
218     installNormalBorders(toolBar);
219
220     rolloverBorder = null;
221     nonRolloverBorder = null;
222     nonRolloverToggleBorder = null;
223     }
224
225     protected void installComponents( )
226     {
227     }
228
229     protected void uninstallComponents( )
230     {
231     }
232
233     protected void installListeners( )
234     {
235         dockingListener = createDockingListener( );
236
237         if ( dockingListener != null )
238         {
239         toolBar.addMouseMotionListener( dockingListener );
240         toolBar.addMouseListener( dockingListener );
241     }
242
243     propertyListener = createPropertyListener(); // added in setFloating
244
if (propertyListener != null) {
245         toolBar.addPropertyChangeListener(propertyListener);
246     }
247
248     toolBarContListener = createToolBarContListener();
249         if ( toolBarContListener != null ) {
250         toolBar.addContainerListener( toolBarContListener );
251     }
252
253     toolBarFocusListener = createToolBarFocusListener();
254
255         if ( toolBarFocusListener != null )
256         {
257         // Put focus listener on all components in toolbar
258
Component[] components = toolBar.getComponents();
259
260         for ( int i = 0; i < components.length; ++i )
261         {
262             components[ i ].addFocusListener( toolBarFocusListener );
263         }
264     }
265     }
266
267     protected void uninstallListeners( )
268     {
269         if ( dockingListener != null )
270         {
271         toolBar.removeMouseMotionListener(dockingListener);
272         toolBar.removeMouseListener(dockingListener);
273
274             dockingListener = null;
275     }
276
277     if ( propertyListener != null )
278     {
279         toolBar.removePropertyChangeListener(propertyListener);
280         propertyListener = null; // removed in setFloating
281
}
282
283     if ( toolBarContListener != null )
284     {
285         toolBar.removeContainerListener( toolBarContListener );
286         toolBarContListener = null;
287     }
288
289         if ( toolBarFocusListener != null )
290         {
291         // Remove focus listener from all components in toolbar
292
Component[] components = toolBar.getComponents();
293
294         for ( int i = 0; i < components.length; ++i )
295         {
296             components[ i ].removeFocusListener( toolBarFocusListener );
297         }
298
299         toolBarFocusListener = null;
300     }
301         handler = null;
302     }
303
304     protected void installKeyboardActions( )
305     {
306     InputMap km = getInputMap(JComponent.
307                   WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
308
309     SwingUtilities.replaceUIInputMap(toolBar, JComponent.
310                      WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
311                      km);
312
313     LazyActionMap.installLazyActionMap(toolBar, BasicToolBarUI JavaDoc.class,
314             "ToolBar.actionMap");
315     }
316
317     InputMap getInputMap(int condition) {
318     if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) {
319         return (InputMap)DefaultLookup.get(toolBar, this,
320                     "ToolBar.ancestorInputMap");
321     }
322     return null;
323     }
324
325     static void loadActionMap(LazyActionMap JavaDoc map) {
326         map.put(new Actions(Actions.NAVIGATE_RIGHT));
327         map.put(new Actions(Actions.NAVIGATE_LEFT));
328         map.put(new Actions(Actions.NAVIGATE_UP));
329         map.put(new Actions(Actions.NAVIGATE_DOWN));
330     }
331
332     protected void uninstallKeyboardActions( )
333     {
334     SwingUtilities.replaceUIActionMap(toolBar, null);
335     SwingUtilities.replaceUIInputMap(toolBar, JComponent.
336                      WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
337                      null);
338     }
339
340     protected void navigateFocusedComp( int direction )
341     {
342         int nComp = toolBar.getComponentCount();
343     int j;
344
345         switch ( direction )
346     {
347         case EAST:
348         case SOUTH:
349
350         if ( focusedCompIndex < 0 || focusedCompIndex >= nComp ) break;
351
352         j = focusedCompIndex + 1;
353
354         while ( j != focusedCompIndex )
355         {
356             if ( j >= nComp ) j = 0;
357             Component comp = toolBar.getComponentAtIndex( j++ );
358
359             if ( comp != null && comp.isFocusTraversable() && comp.isEnabled() )
360             {
361                 comp.requestFocus();
362             break;
363             }
364         }
365
366             break;
367
368         case WEST:
369         case NORTH:
370
371         if ( focusedCompIndex < 0 || focusedCompIndex >= nComp ) break;
372
373         j = focusedCompIndex - 1;
374
375         while ( j != focusedCompIndex )
376         {
377             if ( j < 0 ) j = nComp - 1;
378             Component comp = toolBar.getComponentAtIndex( j-- );
379
380             if ( comp != null && comp.isFocusTraversable() && comp.isEnabled() )
381             {
382                 comp.requestFocus();
383             break;
384             }
385         }
386
387             break;
388
389         default:
390             break;
391     }
392     }
393
394     /**
395      * Creates a rollover border for toolbar components. The
396      * rollover border will be installed if rollover borders are
397      * enabled.
398      * <p>
399      * Override this method to provide an alternate rollover border.
400      *
401      * @since 1.4
402      */

403     protected Border createRolloverBorder() {
404         Object JavaDoc border = UIManager.get("ToolBar.rolloverBorder");
405         if (border != null) {
406             return (Border)border;
407         }
408     UIDefaults table = UIManager.getLookAndFeelDefaults();
409     return new CompoundBorder(new BasicBorders.RolloverButtonBorder JavaDoc(
410                        table.getColor("controlShadow"),
411                                            table.getColor("controlDkShadow"),
412                                            table.getColor("controlHighlight"),
413                                            table.getColor("controlLtHighlight")),
414                   new BasicBorders.RolloverMarginBorder JavaDoc());
415     }
416
417     /**
418      * Creates the non rollover border for toolbar components. This
419      * border will be installed as the border for components added
420      * to the toolbar if rollover borders are not enabled.
421      * <p>
422      * Override this method to provide an alternate rollover border.
423      *
424      * @since 1.4
425      */

426     protected Border createNonRolloverBorder() {
427         Object JavaDoc border = UIManager.get("ToolBar.nonrolloverBorder");
428         if (border != null) {
429             return (Border)border;
430         }
431     UIDefaults table = UIManager.getLookAndFeelDefaults();
432     return new CompoundBorder(new BasicBorders.ButtonBorder JavaDoc(
433                        table.getColor("Button.shadow"),
434                                            table.getColor("Button.darkShadow"),
435                                            table.getColor("Button.light"),
436                                            table.getColor("Button.highlight")),
437                   new BasicBorders.RolloverMarginBorder JavaDoc());
438     }
439
440     /**
441      * Creates a non rollover border for Toggle buttons in the toolbar.
442      */

443     private Border createNonRolloverToggleBorder() {
444     UIDefaults table = UIManager.getLookAndFeelDefaults();
445     return new CompoundBorder(new BasicBorders.RadioButtonBorder JavaDoc(
446                        table.getColor("ToggleButton.shadow"),
447                                            table.getColor("ToggleButton.darkShadow"),
448                                            table.getColor("ToggleButton.light"),
449                                            table.getColor("ToggleButton.highlight")),
450                   new BasicBorders.RolloverMarginBorder JavaDoc());
451     }
452
453     /**
454      * No longer used, use BasicToolBarUI.createFloatingWindow(JToolBar)
455      * @see #createFloatingWindow
456      */

457     protected JFrame createFloatingFrame(JToolBar toolbar) {
458     Window window = SwingUtilities.getWindowAncestor(toolbar);
459     JFrame frame = new JFrame(toolbar.getName(),
460                   (window != null) ? window.getGraphicsConfiguration() : null) {
461         // Override createRootPane() to automatically resize
462
// the frame when contents change
463
protected JRootPane createRootPane() {
464         JRootPane rootPane = new JRootPane() {
465             private boolean packing = false;
466
467             public void validate() {
468             super.validate();
469             if (!packing) {
470                 packing = true;
471                 pack();
472                 packing = false;
473             }
474             }
475         };
476         rootPane.setOpaque(true);
477         return rootPane;
478         }
479     };
480         frame.getRootPane().setName("ToolBar.FloatingFrame");
481     frame.setResizable(false);
482     WindowListener wl = createFrameListener();
483     frame.addWindowListener(wl);
484         return frame;
485     }
486
487     /**
488      * Creates a window which contains the toolbar after it has been
489      * dragged out from its container
490      * @return a <code>RootPaneContainer</code> object, containing the toolbar.
491      */

492     protected RootPaneContainer createFloatingWindow(JToolBar toolbar) {
493     class ToolBarDialog extends JDialog {
494         public ToolBarDialog(Frame owner, String JavaDoc title, boolean modal) {
495         super(owner, title, modal);
496         }
497
498         public ToolBarDialog(Dialog owner, String JavaDoc title, boolean modal) {
499         super(owner, title, modal);
500         }
501
502         // Override createRootPane() to automatically resize
503
// the frame when contents change
504
protected JRootPane createRootPane() {
505         JRootPane rootPane = new JRootPane() {
506             private boolean packing = false;
507
508             public void validate() {
509             super.validate();
510             if (!packing) {
511                 packing = true;
512                 pack();
513                 packing = false;
514             }
515             }
516         };
517         rootPane.setOpaque(true);
518         return rootPane;
519         }
520     }
521
522     JDialog dialog;
523     Window window = SwingUtilities.getWindowAncestor(toolbar);
524     if (window instanceof Frame) {
525         dialog = new ToolBarDialog((Frame)window, toolbar.getName(), false);
526     } else if (window instanceof Dialog) {
527         dialog = new ToolBarDialog((Dialog)window, toolbar.getName(), false);
528     } else {
529         dialog = new ToolBarDialog((Frame)null, toolbar.getName(), false);
530     }
531
532         dialog.getRootPane().setName("ToolBar.FloatingWindow");
533     dialog.setTitle(toolbar.getName());
534     dialog.setResizable(false);
535     WindowListener wl = createFrameListener();
536     dialog.addWindowListener(wl);
537         return dialog;
538     }
539
540     protected DragWindow createDragWindow(JToolBar toolbar) {
541     Window frame = null;
542     if(toolBar != null) {
543         Container p;
544         for(p = toolBar.getParent() ; p != null && !(p instanceof Window) ;
545         p = p.getParent());
546         if(p != null && p instanceof Window)
547         frame = (Window) p;
548     }
549     if(floatingToolBar == null) {
550         floatingToolBar = createFloatingWindow(toolBar);
551     }
552     if (floatingToolBar instanceof Window) frame = (Window) floatingToolBar;
553     DragWindow dragWindow = new DragWindow(frame);
554     return dragWindow;
555     }
556
557     /**
558      * Returns a flag to determine whether rollover button borders
559      * are enabled.
560      *
561      * @return true if rollover borders are enabled; false otherwise
562      * @see #setRolloverBorders
563      * @since 1.4
564      */

565     public boolean isRolloverBorders() {
566         return rolloverBorders;
567     }
568     
569     /**
570      * Sets the flag for enabling rollover borders on the toolbar and it will
571      * also install the apropriate border depending on the state of the flag.
572      *
573      * @param rollover if true, rollover borders are installed.
574      * Otherwise non-rollover borders are installed
575      * @see #isRolloverBorders
576      * @since 1.4
577      */

578     public void setRolloverBorders( boolean rollover ) {
579         rolloverBorders = rollover;
580         
581     if ( rolloverBorders ) {
582         installRolloverBorders( toolBar );
583     } else {
584         installNonRolloverBorders( toolBar );
585     }
586     }
587
588     /**
589      * Installs rollover borders on all the child components of the JComponent.
590      * <p>
591      * This is a convenience method to call <code>setBorderToRollover</code>
592      * for each child component.
593      *
594      * @param c container which holds the child components (usally a JToolBar)
595      * @see #setBorderToRollover
596      * @since 1.4
597      */

598     protected void installRolloverBorders ( JComponent c ) {
599     // Put rollover borders on buttons
600
Component[] components = c.getComponents();
601
602     for ( int i = 0; i < components.length; ++i ) {
603         if ( components[ i ] instanceof JComponent ) {
604         ( (JComponent)components[ i ] ).updateUI();
605         setBorderToRollover( components[ i ] );
606         }
607     }
608     }
609
610     /**
611      * Installs non-rollover borders on all the child components of the JComponent.
612      * A non-rollover border is the border that is installed on the child component
613      * while it is in the toolbar.
614      * <p>
615      * This is a convenience method to call <code>setBorderToNonRollover</code>
616      * for each child component.
617      *
618      * @param c container which holds the child components (usally a JToolBar)
619      * @see #setBorderToNonRollover
620      * @since 1.4
621      */

622     protected void installNonRolloverBorders ( JComponent c ) {
623     // Put non-rollover borders on buttons. These borders reduce the margin.
624
Component[] components = c.getComponents();
625
626     for ( int i = 0; i < components.length; ++i ) {
627         if ( components[ i ] instanceof JComponent ) {
628         ( (JComponent)components[ i ] ).updateUI();
629         setBorderToNonRollover( components[ i ] );
630         }
631     }
632     }
633
634     /**
635      * Installs normal borders on all the child components of the JComponent.
636      * A normal border is the original border that was installed on the child
637      * component before it was added to the toolbar.
638      * <p>
639      * This is a convenience method to call <code>setBorderNormal</code>
640      * for each child component.
641      *
642      * @param c container which holds the child components (usally a JToolBar)
643      * @see #setBorderToNonRollover
644      * @since 1.4
645      */

646     protected void installNormalBorders ( JComponent c ) {
647     // Put back the normal borders on buttons
648
Component[] components = c.getComponents();
649
650     for ( int i = 0; i < components.length; ++i ) {
651         setBorderToNormal( components[ i ] );
652     }
653     }
654
655     /**
656      * Sets the border of the component to have a rollover border which
657      * was created by <code>createRolloverBorder</code>.
658      *
659      * @param c component which will have a rollover border installed
660      * @see #createRolloverBorder
661      * @since 1.4
662      */

663     protected void setBorderToRollover(Component c) {
664         if (c instanceof AbstractButton) {
665         AbstractButton b = (AbstractButton)c;
666         
667         Border border = (Border)borderTable.get(b);
668         if (border == null || border instanceof UIResource) {
669         borderTable.put(b, b.getBorder());
670         }
671
672         // Only set the border if its the default border
673
if (b.getBorder() instanceof UIResource) {
674         b.setBorder(getRolloverBorder(b));
675         }
676
677         rolloverTable.put(b, b.isRolloverEnabled()?
678                   Boolean.TRUE: Boolean.FALSE);
679         b.setRolloverEnabled(true);
680     }
681     }
682
683     private Border getRolloverBorder(AbstractButton b) {
684         Object JavaDoc borderProvider = UIManager.get("ToolBar.rolloverBorderProvider");
685         if(borderProvider == null) {
686             return rolloverBorder;
687         }
688         
689         return ((BorderProvider) borderProvider).getRolloverBorder(b);
690     }
691     
692     /**
693      * Sets the border of the component to have a non-rollover border which
694      * was created by <code>createNonRolloverBorder</code>.
695      *
696      * @param c component which will have a non-rollover border installed
697      * @see #createNonRolloverBorder
698      * @since 1.4
699      */

700     protected void setBorderToNonRollover(Component c) {
701         if (c instanceof AbstractButton) {
702         AbstractButton b = (AbstractButton)c;
703         
704         Border border = (Border)borderTable.get(b);
705         if (border == null || border instanceof UIResource) {
706         borderTable.put(b, b.getBorder());
707         }
708
709         // Only set the border if its the default border
710
if (b.getBorder() instanceof UIResource) {
711         if (b instanceof JToggleButton) {
712             ((JToggleButton)b).setBorder(nonRolloverToggleBorder);
713         } else {
714             b.setBorder(nonRolloverBorder);
715         }
716         }
717         rolloverTable.put(b, b.isRolloverEnabled()?
718                   Boolean.TRUE: Boolean.FALSE);
719         b.setRolloverEnabled(false);
720     }
721     }
722
723
724
725     /**
726      * Sets the border of the component to have a normal border.
727      * A normal border is the original border that was installed on the child
728      * component before it was added to the toolbar.
729      *
730      * @param c component which will have a normal border re-installed
731      * @see #createNonRolloverBorder
732      * @since 1.4
733      */

734     protected void setBorderToNormal(Component c) {
735         if (c instanceof AbstractButton) {
736         AbstractButton b = (AbstractButton)c;
737
738         Border border = (Border)borderTable.remove(b);
739         b.setBorder(border);
740
741         Boolean JavaDoc value = (Boolean JavaDoc)rolloverTable.remove(b);
742         if (value != null) {
743         b.setRolloverEnabled(value.booleanValue());
744         }
745     }
746     }
747
748     public void setFloatingLocation(int x, int y) {
749     floatingX = x;
750     floatingY = y;
751     }
752     
753     public boolean isFloating() {
754     return floating;
755     }
756
757     public void setFloating(boolean b, Point p) {
758     if (toolBar.isFloatable() == true) {
759         if (dragWindow != null)
760         dragWindow.setVisible(false);
761         this.floating = b;
762         if (b == true)
763         {
764         if (dockingSource == null)
765         {
766             dockingSource = toolBar.getParent();
767             dockingSource.remove(toolBar);
768         }
769         constraintBeforeFloating = calculateConstraint();
770         if ( propertyListener != null )
771                     UIManager.addPropertyChangeListener( propertyListener );
772         if (floatingToolBar == null)
773             floatingToolBar = createFloatingWindow(toolBar);
774         floatingToolBar.getContentPane().add(toolBar,BorderLayout.CENTER);
775         if (floatingToolBar instanceof Window) ((Window)floatingToolBar).pack();
776         if (floatingToolBar instanceof Window) ((Window)floatingToolBar).setLocation(floatingX, floatingY);
777         if (floatingToolBar instanceof Window) ((Window)floatingToolBar).show();
778         } else {
779         if (floatingToolBar == null)
780             floatingToolBar = createFloatingWindow(toolBar);
781         if (floatingToolBar instanceof Window) ((Window)floatingToolBar).setVisible(false);
782         floatingToolBar.getContentPane().remove(toolBar);
783         String JavaDoc constraint = getDockingConstraint(dockingSource,
784                              p);
785         if (constraint == null) {
786             constraint = BorderLayout.NORTH;
787         }
788         int orientation = mapConstraintToOrientation(constraint);
789         setOrientation(orientation);
790         if (dockingSource== null)
791             dockingSource = toolBar.getParent();
792         if ( propertyListener != null )
793             UIManager.removePropertyChangeListener( propertyListener );
794         dockingSource.add(constraint, toolBar);
795         }
796         dockingSource.invalidate();
797         Container dockingSourceParent = dockingSource.getParent();
798         if (dockingSourceParent != null)
799         dockingSourceParent.validate();
800         dockingSource.repaint();
801     }
802     }
803
804     private int mapConstraintToOrientation(String JavaDoc constraint)
805     {
806     int orientation = toolBar.getOrientation();
807
808     if ( constraint != null )
809     {
810         if ( constraint.equals(BorderLayout.EAST) || constraint.equals(BorderLayout.WEST) )
811             orientation = JToolBar.VERTICAL;
812         else if ( constraint.equals(BorderLayout.NORTH) || constraint.equals(BorderLayout.SOUTH) )
813             orientation = JToolBar.HORIZONTAL;
814     }
815
816     return orientation;
817     }
818     
819     public void setOrientation(int orientation)
820     {
821         toolBar.setOrientation( orientation );
822
823     if (dragWindow !=null)
824         dragWindow.setOrientation(orientation);
825     }
826     
827     /**
828      * Gets the color displayed when over a docking area
829      */

830     public Color getDockingColor() {
831     return dockingColor;
832     }
833     
834     /**
835      * Sets the color displayed when over a docking area
836      */

837    public void setDockingColor(Color c) {
838     this.dockingColor = c;
839     }
840
841     /**
842      * Gets the color displayed when over a floating area
843      */

844     public Color getFloatingColor() {
845     return floatingColor;
846     }
847
848     /**
849      * Sets the color displayed when over a floating area
850      */

851     public void setFloatingColor(Color c) {
852     this.floatingColor = c;
853     }
854     
855     private boolean isBlocked(Component comp, Object JavaDoc constraint) {
856     if (comp instanceof Container) {
857         Container cont = (Container)comp;
858         LayoutManager lm = cont.getLayout();
859         if (lm instanceof BorderLayout) {
860         BorderLayout blm = (BorderLayout)lm;
861         Component c = blm.getLayoutComponent(cont, constraint);
862         return (c != null && c != toolBar);
863         }
864     }
865     return false;
866     }
867
868     public boolean canDock(Component c, Point p) {
869     return (p != null && getDockingConstraint(c, p) != null);
870     }
871
872     private String JavaDoc calculateConstraint() {
873     String JavaDoc constraint = null;
874     LayoutManager lm = dockingSource.getLayout();
875     if (lm instanceof BorderLayout) {
876         constraint = (String JavaDoc)((BorderLayout)lm).getConstraints(toolBar);
877     }
878     return (constraint != null) ? constraint : constraintBeforeFloating;
879     }
880
881
882
883     private String JavaDoc getDockingConstraint(Component c, Point p) {
884     if (p == null) return constraintBeforeFloating;
885     if (c.contains(p)) {
886         dockingSensitivity = (toolBar.getOrientation() == JToolBar.HORIZONTAL)
887                         ? toolBar.getSize().height
888                         : toolBar.getSize().width;
889         // North (Base distance on height for now!)
890
if (p.y < dockingSensitivity && !isBlocked(c, BorderLayout.NORTH)) {
891         return BorderLayout.NORTH;
892         }
893         // East (Base distance on height for now!)
894
if (p.x >= c.getWidth() - dockingSensitivity && !isBlocked(c, BorderLayout.EAST)) {
895         return BorderLayout.EAST;
896         }
897         // West (Base distance on height for now!)
898
if (p.x < dockingSensitivity && !isBlocked(c, BorderLayout.WEST)) {
899         return BorderLayout.WEST;
900         }
901         if (p.y >= c.getHeight() - dockingSensitivity && !isBlocked(c, BorderLayout.SOUTH)) {
902         return BorderLayout.SOUTH;
903         }
904     }
905     return null;
906     }
907
908     protected void dragTo(Point position, Point origin)
909     {
910     if (toolBar.isFloatable() == true)
911     {
912       try
913       {
914         if (dragWindow == null)
915         dragWindow = createDragWindow(toolBar);
916         Point offset = dragWindow.getOffset();
917         if (offset == null) {
918         Dimension size = toolBar.getPreferredSize();
919         offset = new Point(size.width/2, size.height/2);
920         dragWindow.setOffset(offset);
921         }
922         Point global = new Point(origin.x+ position.x,
923                      origin.y+position.y);
924         Point dragPoint = new Point(global.x- offset.x,
925                     global.y- offset.y);
926         if (dockingSource == null)
927         dockingSource = toolBar.getParent();
928         constraintBeforeFloating = calculateConstraint();
929         Point dockingPosition = dockingSource.getLocationOnScreen();
930         Point comparisonPoint = new Point(global.x-dockingPosition.x,
931                           global.y-dockingPosition.y);
932         if (canDock(dockingSource, comparisonPoint)) {
933         dragWindow.setBackground(getDockingColor());
934         String JavaDoc constraint = getDockingConstraint(dockingSource,
935                              comparisonPoint);
936         int orientation = mapConstraintToOrientation(constraint);
937         dragWindow.setOrientation(orientation);
938         dragWindow.setBorderColor(dockingBorderColor);
939         } else {
940         dragWindow.setBackground(getFloatingColor());
941         dragWindow.setBorderColor(floatingBorderColor);
942         }
943         
944         dragWindow.setLocation(dragPoint.x, dragPoint.y);
945         if (dragWindow.isVisible() == false) {
946         Dimension size = toolBar.getPreferredSize();
947         dragWindow.setSize(size.width, size.height);
948         dragWindow.show();
949         }
950       }
951       catch ( IllegalComponentStateException e )
952       {
953       }
954     }
955     }
956
957     protected void floatAt(Point position, Point origin)
958     {
959     if(toolBar.isFloatable() == true)
960     {
961       try
962       {
963         Point offset = dragWindow.getOffset();
964         if (offset == null) {
965         offset = position;
966         dragWindow.setOffset(offset);
967         }
968         Point global = new Point(origin.x+ position.x,
969                      origin.y+position.y);
970         setFloatingLocation(global.x-offset.x,
971                 global.y-offset.y);
972         if (dockingSource != null) {
973         Point dockingPosition = dockingSource.getLocationOnScreen();
974         Point comparisonPoint = new Point(global.x-dockingPosition.x,
975                           global.y-dockingPosition.y);
976         if (canDock(dockingSource, comparisonPoint)) {
977             setFloating(false, comparisonPoint);
978         } else {
979             setFloating(true, null);
980         }
981         } else {
982         setFloating(true, null);
983         }
984         dragWindow.setOffset(null);
985       }
986       catch ( IllegalComponentStateException e )
987       {
988       }
989     }
990     }
991
992     private Handler getHandler() {
993         if (handler == null) {
994             handler = new Handler();
995         }
996         return handler;
997     }
998
999     protected ContainerListener createToolBarContListener( )
1000    {
1001        return getHandler();
1002    }
1003
1004    protected FocusListener createToolBarFocusListener( )
1005    {
1006        return getHandler();
1007    }
1008
1009    protected PropertyChangeListener createPropertyListener()
1010    {
1011        return getHandler();
1012    }
1013
1014    protected MouseInputListener createDockingListener( ) {
1015        getHandler().tb = toolBar;
1016        return getHandler();
1017    }
1018    
1019    protected WindowListener createFrameListener() {
1020    return new FrameListener();
1021    }
1022
1023    /**
1024     * Paints the contents of the window used for dragging.
1025     *
1026     * @param g Graphics to paint to.
1027     * @throws NullPointerException is <code>g</code> is null
1028     * @since 1.5
1029     */

1030    protected void paintDragWindow(Graphics g) {
1031        g.setColor(dragWindow.getBackground());
1032        int w = dragWindow.getWidth();
1033        int h = dragWindow.getHeight();
1034        g.fillRect(0, 0, w, h);
1035        g.setColor(dragWindow.getBorderColor());
1036        g.drawRect(0, 0, w - 1, h - 1);
1037    }
1038
1039
1040    private static class Actions extends UIAction {
1041        private static final String JavaDoc NAVIGATE_RIGHT = "navigateRight";
1042        private static final String JavaDoc NAVIGATE_LEFT = "navigateLeft";
1043        private static final String JavaDoc NAVIGATE_UP = "navigateUp";
1044        private static final String JavaDoc NAVIGATE_DOWN = "navigateDown";
1045
1046        public Actions(String JavaDoc name) {
1047            super(name);
1048        }
1049
1050        public void actionPerformed(ActionEvent evt) {
1051            String JavaDoc key = getName();
1052            JToolBar toolBar = (JToolBar)evt.getSource();
1053            BasicToolBarUI JavaDoc ui = (BasicToolBarUI JavaDoc)BasicLookAndFeel.getUIOfType(
1054                     toolBar.getUI(), BasicToolBarUI JavaDoc.class);
1055
1056            if (NAVIGATE_RIGHT == key) {
1057                ui.navigateFocusedComp(EAST);
1058            } else if (NAVIGATE_LEFT == key) {
1059                ui.navigateFocusedComp(WEST);
1060            } else if (NAVIGATE_UP == key) {
1061                ui.navigateFocusedComp(NORTH);
1062            } else if (NAVIGATE_DOWN == key) {
1063                ui.navigateFocusedComp(SOUTH);
1064            }
1065        }
1066    }
1067
1068
1069    private class Handler implements ContainerListener,
1070            FocusListener, MouseInputListener, PropertyChangeListener {
1071
1072        //
1073
// ContainerListener
1074
//
1075
public void componentAdded(ContainerEvent evt) {
1076            Component c = evt.getChild();
1077
1078            if (toolBarFocusListener != null) {
1079                c.addFocusListener(toolBarFocusListener);
1080            }
1081
1082            if (isRolloverBorders()) {
1083                setBorderToRollover(c);
1084            } else {
1085                setBorderToNonRollover(c);
1086            }
1087        }
1088
1089        public void componentRemoved(ContainerEvent evt) {
1090            Component c = evt.getChild();
1091
1092            if (toolBarFocusListener != null) {
1093                c.removeFocusListener(toolBarFocusListener);
1094            }
1095
1096            // Revert the button border
1097
setBorderToNormal(c);
1098        }
1099
1100
1101        //
1102
// FocusListener
1103
//
1104
public void focusGained(FocusEvent evt) {
1105            Component c = evt.getComponent();
1106            focusedCompIndex = toolBar.getComponentIndex(c);
1107        }
1108
1109        public void focusLost(FocusEvent evt) { }
1110
1111
1112        //
1113
// MouseInputListener (DockingListener)
1114
//
1115
JToolBar tb;
1116        boolean isDragging = false;
1117        Point origin = null;
1118
1119        public void mousePressed(MouseEvent evt) {
1120            if (!tb.isEnabled()) {
1121                return;
1122            }
1123            isDragging = false;
1124        }
1125
1126        public void mouseReleased(MouseEvent evt) {
1127            if (!tb.isEnabled()) {
1128                return;
1129            }
1130            if (isDragging == true) {
1131                Point position = evt.getPoint();
1132                if (origin == null)
1133                    origin = evt.getComponent().getLocationOnScreen();
1134                floatAt(position, origin);
1135            }
1136            origin = null;
1137            isDragging = false;
1138        }
1139
1140        public void mouseDragged(MouseEvent evt) {
1141            if (!tb.isEnabled()) {
1142                return;
1143            }
1144            isDragging = true;
1145            Point position = evt.getPoint();
1146            if (origin == null) {
1147                origin = evt.getComponent().getLocationOnScreen();
1148            }
1149            dragTo(position, origin);
1150        }
1151
1152        public void mouseClicked(MouseEvent evt) {}
1153        public void mouseEntered(MouseEvent evt) {}
1154        public void mouseExited(MouseEvent evt) {}
1155        public void mouseMoved(MouseEvent evt) {}
1156
1157
1158        //
1159
// PropertyChangeListener
1160
//
1161
public void propertyChange(PropertyChangeEvent evt) {
1162            String JavaDoc propertyName = evt.getPropertyName();
1163            if (propertyName == "lookAndFeel") {
1164                toolBar.updateUI();
1165            } else if (propertyName == "orientation") {
1166                // Search for JSeparator components and change it's orientation
1167
// to match the toolbar and flip it's orientation.
1168
Component[] components = toolBar.getComponents();
1169                int orientation = ((Integer JavaDoc)evt.getNewValue()).intValue();
1170                JToolBar.Separator separator;
1171
1172                for (int i = 0; i < components.length; ++i) {
1173                    if (components[i] instanceof JToolBar.Separator) {
1174                        separator = (JToolBar.Separator)components[i];
1175                        if ((orientation == JToolBar.HORIZONTAL)) {
1176                            separator.setOrientation(JSeparator.VERTICAL);
1177                        } else {
1178                            separator.setOrientation(JSeparator.HORIZONTAL);
1179                        }
1180                        Dimension size = separator.getSeparatorSize();
1181                        if (size != null && size.width != size.height) {
1182                            // Flip the orientation.
1183
Dimension newSize =
1184                                new Dimension(size.height, size.width);
1185                            separator.setSeparatorSize(newSize);
1186                        }
1187                    }
1188                }
1189            } else if (propertyName == IS_ROLLOVER) {
1190        installNormalBorders(toolBar);
1191                setRolloverBorders(((Boolean JavaDoc)evt.getNewValue()).booleanValue());
1192            }
1193        }
1194    }
1195
1196    protected class FrameListener extends WindowAdapter {
1197    public void windowClosing(WindowEvent w) {
1198        if (toolBar.isFloatable() == true) {
1199        if (dragWindow != null)
1200            dragWindow.setVisible(false);
1201        floating = false;
1202        if (floatingToolBar == null)
1203            floatingToolBar = createFloatingWindow(toolBar);
1204        if (floatingToolBar instanceof Window) ((Window)floatingToolBar).setVisible(false);
1205        floatingToolBar.getContentPane().remove(toolBar);
1206        String JavaDoc constraint = constraintBeforeFloating;
1207                if (toolBar.getOrientation() == JToolBar.HORIZONTAL) {
1208                    if (constraint == "West" || constraint == "East") {
1209                        constraint = "North";
1210                    }
1211                } else {
1212                    if (constraint == "North" || constraint == "South") {
1213                        constraint = "West";
1214                    }
1215                }
1216        if (dockingSource == null)
1217            dockingSource = toolBar.getParent();
1218        if (propertyListener != null)
1219            UIManager.removePropertyChangeListener(propertyListener);
1220        dockingSource.add(toolBar, constraint);
1221        dockingSource.invalidate();
1222        Container dockingSourceParent = dockingSource.getParent();
1223        if (dockingSourceParent != null)
1224            dockingSourceParent.validate();
1225        dockingSource.repaint();
1226            }
1227    }
1228
1229    }
1230
1231    protected class ToolBarContListener implements ContainerListener {
1232        // NOTE: This class exists only for backward compatability. All
1233
// its functionality has been moved into Handler. If you need to add
1234
// new functionality add it to the Handler, but make sure this
1235
// class calls into the Handler.
1236
public void componentAdded( ContainerEvent e ) {
1237            getHandler().componentAdded(e);
1238        }
1239
1240        public void componentRemoved( ContainerEvent e ) {
1241            getHandler().componentRemoved(e);
1242        }
1243
1244    }
1245
1246    protected class ToolBarFocusListener implements FocusListener {
1247        // NOTE: This class exists only for backward compatability. All
1248
// its functionality has been moved into Handler. If you need to add
1249
// new functionality add it to the Handler, but make sure this
1250
// class calls into the Handler.
1251
public void focusGained( FocusEvent e ) {
1252            getHandler().focusGained(e);
1253        }
1254
1255        public void focusLost( FocusEvent e ) {
1256            getHandler().focusLost(e);
1257        }
1258    }
1259
1260    protected class PropertyListener implements PropertyChangeListener {
1261        // NOTE: This class exists only for backward compatability. All
1262
// its functionality has been moved into Handler. If you need to add
1263
// new functionality add it to the Handler, but make sure this
1264
// class calls into the Handler.
1265
public void propertyChange( PropertyChangeEvent e ) {
1266            getHandler().propertyChange(e);
1267        }
1268    }
1269
1270    /**
1271     * This class should be treated as a &quot;protected&quot; inner class.
1272     * Instantiate it only within subclasses of BasicToolBarUI.
1273     */

1274    public class DockingListener implements MouseInputListener {
1275        // NOTE: This class exists only for backward compatability. All
1276
// its functionality has been moved into Handler. If you need to add
1277
// new functionality add it to the Handler, but make sure this
1278
// class calls into the Handler.
1279
protected JToolBar toolBar;
1280    protected boolean isDragging = false;
1281    protected Point origin = null;
1282
1283    public DockingListener(JToolBar t) {
1284        this.toolBar = t;
1285            getHandler().tb = t;
1286    }
1287
1288    public void mouseClicked(MouseEvent e) {
1289        getHandler().mouseClicked(e);
1290    }
1291
1292    public void mousePressed(MouseEvent e) {
1293        getHandler().tb = toolBar;
1294        getHandler().mousePressed(e);
1295        isDragging = getHandler().isDragging;
1296    }
1297
1298    public void mouseReleased(MouseEvent e) {
1299        getHandler().tb = toolBar;
1300        getHandler().isDragging = isDragging;
1301        getHandler().origin = origin;
1302        getHandler().mouseReleased(e);
1303        isDragging = getHandler().isDragging;
1304        origin = getHandler().origin;
1305    }
1306
1307    public void mouseEntered(MouseEvent e) {
1308        getHandler().mouseEntered(e);
1309    }
1310
1311    public void mouseExited(MouseEvent e) {
1312        getHandler().mouseExited(e);
1313    }
1314
1315    public void mouseDragged(MouseEvent e) {
1316        getHandler().tb = toolBar;
1317        getHandler().origin = origin;
1318        getHandler().mouseDragged(e);
1319        isDragging = getHandler().isDragging;
1320        origin = getHandler().origin;
1321    }
1322
1323    public void mouseMoved(MouseEvent e) {
1324        getHandler().mouseMoved(e);
1325    }
1326    }
1327
1328    protected class DragWindow extends Window
1329    {
1330    Color borderColor = Color.gray;
1331    int orientation = toolBar.getOrientation();
1332    Point offset; // offset of the mouse cursor inside the DragWindow
1333

1334    DragWindow(Window w) {
1335        super(w);
1336    }
1337
1338    public void setOrientation(int o) {
1339        if(isShowing()) {
1340        if (o == this.orientation)
1341            return;
1342        this.orientation = o;
1343        Dimension size = getSize();
1344        setSize(new Dimension(size.height, size.width));
1345        if (offset!=null) {
1346                    if( BasicGraphicsUtils.isLeftToRight(toolBar) ) {
1347                        setOffset(new Point(offset.y, offset.x));
1348                    } else if( o == JToolBar.HORIZONTAL ) {
1349                        setOffset(new Point( size.height-offset.y, offset.x));
1350                    } else {
1351                        setOffset(new Point(offset.y, size.width-offset.x));
1352                    }
1353                }
1354        repaint();
1355        }
1356    }
1357
1358    public Point getOffset() {
1359        return offset;
1360    }
1361
1362    public void setOffset(Point p) {
1363        this.offset = p;
1364    }
1365    
1366    public void setBorderColor(Color c) {
1367        if (this.borderColor == c)
1368        return;
1369        this.borderColor = c;
1370        repaint();
1371    }
1372
1373    public Color getBorderColor() {
1374        return this.borderColor;
1375    }
1376
1377    public void paint(Graphics g) {
1378            paintDragWindow(g);
1379            // Paint the children
1380
super.paint(g);
1381    }
1382    public Insets getInsets() {
1383        return new Insets(1,1,1,1);
1384    }
1385    }
1386}
1387
Popular Tags