Miles
Miles

Reputation: 2527

JSlider alternative

I have just realised that JSlider cannot deal with floating point numbers. Can anybody recommend a Swing/AWT alternative that can?

EDIT: Or a workaround of some description.

Upvotes: 4

Views: 2017

Answers (1)

Edwin Buck
Edwin Buck

Reputation: 70909

Sliders in general deal with ranges of numbers. From a practical implementation, each slider must have two elements:

  1. A starting position.
  2. A finite number of "next" increments.

It is the "finite number" that is causing you the trouble. Without a finite number of increments, the slider cannot fit on a screen. With a finite number of increments, it is impossible to select a float number that lies between two incremental "steps".

In short, it is impossible; so, here's the workaround:

  1. Decide on the range of the "float" side of the input. This could be 0.0f to 10.0f or whatever, it doesn't matter, but you must have a range.
  2. Decide on the smallest increment you wish to support. This could be 0.1f or 0.001f or whatever, it doesn't matter, but you must have an increment.
  3. Create a pair of functions. One that takes the Slider integer value and "maps" them to the float value, and one that takes the float value and "maps" them to a Slider value.

An example, for 5.0f to 10.0f with 0.1f increments:

((10.0f - 5.0f) / 0.1f) + 1 = 51 increments (0 to 50)

updateSlider(float value) {
  if (value > 10.0f) {
    Slider.setValue(50);
  } else if (value < 5.0f) {
    Slider.setValue(0);
  } else {
    Slider.setValue((int)Math.round((value - 5.0f)/0.1f));
  }
}

float updateFloat(Slider slider) {
  int value = slider.getValue();
  return 5.0f + (slider.getValue() * 0.1f);
}

Upvotes: 7

Related Questions