All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.gephi.ui.components.gradientslider.MultiThumbSlider Maven / Gradle / Ivy

/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian 
Website : http://www.gephi.org

This file is part of Gephi.

DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

Copyright 2011 Gephi Consortium. All rights reserved.

The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License.  When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"

If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.

Contributor(s):

Portions Copyrighted 2011 Gephi Consortium.
*/

package org.gephi.ui.components.gradientslider;

import java.util.List;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.openide.util.Exceptions;

/**
 * This JComponent resembles a JSlider, except there are
 * at least two thumbs.  A JSlider is designed to modify
 * one number within a certain range of values.  By contrast a MultiThumbSlider
 * actually modifies a table of data.  Each thumb in a MultiThumbSlider
 * should be thought of as a key, and it maps to an abstract value.  In the case
 * of the GradientSlider: each value is a java.awt.Color.
 * Other subclasses could come along that map to other abstract objects.  (For example,
 * a VolumeSlider might map each thumb to a specific volume level.  This
 * type of widget would let the user control fading in/out of an audio track.)
 * 

The slider graphically represents the domain from zero to one, so each thumb * is always positioned within that domain. If the user drags * a thumb outside this domain: that thumb disappears. *

There is always a selected thumb in each slider when this slider has the * keyboard focus. The user can press the tab key (or shift-tab) to transfer focus to different * thumbs. Also the arrow keys can be used to control the selected thumb. *

The user can click and drag any thumb to a new location. If a thumb is dragged * so it is less than zero or greater than one: then that thumb is removed. If the user * clicks between two existing thumbs: a new thumb is created if autoAdd is * set to true. (If autoAdd is set to false: nothing happens.) *

There are unimplemented methods in this class: doDoubleClick() and * doPopup(). The UI will invoke these methods as needed; this gives the * user a chance to edit the values represented at a particular point. *

Also using the keyboard: *

    *
  • In a horizontal slider, the user can press modifier+left or modifer+right to insert * a new thumb to the left/right of the currently selected thumb. (Where "modifier" refers * to Toolkit.getDefaultTookit().getMenuShortcutKeyMask(). On Mac this is META, and on Windows * this is CONTROL.) Likewise on a vertical slider the up/down arrow keys can be used to add * thumbs. *
  • The delete/backspace key can be used to remove thumbs. *
  • In a horizontal slider, the down arrow key can be used to invoke doPopup(). * This should invoke a JPopupMenu that is keyboard accessible, so the user should be * able to navigate this component without a mouse. Likewise on a vertical slider the right * arrow key should do the same. *
  • The space bar or return key invokes doDoubleClick(). *
*

Because thumbs can be abstractly inserted, this values each thumb represents should be * tween-able. That is, if there is a value at zero and a value at one, the call * getValue(.5f) must return a value that is halfway between those values. *

Also note that although the thumbs must always be between zero and one: the minimum * and maximum thumbs do not have to be zero and one. The user can adjust them so the * minimum thumb is, say, .2f, and the maximum thumb is .5f. */ //Author Jeremy Wood public abstract class MultiThumbSlider extends JComponent { /** * The property that is changed when setSelectedThumb() is called. */ public static final String SELECTED_THUMB_PROPERTY = "selected thumb"; /** * The property that is changed when setInverted(b) is called. */ public static final String INVERTED_PROPERTY = "inverted"; /** * The property that is changed when setOrientation(i) is called. */ public static final String ORIENTATION_PROPERTY = "orientation"; /** * The property that is changed when setValues() is called. * Note this is used when either the positions or the values are updated, because * they need to be updated at the same time to maintain an exact one-to-one * ratio. */ public static final String VALUES_PROPERTY = "values"; /** * The property that is changed when setValueIsAdjusting(b) is called. */ public static final String ADJUST_PROPERTY = "adjusting"; /** * The property that is changed when setPaintTicks(b) is called. */ public static final String PAINT_TICKS_PROPERTY = "paint ticks"; /** * The orientation constant for a horizontal slider. */ public static final int HORIZONTAL = SwingConstants.HORIZONTAL; /** * The orientation constant for a vertical slider. */ public static final int VERTICAL = SwingConstants.VERTICAL; private static final long serialVersionUID = 1L; /** * The positions of the thumbs */ protected float[] thumbPositions = new float[0]; /** * The values for each thumb */ Object[] values = new Object[0]; /** * Whether thumbs are automatically added when the user clicks * in a space with no existing thumbs */ boolean autoAdd = true; /** * Whether the UI is currently adjusting values. */ boolean adjusting = false; /** * Whether this slider is HORIZONTAL or VERTICAL. */ int orientation; /** * Whether this slider is inverted or not. */ boolean inverted = false; /** * Whether tickmarks should be painted on this slider. */ boolean paintTicks = false; /** * Whether this slider is blocked, no more colors can be added by user. */ boolean blocked = false; /** * ChangeListeners registered with this slider. */ List changeListeners; /** * Creates a new MultiThumbSlider. * * @param orientation must be HORIZONTAL or VERTICAL * @param thumbPositions an array of values from zero to one. * @param values an array of values, each value corresponds to a value in thumbPositions. */ public MultiThumbSlider(int orientation, float[] thumbPositions, Object[] values) { setOrientation(orientation); setValues(thumbPositions, values); setFocusable(true); updateUI(); } /** * @param f an array of floats * @return a string representation of f */ private static String toString(float[] f) { StringBuffer sb = new StringBuffer(); sb.append('['); for (int a = 0; a < f.length; a++) { sb.append(f[a]); if (a != f.length - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); } /** * This listener will be notified when the colors/positions of * this slider are modified. *

Note you can also listen to these events by listening to * the VALUES_PROPERTY, but this mechanism is provided * as a convenience to resemble the JSlider model. * * @param l the ChangeListener to add. */ public void addChangeListener(ChangeListener l) { if (changeListeners == null) { changeListeners = new Vector(); } if (changeListeners.contains(l)) { return; } changeListeners.add(l); } /** * Removes a ChangeListener from this slider. * * @param l the ChangeListener to remove. */ public void removeChangeListener(ChangeListener l) { if (changeListeners == null) { return; } changeListeners.remove(l); } /** * Invokes all the ChangeListeners. */ protected void fireChangeListeners() { if (changeListeners == null) { return; } for (int a = 0; a < changeListeners.size(); a++) { try { ((ChangeListener) changeListeners.get(a)).stateChanged(new ChangeEvent(this)); } catch (Throwable t) { Exceptions.printStackTrace(t); } } } /** * Depending on which thumb is selected, this may shift the focus * to the next available thumb, or it may shift the focus to the * next focusable JComponent. */ @Override public void transferFocus() { transferFocus(true); } /** * Shifts the focus forward or backward. * This may decide to select another thumb, or it may * call super.transferFocus() to let the * next JComponent receive the focus. * * @param forward whether we're shifting forward or backward */ private void transferFocus(boolean forward) { int direction = (forward) ? 1 : -1; //because vertical sliders are technically inverted already: if (orientation == VERTICAL) { direction = direction * -1; } //because inverted sliders are, well, inverted: if (inverted) { direction = direction * -1; } int selectedThumb = getSelectedThumb(); if (direction == 1) { if (selectedThumb != thumbPositions.length - 1) { setSelectedThumb(selectedThumb + 1); return; } } else { if (selectedThumb != 0) { setSelectedThumb(selectedThumb - 1); return; } } if (forward) { super.transferFocus(); } else { super.transferFocusBackward(); } } /** * Depending on which thumb is selected, this may shift the focus * to the previous available thumb, or it may shift the focus to the * previous focusable JComponent. */ @Override public void transferFocusBackward() { transferFocus(false); } /** * This returns a value at a certain position on this slider. *

Subclasses implementing this method should note that * this method cannot return null. If the pos argument * is outside the domain of thumbs, then a value still needs to be * returned. * * @param pos a position between zero and one * @return a value that corresponds to the position pos */ public abstract Object getValue(float pos); /** * Removes a specific thumb * * @param thumbIndex the thumb index to remove. */ public void removeThumb(int thumbIndex) { if (thumbIndex <= 0 || thumbIndex > thumbPositions.length) { throw new IllegalArgumentException("There is not thumb at index " + thumbIndex + " to remove."); } float[] f = new float[thumbPositions.length - 1]; Object[] c = new Object[values.length - 1]; System.arraycopy(thumbPositions, 0, f, 0, thumbIndex); System.arraycopy(values, 0, c, 0, thumbIndex); System.arraycopy(thumbPositions, thumbIndex + 1, f, thumbIndex, f.length - thumbIndex); System.arraycopy(values, thumbIndex + 1, c, thumbIndex, f.length - thumbIndex); setValues(f, c); } /** * An optional method subclasses can override to react to the user's * double-click. When a thumb is double-clicked the user is trying to edit * the value for that thumb. A double-click probably * suggests the user wants a detailed set of controls to edit a value, such * as a dialog. *

Note this method will be called with arguments (-1,-1) if * the space bar or return key is pressed. *

By default this method does nothing, and returns false *

Note the (x,y) information passed to this method is only provided so * subclasses can position components (such as a JPopupMenu). It can be * assumed for a double-click event that the user has selected a thumb * (since one click will click/create a thumb) and intends to edit the currently * selected thumb. * * @param x the x-value of the mouse click location * @param y the y-value of the mouse click location * @return true if this event was consumed, or acted upon. * false if this is unimplemented. */ public boolean doDoubleClick(int x, int y) { return false; } /** * An optional method subclasses can override to react to the user's * request for a contextual menu. When a thumb is right-clicked the * user is trying to edit the value for that thumb. A right-click probably * suggests the user wants very quick, simple options to adjust a thumb. *

By default this method does nothing, and returns false * * @param x the x-value of the mouse click location * @param y the y-value of the mouse click location * @return true if this event was consumed, or acted upon. * false if this is unimplemented. */ public boolean doPopup(int x, int y) { return false; } /** * Tells if tick marks are to be painted. * * @return whether ticks should be painted on this slider. */ public boolean isPaintTicks() { return paintTicks; } /** * Turns on/off the painted tick marks for this slider. *

This triggers a PropertyChangeEvent for * PAINT_TICKS_PROPERTY. * * @param b whether tick marks should be painted */ public void setPaintTicks(boolean b) { if (b == paintTicks) { return; } paintTicks = b; firePropertyChange(PAINT_TICKS_PROPERTY, new Boolean(!b), new Boolean(b)); } /** * Returns true if the slider is blocked. No more colors can be added by user. * * @return true if blocked */ public boolean isBlocked() { return blocked; } /** * Enable/Disable adding new colors by user * * @param blocked whether the user can add new colors */ public void setBlocked(boolean blocked) { this.blocked = blocked; } /** * This inserts a thumb at a position indicated. *

This method relies on the abstract getValue(float) to * determine what value to put at the new thumb location. * * @param pos the new thumb position * @return the index of the newly created thumb */ public int addThumb(float pos) { if (pos < 0 || pos > 1) { throw new IllegalArgumentException("the new position (" + pos + ") must be between zero and one"); } Object newValue = getValue(pos); float[] f = new float[thumbPositions.length + 1]; Object[] c = new Object[values.length + 1]; int newIndex = -1; if (pos < thumbPositions[0]) { System.arraycopy(thumbPositions, 0, f, 1, thumbPositions.length); System.arraycopy(values, 0, c, 1, values.length); newIndex = 0; f[0] = pos; c[0] = newValue; } else if (pos > thumbPositions[thumbPositions.length - 1]) { System.arraycopy(thumbPositions, 0, f, 0, thumbPositions.length); System.arraycopy(values, 0, c, 0, values.length); newIndex = f.length - 1; f[f.length - 1] = pos; c[c.length - 1] = newValue; } else { boolean addedYet = false; for (int a = 0; a < f.length; a++) { if (addedYet == false && thumbPositions[a] < pos) { f[a] = thumbPositions[a]; c[a] = values[a]; } else { if (addedYet == false) { c[a] = newValue; f[a] = pos; addedYet = true; newIndex = a; } else { f[a] = thumbPositions[a - 1]; c[a] = values[a - 1]; } } } } setValues(f, c); return newIndex; } /** * This is used to notify other objects when the user is in the process * of adjusting values in this slider. *

A listener may not want to act on certain changes until this property * is false if it is expensive to process certain changes. * *

This triggers a PropertyChangeEvent for * ADJUST_PROPERTY. * * @param b value */ public void setValueIsAdjusting(boolean b) { if (b == adjusting) { return; } adjusting = b; firePropertyChange(ADJUST_PROPERTY, new Boolean(!b), new Boolean(b)); } /** * true if the user is current modifying this component. * * @return the value of the adjusting property */ public boolean isValueAdjusting() { return adjusting; } /** * The thumb positions for this slider. *

There is a one-to-one correspondence between this array and the * getValues() array. *

This array is always sorted in ascending order. * * @return an array of the positions of thumbs. */ public float[] getThumbPositions() { float[] f = new float[thumbPositions.length]; System.arraycopy(thumbPositions, 0, f, 0, f.length); return f; } /** * The values for thumbs for this slider. *

There is a one-to-one correspondence between this array and the * getThumbPositions() array. * * @return an array of the values associated with each thumb. */ public Object[] getValues() { Object[] c = new Object[values.length]; System.arraycopy(values, 0, c, 0, c.length); return c; } /** * This assigns new positions/values for the thumbs in this slider. * The two must be assigned at exactly the same time, so there is * always the same number of thumbs/sliders. * *

This triggers a PropertyChangeEvent for * VALUES_PROPERTY, and possibly for the * SELECTED_THUMB_PROPERTY if that had to be adjusted, too. * * @param thumbPositions an array of the new position of each thumb * @param values an array of the value associated with each thumb * @throws IllegalArgumentException if the size of the arrays are different, * or if the thumbPositions array is not sorted in ascending order. */ public void setValues(float[] thumbPositions, Object[] values) { if (values.length != thumbPositions.length) { throw new IllegalArgumentException( "there number of positions (" + thumbPositions.length + ") must equal the number of values (" + values.length + ")"); } for (int a = 0; a < values.length; a++) { if (values[a] == null) { throw new NullPointerException(); } if (a > 0 && thumbPositions[a] < thumbPositions[a - 1]) { throw new IllegalArgumentException( "the thumb positions must be ascending order (" + toString(thumbPositions) + ")"); } if (thumbPositions[a] < 0 || thumbPositions[a] > 1) { throw new IllegalArgumentException( "illegal thumb value " + thumbPositions[a] + " (must be between zero and one)"); } } //don't clone arrays and fire off events if //there really is no change here: if (thumbPositions.length == this.thumbPositions.length) { boolean equal = true; for (int a = 0; a < thumbPositions.length && equal; a++) { if (thumbPositions[a] != this.thumbPositions[a]) { equal = false; } } for (int a = 0; a < values.length && equal; a++) { if (!values[a].equals(this.values[a])) { equal = false; } } if (equal) { return; //no change! go home. } } this.thumbPositions = new float[thumbPositions.length]; System.arraycopy(thumbPositions, 0, this.thumbPositions, 0, thumbPositions.length); this.values = new Object[values.length]; System.arraycopy(values, 0, this.values, 0, values.length); int oldThumb = getSelectedThumb(); int newThumb = oldThumb; if (newThumb >= thumbPositions.length) { newThumb = thumbPositions.length - 1; } firePropertyChange(VALUES_PROPERTY, null, values); if (oldThumb != newThumb) { setSelectedThumb(newThumb); } fireChangeListeners(); } /** * The number of thumbs in this slider. * * @return the number of thumbs. */ public int getThumbCount() { return thumbPositions.length; } /** * Returns the selected thumb index, or -1 if this component doesn't have * the keyboard focus. * * @return the selected thumb index */ public int getSelectedThumb() { return getSelectedThumb(true); } /** * Assigns the currently selected thumb. A value of -1 indicates * that no thumb is currently selected. *

A slider should always have a selected thumb if it has the keyboard focus, though, * so be careful when you modify this. *

This triggers a PropertyChangeEvent for * SELECTED_THUMB_PROPERTY. * * @param index the new selected thumb */ public void setSelectedThumb(int index) { putClientProperty(SELECTED_THUMB_PROPERTY, new Integer(index)); } /** * Returns the currently selected thumb index. *

Note this might be -1, indicating that there is no selected thumb. * *

It is recommend you use the getSelectedThumb() method * most of the time. This method is made public so UI's can provide * a better user experience as this component gains and loses focus. * * @param ignoreIfUnfocused if this component doesn't have focus and this * is true, then this returns -1. If this is false * then this returns the internal value used to store the selected index, but * the user may not realize this thumb is "selected". * @return the selected thumb */ public int getSelectedThumb(boolean ignoreIfUnfocused) { if (hasFocus() == false && ignoreIfUnfocused) { return -1; } Integer i = (Integer) getClientProperty(SELECTED_THUMB_PROPERTY); if (i == null) { return -1; } return i.intValue(); } /** * Whether thumbs are automatically added when the * user clicks in a space that doesn't already have a thumb. * * @return true if auto adding */ public boolean isAutoAdding() { return autoAdd; } /** * Controls whether thumbs are automatically added when the * user clicks in a space that doesn't already have a thumb. * * @param b whether auto adding is active or not */ public void setAutoAdding(boolean b) { autoAdd = b; } /** * The orientation of this slider. * * @return HORIZONTAL or VERTICAL */ public int getOrientation() { return orientation; } /** * Reassign the orientation of this slider. * * @param i must be HORIZONTAL or VERTICAL */ public void setOrientation(int i) { if (!(i == SwingConstants.HORIZONTAL || i == SwingConstants.VERTICAL)) { throw new IllegalArgumentException("the orientation must be HORIZONTAL or VERTICAL"); } if (orientation == i) { return; } int oldValue = orientation; orientation = i; firePropertyChange(ORIENTATION_PROPERTY, new Integer(oldValue), new Integer(i)); } /** * Whether this slider is inverted or not. * * @return true if inverted */ public boolean isInverted() { return inverted; } /** * Assigns whether this slider is inverted or not. * *

This triggers a PropertyChangeEvent for * INVERTED_PROPERTY. * * @param b value */ public void setInverted(boolean b) { if (inverted == b) { return; } inverted = b; firePropertyChange(INVERTED_PROPERTY, new Boolean(!b), new Boolean(b)); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy