The class makes it easy to select a numerical value, possibly from a given range : Panel « Swing Components « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Swing Components » Panel 




The class makes it easy to select a numerical value, possibly from a given range
        
//package com.ryanm.util.swing;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.BoundedRangeModel;
import javax.swing.BoxLayout;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * The class makes it easy to select a numerical value, possibly from a given
 * range
 
 @author ryanm
 */
public class FloatChooser extends JPanel implements ChangeListener
{
  /**
   * The size of steps in the spinner to aim for. What you get will depend on
   * the range.
   */
  private float stepSize = 0.1f;

  /**
   * The number of steps in the slider to aim for. What you get will depend on
   * the range.
   */
  private static final int SCALE = 10000;

  private static final float MAX_VELOCITY = 5;

  private List<Listener> listeners = new LinkedList<Listener>();

  private JSlider slider = new JSlider();

  private SpinnerNumberModel snm;

  private JSpinner spinner = new JSpinner();

  private boolean absolute = false;

  private Timer timer = new Timer50new ActionListener() {
    @Override
    public void actionPerformedActionEvent e )
    {
      ife.getSource() == timer )
      {
        // set the value
        ifvelocity != )
        {
          setValuegetValue() + velocity );
        }
      }
    }
  } );

  private float velocity = 0;

  private float oldValue;

  private boolean integer = false;

  private RangeEditor rangeEditor = new RangeEditor();

  private float[] range = new float[] { Float.NaN, Float.NaN };

  /**
   * Controls the unbounded slider operation
   */
  private MouseListener sliderListener = new MouseAdapter() {
    @Override
    public void mousePressedMouseEvent e )
    {
      // start the Timertask
      timer.start();
    }

    @Override
    public void mouseReleasedMouseEvent e )
    {
      // end the timertask
      timer.stop();

      slider.getModel().setValueSCALE / );
    }
  };

  private MouseListener rangeAdjustListener = new MouseAdapter() {
    @Override
    public void mouseReleasedMouseEvent e )
    {
      ife.isPopupTrigger() && e.isShiftDown() )
      {
        showRangeAdjuster();
      }
    }

    @Override
    public void mouseClickedMouseEvent e )
    {
      ife.isPopupTrigger() && e.isShiftDown() )
      {
        showRangeAdjuster();
      }
    }

    @Override
    public void mousePressedMouseEvent e )
    {
      ife.isPopupTrigger() && e.isShiftDown() )
      {
        showRangeAdjuster();
      }
    }

    private void showRangeAdjuster()
    {
      rangeEditor.lower.setTextsnm.getMinimum() == null "None" : snm
          .getMinimum().toString() );
      rangeEditor.upper.setTextsnm.getMaximum() == null "None" : snm
          .getMaximum().toString() );

      rangeEditor.setLocationRelativeToFloatChooser.this );
      rangeEditor.setVisibletrue );
    }
  };

  /**
   * Constructs a new FloatChooser
   
   @param min
   *           The minimum value, or null for no minimum
   @param max
   *           The maximum value, or null for no maximum
   @param value
   *           The current value
   */
  public FloatChooserFloat min, Float max, float value )
  {
    thismin, max, value, false );
  }

  /**
   * Constructs a new FloatChooser
   
   @param min
   *           The minimum vlaue, or null for no minimum
   @param max
   *           The maximum value, or null for no maximum
   @param value
   *           The current value
   @param integer
   *           If <code>true</code>, values will be rounded to the nearest
   *           integer, and the velocity slider will be scaled linearly
   */
  public FloatChooserFloat min, Float max, float value, boolean integer )
  {
    setLayoutnew BoxLayoutthis, BoxLayout.Y_AXIS ) );
    oldValue = value;

    addspinner );
    spinner.addChangeListenerthis );
    addslider );
    slider.addChangeListenerthis );

    this.integer = integer;

    setRangemin, max );

    JSpinner.NumberEditor ne = new JSpinner.NumberEditorspinner, "0.#####" );
    spinner.setEditorne );

    slider.setPreferredSizenew Dimension120,
        slider.getPreferredSize().height ) );
  }

  /**
   * Gets the listener that will trigger the range adjust dialog. Apply it to
   * what you want sensitised
   
   @return The range adjust dialog trigger
   */
  public MouseListener getRangeAdjustListener()
  {
    return rangeAdjustListener;
  }

  /**
   * Sets the range of possible values
   
   @param min
   *           The minimum possible value, or {@link Float}.NaN for no minimum
   *           limit
   @param max
   *           The maximum possible value, or {@link Float}.NaN for no maximum
   *           limit
   */
  public void setRangefloat min, float max )
  {
    setRangeFloat.isNaNmin null new Floatmin ),
        Float.isNaNmax null new Floatmax ) );
  }

  /**
   * Sets the range of possible values
   
   @param min
   *           The minimum possible value, or null for no minimum limit
   @param max
   *           The maximum possible value, or null for no maximum limit
   */
  public void setRangeFloat min, Float max )
  {
    range= min != null ? min.floatValue() : Float.NaN;
    range= max != null ? max.floatValue() : Float.NaN;

    slider.removeChangeListenerthis );

    // get the limits

    snm = new SpinnerNumberModel();
    snm.setMinimummin );
    snm.setMaximummax );

    snm.setValuenew FloatoldValue ) );
    spinner.setModelsnm );

    BoundedRangeModel brm = new DefaultBoundedRangeModel();

    ifmin != null && max != null )
    // put the slider into absolute mode
      absolute = true;

      snm.setStepSizenew FloatstepSize ) );

      // build the slider
      brm.setMinimum( ( int ) ( min.floatValue() * SCALE ) );
      brm.setMaximum( ( int ) ( max.floatValue() * SCALE ) );
      brm.setValue( ( int ) ( oldValue * SCALE ) );

      slider.removeMouseListenersliderListener );
    }
    else
    // put the slider into velocity mode
      absolute = false;

      brm.setMinimum);
      brm.setMaximumSCALE );
      brm.setValueSCALE / );

      slider.addMouseListenersliderListener );
    }

    slider.setPaintTrackabsolute );
    slider.setModelbrm );
    slider.addChangeListenerthis );
    validate();

    synchronizedlisteners )
    {
      forListener l : listeners )
      {
        l.rangeChangedmin == null ? Float.NaN : min.floatValue(),
            max == null ? Float.NaN : max.floatValue() );
      }
    }
  }

  /**
   * Gets the currently set range
   
   @return an {min,max} array, where {@link Float#NaN} signifies no limit
   */
  public float[] getRange()
  {
    return range;
  }

  /**
   * Gets the minimum value possible in this FloatChooser
   
   @return the minimum value possible, or null if there is no lower limit
   */
  public Float getMinValue()
  {
    SpinnerNumberModel snm = SpinnerNumberModel spinner.getModel();

    return Float snm.getMinimum();
  }

  /**
   * Gets the maximum value possible in this FloatChooser
   
   @return the maximum value possible, or null if there is no upper limit
   */
  public Float getMaxValue()
  {
    SpinnerNumberModel snm = SpinnerNumberModel spinner.getModel();

    return Float snm.getMaximum();
  }

  /**
   * Gets the current value
   
   @return The current value
   */
  public float getValue()
  {
    return ( ( Number spinner.getValue() ).floatValue();
  }

  /**
   * Sets the current value. If the supplied value is outside of the current
   * range, the closest legal value will be set. Listeners will be notified
   
   @param value
   *           The value to set.
   */
  public void setValuefloat value )
  {
    ifinteger )
    {
      value = Math.roundvalue );
    }

    ifgetMinValue() != null )
    {
      value = Math.maxgetMinValue().floatValue(), value );
    }
    ifgetMaxValue() != null )
    {
      value = Math.mingetMaxValue().floatValue(), value );
    }

    ifvalue != oldValue )
    {
      oldValue = value;
      spinner.setValuenew Floatvalue ) );

      ifabsolute )
      {
        slider.setValue( ( int ) ( SCALE * value ) );
      }

      synchronizedlisteners )
      {
        forListener listener : listeners )
        {
          listener.valueChangedvalue );
        }
      }
    }
  }

  /**
   * Sets the step size for the spinner's up and down buttons
   
   @param stepSize
   *           The new step size
   */
  public void setSpinnerStepSizefloat stepSize )
  {
    this.stepSize = stepSize;

    ( ( SpinnerNumberModel spinner.getModel() ).setStepSizenew Float(
        stepSize ) );
  }

  /**
   * Gets the step size for the spinner's up and down buttons
   
   @return The current step size
   */
  public float getSpinnerStepSize()
  {
    return stepSize;
  }

  @Override
  public void setEnabledboolean enabled )
  {
    spinner.setEnabledenabled );
    ifslider != null )
    {
      slider.setEnabledenabled );
    }
  }

  @Override
  public boolean isEnabled()
  {
    return spinner.isEnabled();
  }

  /**
   * Adds a {@link Listener} to this FloatChooser. The {@link Listener} will be
   * appraised of any changes to the selected value
   
   @param listener
   *           The {@link Listener} to add
   */
  public void addListenerListener listener )
  {
    synchronizedlisteners )
    {
      listeners.addlistener );
    }
  }

  /**
   * Removes a {@link Listener} from this FloatChooser. The {@link Listener}
   * will no longer be appraised of changes to the selected value
   
   @param listener
   *           The {@link Listener} to remove
   */
  public void removeListenerListener listener )
  {
    synchronizedlisteners )
    {
      listeners.removelistener );
    }
  }

  @Override
  public void stateChangedChangeEvent e )
  {
    Float value = null;
    ife.getSource() == spinner )
    {
      value = Float spinner.getValue();
    }
    else ife.getSource() == slider )
    {
      ifabsolute )
      {
        value = new Float( ( float slider.getValue() / SCALE );
      }
      else
      {
        // change the velocity
        float fraction = ( ( float slider.getValue() - SCALE / )
            SCALE / );

        if!integer )
        {
          fraction = float Math.powfraction, );
        }

        velocity = fraction * MAX_VELOCITY;

        ifvelocity == )
        {
          timer.stop();
        }
        else
        {
          timer.start();
        }
      }
    }

    ifvalue != null )
    {
      setValuevalue.floatValue() );
    }
  }

  /**
   * Interface for keeping track of the state of this widget
   
   @author ryanm
   */
  public interface Listener
  {
    /**
     * Called when the value of the widget is changed, either by the user or
     * via code
     
     @param value
     *           the new value
     */
    public void valueChangedfloat value );

    /**
     * Called when the valid range is changed, either by the user or via code
     
     @param low
     *           the new lower bound, or {@link Float#NaN} for no bound
     @param high
     *           the new upper bound, or {@link Float#NaN} for no bound
     */
    public void rangeChangedfloat low, float high );
  }

  private class RangeEditor extends JDialog
  {
    private JTextField lower = new JTextField16 );

    private JTextField upper = new JTextField16 );

    private JButton yes = new JButton"OK" );

    private JButton no = new JButton"Cancel" );

    private RangeEditor()
    {
      setTitle"Valid Range" );
      setModaltrue );

      setResizablefalse );

      lower.setBordernew TitledBorder"Lower bound" ) );
      lower.setHorizontalAlignmentSwingConstants.CENTER );
      upper.setBordernew TitledBorder"Upper bound" ) );
      upper.setHorizontalAlignmentSwingConstants.CENTER );

      no.setMnemonic'C' );
      getRootPane().setDefaultButtonyes );

      JPanel bp = new JPanel();
      bp.setLayoutnew FlowLayoutFlowLayout.RIGHT ) );
      bp.addno );
      bp.addyes );

      no.addActionListenernew ActionListener() {
        @Override
        public void actionPerformedActionEvent e )
        {
          setVisiblefalse );
        }
      } );

      yes.addActionListenernew ActionListener() {

        @Override
        public void actionPerformedActionEvent e )
        {
          Float low = null;
          try
          {
            low = new Floatlower.getText() );
          }
          catchNumberFormatException nfe )
          {
          }
          Float high = null;
          try
          {
            high = new Floatupper.getText() );
          }
          catchNumberFormatException nfe )
          {
          }

          ifinteger )
          {
            iflow != null )
            {
              low = new Floatlow.intValue() );
            }
            ifhigh != null )
            {
              high = new Floathigh.intValue() );
            }
          }

          setRangelow, high );

          setVisiblefalse );
        }
      } );

      getContentPane().setLayout(
          new BoxLayoutgetContentPane(), BoxLayout.Y_AXIS ) );

      addlower );
      addupper );
      addbp );

      pack();
    }
  }

}

   
    
    
    
    
    
    
    
  














Related examples in the same category
1.Yes / No Panel
2.Transparent PanelTransparent Panel
3.Swing Panel GroupSwing Panel Group
4.Swing Panel Group 2Swing Panel Group 2
5.Gradient Panel
6.Transfer focus from button to button with help of arrows keys.Transfer focus from button to button with help of arrows keys.
7.A JPanel with a textured background.
8.Time panel shows the current time.
9.Graph Canvas
10.A basic panel that displays a small up or down arrow.
11.HeatMap is a JPanel that displays a 2-dimensional array of data using a selected color gradient scheme.
12.GradientPanel is a class with a gradient background.
13.A simple JPanel with a border and a title
14.Translucent PanelTranslucent Panel
15.Image Panel
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.