Merge from mainline (gomp-merge-2005-02-26).
[official-gcc.git] / libjava / javax / swing / plaf / basic / BasicProgressBarUI.java
blob1feb2c4ce452b5a6dd9a3b528eea2d4b8c6227e3
1 /* BasicProgressBarUI.java --
2 Copyright (C) 2004, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package javax.swing.plaf.basic;
41 import java.awt.Color;
42 import java.awt.Dimension;
43 import java.awt.Font;
44 import java.awt.FontMetrics;
45 import java.awt.Graphics;
46 import java.awt.Insets;
47 import java.awt.Point;
48 import java.awt.Rectangle;
49 import java.awt.event.ActionEvent;
50 import java.awt.event.ActionListener;
51 import java.beans.PropertyChangeEvent;
52 import java.beans.PropertyChangeListener;
54 import javax.swing.JComponent;
55 import javax.swing.JProgressBar;
56 import javax.swing.SwingConstants;
57 import javax.swing.SwingUtilities;
58 import javax.swing.Timer;
59 import javax.swing.UIDefaults;
60 import javax.swing.UIManager;
61 import javax.swing.event.ChangeEvent;
62 import javax.swing.event.ChangeListener;
63 import javax.swing.plaf.ComponentUI;
64 import javax.swing.plaf.ProgressBarUI;
66 /**
67 * The Basic Look and Feel UI delegate for the
68 * JProgressBar.
70 public class BasicProgressBarUI extends ProgressBarUI
72 /**
73 * A helper class that listens for ChangeEvents
74 * from the progressBar's model.
76 protected class ChangeHandler implements ChangeListener
78 /**
79 * Called every time the state of the model changes.
81 * @param e The ChangeEvent given by the model.
83 public void stateChanged(ChangeEvent e)
85 // Nothing to do but repaint.
86 progressBar.repaint();
90 /**
91 * This helper class is used to listen for
92 * PropertyChangeEvents from the progressBar.
94 private class PropertyChangeHandler implements PropertyChangeListener
96 /**
97 * Called every time the properties of the
98 * progressBar change.
100 * @param e The PropertyChangeEvent given by the progressBar.
102 public void propertyChange(PropertyChangeEvent e)
104 // Only need to listen for indeterminate changes.
105 // All other things are done on a repaint.
106 if (e.getPropertyName().equals("inderterminate"))
107 if (((Boolean) e.getNewValue()).booleanValue())
108 startAnimationTimer();
109 else
110 stopAnimationTimer();
111 else
112 progressBar.repaint();
117 * This helper class is used to listen for
118 * the animationTimer's intervals. On every interval,
119 * the bouncing box should move.
121 private class Animator implements ActionListener
124 * Called every time the animationTimer reaches
125 * its interval.
127 * @param e The ActionEvent given by the timer.
129 public void actionPerformed(ActionEvent e)
131 // Incrementing the animation index will cause
132 // a repaint.
133 incrementAnimationIndex();
137 /** The timer used to move the bouncing box. */
138 private transient Timer animationTimer;
140 // The total number of frames must be an even number.
141 // The total number of frames is calculated from
142 // the cycleTime and repaintInterval given by
143 // the basic Look and Feel defaults.
145 // +-----------------------------------------------+
146 // | frame0 | frame1 | frame2 | frame 3 | frame 4 |
147 // | | frame7 | frame6 | frame 5 | |
148 // +-----------------------------------------------+
150 /** The current animation index. */
151 private transient int animationIndex;
153 /** The total number of frames.*/
154 private transient int numFrames;
156 /** The helper that moves the bouncing box. */
157 private transient Animator animation;
159 /** The helper that listens for property change events. */
160 private transient PropertyChangeHandler propertyListener;
162 /** The Listener for the model. */
163 protected ChangeListener changeListener;
165 /** The progressBar for this UI. */
166 protected JProgressBar progressBar;
168 /** The length of the cell. The cell is the painted part. */
169 private transient int cellLength;
171 /** The gap between cells. */
172 private transient int cellSpacing;
174 /** The color of the text when the bar is not over it.*/
175 private transient Color selectionBackground;
177 /** The color of the text when the bar is over it. */
178 private transient Color selectionForeground;
181 * Creates a new BasicProgressBarUI object.
183 public BasicProgressBarUI()
185 super();
189 * Creates a new BasicProgressBarUI for the component.
191 * @param x The JComponent to create the UI for.
193 * @return A new BasicProgressBarUI.
195 public static ComponentUI createUI(JComponent x)
197 return new BasicProgressBarUI();
201 * This method returns the length of the bar (from the minimum)
202 * in pixels (or units that the Graphics object draws in) based
203 * on the progressBar's getPercentComplete() value.
205 * @param b The insets of the progressBar.
206 * @param width The width of the progressBar.
207 * @param height The height of the progressBar.
209 * @return The length of the bar that should be painted in pixels.
211 protected int getAmountFull(Insets b, int width, int height)
213 double percentDone = progressBar.getPercentComplete();
214 if (progressBar.getOrientation() == JProgressBar.HORIZONTAL)
215 return (int) (percentDone * (width - b.left - b.right));
216 else
217 return (int) (percentDone * (height - b.top - b.bottom));
221 * The current animation index.
223 * @return The current animation index.
225 protected int getAnimationIndex()
227 return animationIndex;
231 * This method returns the size and position of the bouncing box
232 * for the current animation index. It stores the values in the
233 * given rectangle and returns it. It returns null if no box should
234 * be drawn.
236 * @param r The bouncing box rectangle.
238 * @return The bouncing box rectangle.
240 protected Rectangle getBox(Rectangle r)
242 if (!progressBar.isIndeterminate())
243 return null;
244 //numFrames has to be an even number as defined by spec.
245 int iterations = numFrames / 2 + 1;
247 double boxDependent;
248 double boxIndependent;
250 if (progressBar.getOrientation() == JProgressBar.HORIZONTAL)
252 Dimension dims = getPreferredInnerHorizontal();
253 boxDependent = (double) dims.width / iterations;
254 boxIndependent = dims.height;
256 else
258 Dimension dims = getPreferredInnerVertical();
259 boxDependent = (double) dims.height / iterations;
260 boxIndependent = dims.width;
263 Rectangle vr = new Rectangle();
264 SwingUtilities.calculateInnerArea(progressBar, vr);
266 int index = getAnimationIndex();
267 if (animationIndex > (numFrames + 1) / 2)
268 index = numFrames - getAnimationIndex();
270 if (progressBar.getOrientation() == JProgressBar.HORIZONTAL)
272 r.x = vr.x + (int) (index * boxDependent);
273 r.y = vr.y;
274 r.width = (int) boxDependent;
275 r.height = (int) boxIndependent;
277 else
279 index++;
280 r.x = vr.x;
281 r.y = vr.height - (int) (index * boxDependent) + vr.y;
282 r.width = (int) boxIndependent;
283 r.height = (int) boxDependent;
286 return r;
290 * This method returns the length of the cells.
292 * @return The cell length.
294 protected int getCellLength()
296 return cellLength;
300 * This method returns the spacing between cells.
302 * @return The cell gap.
304 protected int getCellSpacing()
306 return cellSpacing;
310 * This method returns the maximum size of the JComponent.
311 * If it returns null, it is up to the LayoutManager
312 * to give it a size.
314 * @param c The component to find a maximum size for.
316 * @return The maximum size.
318 public Dimension getMaximumSize(JComponent c)
320 return getPreferredSize(c);
324 * This method returns the minimum size of the JComponent.
325 * If it returns null, it is up to the LayoutManager to
326 * give it a size.
328 * @param c The component to find a minimum size for.
330 * @return The minimum size.
332 public Dimension getMinimumSize(JComponent c)
334 return getPreferredSize(c);
338 * This method returns the preferred size of the inner
339 * rectangle (the bounds without the insets) if the
340 * progressBar is horizontal.
342 * @return The preferred size of the progressBar minus
343 * insets if it's horizontal.
345 protected Dimension getPreferredInnerHorizontal()
347 Rectangle vr = new Rectangle();
349 SwingUtilities.calculateInnerArea(progressBar, vr);
351 return new Dimension(vr.width, vr.height);
355 * This method returns the preferred size of the inner
356 * rectangle (the bounds without insets) if the
357 * progressBar is vertical.
359 * @return The preferred size of the progressBar minus
360 * insets if it's vertical.
362 protected Dimension getPreferredInnerVertical()
364 Rectangle vr = new Rectangle();
366 SwingUtilities.calculateInnerArea(progressBar, vr);
368 return new Dimension(vr.width, vr.height);
372 * This method returns the preferred size of the
373 * given JComponent. If it returns null, then it
374 * is up to the LayoutManager to give it a size.
376 * @param c The component to find the preferred size for.
378 * @return The preferred size of the component.
380 public Dimension getPreferredSize(JComponent c)
382 // The only thing we need to worry about is
383 // the text size.
384 Graphics g = progressBar.getGraphics();
386 Insets insets = c.getInsets();
388 FontMetrics fm = g.getFontMetrics(c.getFont());
390 int textW = fm.stringWidth(progressBar.getString());
391 int textH = fm.getHeight();
393 g.dispose();
395 if (progressBar.getOrientation() == JProgressBar.HORIZONTAL)
397 if (textH < 20)
398 textH = 20;
399 if (textW < 200)
400 textW = 200;
402 else
404 if (textH < 200)
405 textH = 200;
406 if (textW < 20)
407 textW = 20;
409 textW += insets.left + insets.right;
410 textH += insets.top + insets.bottom;
411 return new Dimension(textW, textH);
415 * This method returns the Color that the text is shown in when the bar is
416 * not over the text.
418 * @return The color of the text when the bar is not over it.
420 protected Color getSelectionBackground()
422 return selectionBackground;
426 * This method returns the Color that the text is shown in when the bar is
427 * over the text.
429 * @return The color of the text when the bar is over it.
431 protected Color getSelectionForeground()
433 return selectionForeground;
437 * This method returns the point (the top left of the bounding box)
438 * where the text should be painted.
440 * @param g The Graphics object to measure FontMetrics with.
441 * @param progressString The string to paint.
442 * @param x The x coordinate of the overall bounds box.
443 * @param y The y coordinate of the overall bounds box.
444 * @param width The width of the overall bounds box.
445 * @param height The height of the overall bounds box.
447 * @return The top left of the bounding box where text should be painted.
449 protected Point getStringPlacement(Graphics g, String progressString, int x,
450 int y, int width, int height)
452 Rectangle tr = new Rectangle();
453 Rectangle vr = new Rectangle(x, y, width, height);
454 Rectangle ir = new Rectangle();
456 Font f = g.getFont();
457 FontMetrics fm = g.getFontMetrics(f);
459 SwingUtilities.layoutCompoundLabel(progressBar, fm, progressString, null,
460 SwingConstants.CENTER,
461 SwingConstants.CENTER,
462 SwingConstants.CENTER,
463 SwingConstants.CENTER, vr, ir, tr, 0);
464 return new Point(tr.x, tr.y);
468 * This method increments the animation index.
470 protected void incrementAnimationIndex()
472 animationIndex++;
473 //numFrames is like string length, it should be named numFrames or something
474 if (animationIndex >= numFrames)
475 animationIndex = 0;
476 progressBar.repaint();
480 * This method paints the progressBar. It delegates its responsibilities
481 * to paintDeterminate and paintIndeterminate.
483 * @param g The Graphics object to paint with.
484 * @param c The JComponent to paint.
486 public void paint(Graphics g, JComponent c)
488 if (! progressBar.isIndeterminate())
489 paintDeterminate(g, c);
490 else
491 paintIndeterminate(g, c);
493 if (progressBar.isBorderPainted())
494 progressBar.getBorder().paintBorder(progressBar, g, 0, 0,
495 progressBar.getWidth(),
496 progressBar.getHeight());
500 * This method is called if the painting to be done is
501 * for a determinate progressBar.
503 * @param g The Graphics object to paint with.
504 * @param c The JComponent to paint.
506 protected void paintDeterminate(Graphics g, JComponent c)
508 Color saved = g.getColor();
509 int space = getCellSpacing();
510 int len = getCellLength();
511 int max = progressBar.getMaximum();
512 int min = progressBar.getMinimum();
513 int value = progressBar.getValue();
515 Rectangle vr = new Rectangle();
516 SwingUtilities.calculateInnerArea(c, vr);
518 Rectangle or = c.getBounds();
520 Insets insets = c.getInsets();
522 int amountFull = getAmountFull(insets, or.width, or.height);
524 g.setColor(c.getBackground());
525 g.fill3DRect(vr.x, vr.y, vr.width, vr.height, false);
527 if (max != min && len != 0 && value > min)
529 int iterations = value / (space + len);
531 if (progressBar.getOrientation() == JProgressBar.HORIZONTAL)
533 double spaceInUnits = space * (double) vr.width / (max - min);
534 double lenInUnits = len * (double) vr.width / (max - min);
535 double currX = vr.x;
537 g.setColor(c.getForeground());
538 g.fill3DRect(vr.x, vr.y, amountFull, vr.height, true);
540 g.setColor(c.getBackground());
541 if (spaceInUnits != 0)
543 for (int i = 0; i < iterations; i++)
545 currX += lenInUnits;
546 g.fill3DRect((int) currX, vr.y, (int) spaceInUnits,
547 vr.height, true);
548 currX += spaceInUnits;
552 else
554 double currY = vr.y;
555 double spaceInUnits = space * (double) vr.height / (max - min);
556 double lenInUnits = len * (double) vr.height / (max - min);
558 g.setColor(c.getForeground());
559 g.fill3DRect(vr.x, vr.y + vr.height - amountFull, vr.width,
560 amountFull, true);
562 g.setColor(c.getBackground());
564 if (spaceInUnits != 0)
566 for (int i = 0; i < iterations; i++)
568 currY -= lenInUnits + spaceInUnits;
569 g.fill3DRect(vr.x, (int) currY, vr.width,
570 (int) spaceInUnits, true);
576 if (progressBar.isStringPainted() && !progressBar.getString().equals(""))
577 paintString(g, 0, 0, or.width, or.height, amountFull, insets);
578 g.setColor(saved);
582 * This method is called if the painting to be done is for
583 * an indeterminate progressBar.
585 * @param g The Graphics object to paint with.
586 * @param c The JComponent to paint.
588 protected void paintIndeterminate(Graphics g, JComponent c)
590 //need to paint the box at it's current position. no text is painted since
591 //all we're doing is bouncing back and forth
592 Color saved = g.getColor();
593 Insets insets = c.getInsets();
595 Rectangle or = c.getBounds();
596 Rectangle vr = new Rectangle();
597 SwingUtilities.calculateInnerArea(c, vr);
599 g.setColor(c.getBackground());
600 g.fill3DRect(vr.x, vr.y, vr.width, vr.height, false);
602 Rectangle box = new Rectangle();
603 getBox(box);
605 g.setColor(c.getForeground());
606 g.fill3DRect(box.x, box.y, box.width, box.height, true);
608 if (progressBar.isStringPainted() && !progressBar.getString().equals(""))
609 paintString(g, 0, 0, or.width, or.height,
610 getAmountFull(insets, or.width, or.height), insets);
612 g.setColor(saved);
616 * This method paints the string for the progressBar.
618 * @param g The Graphics object to paint with.
619 * @param x The x coordinate of the progressBar.
620 * @param y The y coordinate of the progressBar.
621 * @param width The width of the progressBar.
622 * @param height The height of the progressBar.
623 * @param amountFull The amount of the progressBar that has its bar filled.
624 * @param b The insets of the progressBar.
626 protected void paintString(Graphics g, int x, int y, int width, int height,
627 int amountFull, Insets b)
629 // We want to place in the exact center of the bar.
630 Point placement = getStringPlacement(g, progressBar.getString(),
631 x + b.left, y + b.top,
632 width - b.left - b.right,
633 height - b.top - b.bottom);
634 Color saved = g.getColor();
636 // FIXME: The Color of the text should use selectionForeground and selectionBackground
637 // but that can't be done right now, so we'll use white in the mean time.
638 g.setColor(Color.WHITE);
640 FontMetrics fm = g.getFontMetrics(progressBar.getFont());
642 g.drawString(progressBar.getString(), placement.x,
643 placement.y + fm.getAscent());
645 g.setColor(saved);
649 * This method sets the current animation index. If the index
650 * is greater than the number of frames, it resets to 0.
652 * @param newValue The new animation index.
654 protected void setAnimationIndex(int newValue)
656 animationIndex = (newValue <= numFrames) ? newValue : 0;
657 progressBar.repaint();
661 * This method sets the cell length.
663 * @param cellLen The cell length.
665 protected void setCellLength(int cellLen)
667 cellLength = cellLen;
671 * This method sets the cell spacing.
673 * @param cellSpace The cell spacing.
675 protected void setCellSpacing(int cellSpace)
677 cellSpacing = cellSpace;
681 * This method starts the animation timer. It is called
682 * when the propertyChangeListener detects that the progressBar
683 * has changed to indeterminate mode.
685 * @since 1.4
687 protected void startAnimationTimer()
689 if (animationTimer != null)
690 animationTimer.start();
694 * This method stops the animation timer. It is called when
695 * the propertyChangeListener detects that the progressBar
696 * has changed to determinate mode.
698 * @since 1.4
700 protected void stopAnimationTimer()
702 if (animationTimer != null)
703 animationTimer.stop();
704 setAnimationIndex(0);
708 * This method changes the settings for the progressBar to
709 * the defaults provided by the current Look and Feel.
711 protected void installDefaults()
713 UIDefaults defaults = UIManager.getLookAndFeelDefaults();
715 progressBar.setFont(defaults.getFont("ProgressBar.font"));
716 progressBar.setForeground(defaults.getColor("ProgressBar.foreground"));
717 progressBar.setBackground(defaults.getColor("ProgressBar.background"));
718 progressBar.setBorder(defaults.getBorder("ProgressBar.border"));
719 progressBar.setOpaque(true);
721 selectionForeground = defaults.getColor("ProgressBar.selectionForeground");
722 selectionBackground = defaults.getColor("ProgressBar.selectionBackground");
723 cellLength = defaults.getInt("ProgressBar.cellLength");
724 cellSpacing = defaults.getInt("ProgressBar.cellSpacing");
726 int repaintInterval = defaults.getInt("ProgressBar.repaintInterval");
727 int cycleTime = defaults.getInt("ProgressBar.cycleTime");
729 if (cycleTime % repaintInterval != 0
730 && (cycleTime / repaintInterval) % 2 != 0)
732 int div = (cycleTime / repaintInterval) + 2;
733 div /= 2;
734 div *= 2;
735 cycleTime = div * repaintInterval;
737 setAnimationIndex(0);
738 numFrames = cycleTime / repaintInterval;
739 animationTimer.setDelay(repaintInterval);
743 * The method uninstalls any defaults that were
744 * set by the current Look and Feel.
746 protected void uninstallDefaults()
748 progressBar.setFont(null);
749 progressBar.setForeground(null);
750 progressBar.setBackground(null);
752 selectionForeground = null;
753 selectionBackground = null;
757 * This method registers listeners to all the
758 * components that this UI delegate needs to listen to.
760 protected void installListeners()
762 changeListener = new ChangeHandler();
763 propertyListener = new PropertyChangeHandler();
764 animation = new Animator();
766 progressBar.addChangeListener(changeListener);
767 progressBar.addPropertyChangeListener(propertyListener);
768 animationTimer.addActionListener(animation);
772 * This method unregisters listeners to all the
773 * components that were listened to.
775 protected void uninstallListeners()
777 progressBar.removeChangeListener(changeListener);
778 progressBar.removePropertyChangeListener(propertyListener);
779 animationTimer.removeActionListener(animation);
781 changeListener = null;
782 propertyListener = null;
783 animation = null;
787 * This method installs the UI for the given JComponent.
788 * This includes setting up defaults and listeners as
789 * well as initializing any values or objects that
790 * the UI may need.
792 * @param c The JComponent that is having this UI installed.
794 public void installUI(JComponent c)
796 super.installUI(c);
797 if (c instanceof JProgressBar)
799 progressBar = (JProgressBar) c;
801 animationTimer = new Timer(200, null);
802 animationTimer.setRepeats(true);
804 installDefaults();
805 installListeners();
810 * This method removes the UI for the given JComponent.
811 * This includes removing any listeners or defaults
812 * that the installUI may have set up.
814 * @param c The JComponent that is having this UI uninstalled.
816 public void uninstallUI(JComponent c)
818 super.uninstallUI(c);
819 uninstallListeners();
820 uninstallDefaults();
822 animationTimer = null;
823 progressBar = null;