Sam
Sam

Reputation: 405

JSlider with close double values

I have a JSlider and I want it to match up with my JFreeChart points, but the issue is that the x-values for my plot has values such as 8.993 and 8.997, so rounding will cause issues. Is there a way I can get my slider to match up with doubles (I know this is a common problem but I can't find the actual solutions), or could someone give me a suggestion on what to do to make a normal JSlider work for my data?

Thank you in advance

Upvotes: 2

Views: 2298

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

It can be done, but it would require that you set the JSlider's label table to translate an int into a double (actually a formatted double String), and you would also need to translate the slider's values to the double value as well. For example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SliderEg {
   public static void main(String[] args) {
      int start = 8990;
      int end = 9000;
      int value = 8995;

      final JSlider slider = new JSlider(start, end, value);
      slider.setPaintLabels(true);
      slider.setPaintTicks(true);
      slider.setMajorTickSpacing(2);
      slider.setMinorTickSpacing(1);
      Dictionary<Integer, JLabel> labels = new Hashtable<>();
      for (int i = start; i <= end; i += 2) {
         String text = String.format("%4.3f", i / 1000.0);
         labels.put(i, new JLabel(text));
      }

      slider.setLabelTable(labels);
      JPanel panel = new JPanel(new BorderLayout());
      panel.setPreferredSize(new Dimension(400, 50));
      panel.add(slider, BorderLayout.PAGE_START);

      slider.addChangeListener(new ChangeListener() {

         @Override
         public void stateChanged(ChangeEvent e) {
            int value = slider.getValue();
            double sliderValue = value / 1000.0;
            System.out.printf("Slider Value: %4.3f%n", sliderValue);
         }
      });
      JOptionPane.showMessageDialog(null, panel);
   }
}

Upvotes: 4

Related Questions