2025 lines · 70.1 KB · Java
RawDownload
/* * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.event.*;import java.awt.*;import java.beans.*;import java.util.Dictionary;import java.util.Enumeration; import javax.swing.*;import javax.swing.event.*;import javax.swing.plaf.*;import sun.swing.DefaultLookup;import sun.swing.UIAction;  /** * A Basic L&F implementation of SliderUI. * * @author Tom Santos */public class BasicSliderUI extends SliderUI{    // Old actions forward to an instance of this.    private static final Actions SHARED_ACTION = new Actions();     public static final int POSITIVE_SCROLL = +1;    public static final int NEGATIVE_SCROLL = -1;    public static final int MIN_SCROLL = -2;    public static final int MAX_SCROLL = +2;     protected Timer scrollTimer;    protected JSlider slider;     protected Insets focusInsets = null;    protected Insets insetCache = null;    protected boolean leftToRightCache = true;    protected Rectangle focusRect = null;    protected Rectangle contentRect = null;    protected Rectangle labelRect = null;    protected Rectangle tickRect = null;    protected Rectangle trackRect = null;    protected Rectangle thumbRect = null;     protected int trackBuffer = 0;  // The distance that the track is from the side of the control     private transient boolean isDragging;     protected TrackListener trackListener;    protected ChangeListener changeListener;    protected ComponentListener componentListener;    protected FocusListener focusListener;    protected ScrollListener scrollListener;    protected PropertyChangeListener propertyChangeListener;    private Handler handler;    private int lastValue;     // Colors    private Color shadowColor;    private Color highlightColor;    private Color focusColor;     /**     * Whther or not sameLabelBaselines is up to date.     */    private boolean checkedLabelBaselines;    /**     * Whether or not all the entries in the labeltable have the same     * baseline.     */    private boolean sameLabelBaselines;      protected Color getShadowColor() {        return shadowColor;    }     protected Color getHighlightColor() {        return highlightColor;    }     protected Color getFocusColor() {        return focusColor;    }     /**     * Returns true if the user is dragging the slider.     *     * @return true if the user is dragging the slider     * @since 1.5     */    protected boolean isDragging() {        return isDragging;    }     /////////////////////////////////////////////////////////////////////////////    // ComponentUI Interface Implementation methods    /////////////////////////////////////////////////////////////////////////////    public static ComponentUI createUI(JComponent b)    {        return new BasicSliderUI((JSlider)b);    }     public BasicSliderUI(JSlider b)   {    }     public void installUI(JComponent c)   {        slider = (JSlider) c;         checkedLabelBaselines = false;         slider.setEnabled(slider.isEnabled());        LookAndFeel.installProperty(slider, "opaque", Boolean.TRUE);         isDragging = false;        trackListener = createTrackListener( slider );        changeListener = createChangeListener( slider );        componentListener = createComponentListener( slider );        focusListener = createFocusListener( slider );        scrollListener = createScrollListener( slider );        propertyChangeListener = createPropertyChangeListener( slider );         installDefaults( slider );        installListeners( slider );        installKeyboardActions( slider );         scrollTimer = new Timer( 100, scrollListener );        scrollTimer.setInitialDelay( 300 );         insetCache = slider.getInsets();        leftToRightCache = BasicGraphicsUtils.isLeftToRight(slider);        focusRect = new Rectangle();        contentRect = new Rectangle();        labelRect = new Rectangle();        tickRect = new Rectangle();        trackRect = new Rectangle();        thumbRect = new Rectangle();        lastValue = slider.getValue();         calculateGeometry(); // This figures out where the labels, ticks, track, and thumb are.    }     public void uninstallUI(JComponent c) {        if ( c != slider )            throw new IllegalComponentStateException(                                                    this + " was asked to deinstall() "                                                    + c + " when it only knows about "                                                    + slider + ".");         scrollTimer.stop();        scrollTimer = null;         uninstallDefaults(slider);        uninstallListeners( slider );        uninstallKeyboardActions(slider);         insetCache = null;        leftToRightCache = true;        focusRect = null;        contentRect = null;        labelRect = null;        tickRect = null;        trackRect = null;        thumbRect = null;        trackListener = null;        changeListener = null;        componentListener = null;        focusListener = null;        scrollListener = null;        propertyChangeListener = null;        slider = null;    }     protected void installDefaults( JSlider slider ) {        LookAndFeel.installBorder(slider, "Slider.border");        LookAndFeel.installColorsAndFont(slider, "Slider.background",                                         "Slider.foreground", "Slider.font");        highlightColor = UIManager.getColor("Slider.highlight");         shadowColor = UIManager.getColor("Slider.shadow");        focusColor = UIManager.getColor("Slider.focus");         focusInsets = (Insets)UIManager.get( "Slider.focusInsets" );        // use default if missing so that BasicSliderUI can be used in other        // LAFs like Nimbus        if (focusInsets == null) focusInsets = new InsetsUIResource(2,2,2,2);    }     protected void uninstallDefaults(JSlider slider) {        LookAndFeel.uninstallBorder(slider);         focusInsets = null;    }     protected TrackListener createTrackListener(JSlider slider) {        return new TrackListener();    }     protected ChangeListener createChangeListener(JSlider slider) {        return getHandler();    }     protected ComponentListener createComponentListener(JSlider slider) {        return getHandler();    }     protected FocusListener createFocusListener(JSlider slider) {        return getHandler();    }     protected ScrollListener createScrollListener( JSlider slider ) {        return new ScrollListener();    }     protected PropertyChangeListener createPropertyChangeListener(            JSlider slider) {        return getHandler();    }     private Handler getHandler() {        if (handler == null) {            handler = new Handler();        }        return handler;    }     protected void installListeners( JSlider slider ) {        slider.addMouseListener(trackListener);        slider.addMouseMotionListener(trackListener);        slider.addFocusListener(focusListener);        slider.addComponentListener(componentListener);        slider.addPropertyChangeListener( propertyChangeListener );        slider.getModel().addChangeListener(changeListener);    }     protected void uninstallListeners( JSlider slider ) {        slider.removeMouseListener(trackListener);        slider.removeMouseMotionListener(trackListener);        slider.removeFocusListener(focusListener);        slider.removeComponentListener(componentListener);        slider.removePropertyChangeListener( propertyChangeListener );        slider.getModel().removeChangeListener(changeListener);        handler = null;    }     protected void installKeyboardActions( JSlider slider ) {        InputMap km = getInputMap(JComponent.WHEN_FOCUSED, slider);        SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, km);        LazyActionMap.installLazyActionMap(slider, BasicSliderUI.class,                "Slider.actionMap");    }     InputMap getInputMap(int condition, JSlider slider) {        if (condition == JComponent.WHEN_FOCUSED) {            InputMap keyMap = (InputMap)DefaultLookup.get(slider, this,                  "Slider.focusInputMap");            InputMap rtlKeyMap;             if (slider.getComponentOrientation().isLeftToRight() ||                ((rtlKeyMap = (InputMap)DefaultLookup.get(slider, this,                          "Slider.focusInputMap.RightToLeft")) == null)) {                return keyMap;            } else {                rtlKeyMap.setParent(keyMap);                return rtlKeyMap;            }        }        return null;    }     /**     * Populates ComboBox's actions.     */    static void loadActionMap(LazyActionMap map) {        map.put(new Actions(Actions.POSITIVE_UNIT_INCREMENT));        map.put(new Actions(Actions.POSITIVE_BLOCK_INCREMENT));        map.put(new Actions(Actions.NEGATIVE_UNIT_INCREMENT));        map.put(new Actions(Actions.NEGATIVE_BLOCK_INCREMENT));        map.put(new Actions(Actions.MIN_SCROLL_INCREMENT));        map.put(new Actions(Actions.MAX_SCROLL_INCREMENT));    }     protected void uninstallKeyboardActions( JSlider slider ) {        SwingUtilities.replaceUIActionMap(slider, null);        SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED,                                         null);    }      /**     * Returns the baseline.     *     * @throws NullPointerException {@inheritDoc}     * @throws IllegalArgumentException {@inheritDoc}     * @see javax.swing.JComponent#getBaseline(int, int)     * @since 1.6     */    public int getBaseline(JComponent c, int width, int height) {        super.getBaseline(c, width, height);        if (slider.getPaintLabels() && labelsHaveSameBaselines()) {            FontMetrics metrics = slider.getFontMetrics(slider.getFont());            Insets insets = slider.getInsets();            Dimension thumbSize = getThumbSize();            if (slider.getOrientation() == JSlider.HORIZONTAL) {                int tickLength = getTickLength();                int contentHeight = height - insets.top - insets.bottom -                    focusInsets.top - focusInsets.bottom;                int thumbHeight = thumbSize.height;                int centerSpacing = thumbHeight;                if (slider.getPaintTicks()) {                    centerSpacing += tickLength;                }                // Assume uniform labels.                centerSpacing += getHeightOfTallestLabel();                int trackY = insets.top + focusInsets.top +                    (contentHeight - centerSpacing - 1) / 2;                int trackHeight = thumbHeight;                int tickY = trackY + trackHeight;                int tickHeight = tickLength;                if (!slider.getPaintTicks()) {                    tickHeight = 0;                }                int labelY = tickY + tickHeight;                return labelY + metrics.getAscent();            }            else { // vertical                boolean inverted = slider.getInverted();                Integer value = inverted ? getLowestValue() :                                           getHighestValue();                if (value != null) {                    int thumbHeight = thumbSize.height;                    int trackBuffer = Math.max(metrics.getHeight() / 2,                                               thumbHeight / 2);                    int contentY = focusInsets.top + insets.top;                    int trackY = contentY + trackBuffer;                    int trackHeight = height - focusInsets.top -                        focusInsets.bottom - insets.top - insets.bottom -                        trackBuffer - trackBuffer;                    int yPosition = yPositionForValue(value, trackY,                                                      trackHeight);                    return yPosition - metrics.getHeight() / 2 +                        metrics.getAscent();                }            }        }        return 0;    }     /**     * Returns an enum indicating how the baseline of the component     * changes as the size changes.     *     * @throws NullPointerException {@inheritDoc}     * @see javax.swing.JComponent#getBaseline(int, int)     * @since 1.6     */    public Component.BaselineResizeBehavior getBaselineResizeBehavior(            JComponent c) {        super.getBaselineResizeBehavior(c);        // NOTE: BasicSpinner really provides for CENTER_OFFSET, but        // the default min/pref size is smaller than it should be        // so that getBaseline() doesn't implement the contract        // for CENTER_OFFSET as defined in Component.        return Component.BaselineResizeBehavior.OTHER;    }     /**     * Returns true if all the labels from the label table have the same     * baseline.     *     * @return true if all the labels from the label table have the     *         same baseline     * @since 1.6     */    protected boolean labelsHaveSameBaselines() {        if (!checkedLabelBaselines) {            checkedLabelBaselines = true;            Dictionary dictionary = slider.getLabelTable();            if (dictionary != null) {                sameLabelBaselines = true;                Enumeration elements = dictionary.elements();                int baseline = -1;                while (elements.hasMoreElements()) {                    JComponent label = (JComponent) elements.nextElement();                    Dimension pref = label.getPreferredSize();                    int labelBaseline = label.getBaseline(pref.width,                                                          pref.height);                    if (labelBaseline >= 0) {                        if (baseline == -1) {                            baseline = labelBaseline;                        }                        else if (baseline != labelBaseline) {                            sameLabelBaselines = false;                            break;                        }                    }                    else {                        sameLabelBaselines = false;                        break;                    }                }            }            else {                sameLabelBaselines = false;            }        }        return sameLabelBaselines;    }     public Dimension getPreferredHorizontalSize() {        Dimension horizDim = (Dimension)DefaultLookup.get(slider,                this, "Slider.horizontalSize");        if (horizDim == null) {            horizDim = new Dimension(200, 21);        }        return horizDim;    }     public Dimension getPreferredVerticalSize() {        Dimension vertDim = (Dimension)DefaultLookup.get(slider,                this, "Slider.verticalSize");        if (vertDim == null) {            vertDim = new Dimension(21, 200);        }        return vertDim;    }     public Dimension getMinimumHorizontalSize() {        Dimension minHorizDim = (Dimension)DefaultLookup.get(slider,                this, "Slider.minimumHorizontalSize");        if (minHorizDim == null) {            minHorizDim = new Dimension(36, 21);        }        return minHorizDim;    }     public Dimension getMinimumVerticalSize() {        Dimension minVertDim = (Dimension)DefaultLookup.get(slider,                this, "Slider.minimumVerticalSize");        if (minVertDim == null) {            minVertDim = new Dimension(21, 36);        }        return minVertDim;    }     public Dimension getPreferredSize(JComponent c)    {        recalculateIfInsetsChanged();        Dimension d;        if ( slider.getOrientation() == JSlider.VERTICAL ) {            d = new Dimension(getPreferredVerticalSize());            d.width = insetCache.left + insetCache.right;            d.width += focusInsets.left + focusInsets.right;            d.width += trackRect.width + tickRect.width + labelRect.width;        }        else {            d = new Dimension(getPreferredHorizontalSize());            d.height = insetCache.top + insetCache.bottom;            d.height += focusInsets.top + focusInsets.bottom;            d.height += trackRect.height + tickRect.height + labelRect.height;        }         return d;    }     public Dimension getMinimumSize(JComponent c)  {        recalculateIfInsetsChanged();        Dimension d;         if ( slider.getOrientation() == JSlider.VERTICAL ) {            d = new Dimension(getMinimumVerticalSize());            d.width = insetCache.left + insetCache.right;            d.width += focusInsets.left + focusInsets.right;            d.width += trackRect.width + tickRect.width + labelRect.width;        }        else {            d = new Dimension(getMinimumHorizontalSize());            d.height = insetCache.top + insetCache.bottom;            d.height += focusInsets.top + focusInsets.bottom;

Lines 1–500 of 2025.