0

I need to use JSlider with getting input live, meaning that it will return an input without pressing any button. I have this piece of code for the slider:

JPanel panel = new JPanel();
            JSlider js = new JSlider(JSlider.VERTICAL, 0, 20, 10);
            js.setMajorTickSpacing(2);
            js.setPaintTicks(true);
            Hashtable labelTable = new Hashtable();
            labelTable.put(new Integer(js.getMinimum()), new JLabel("x0"));
            labelTable.put(new Integer((js.getMinimum() + js.getMaximum()) / 2), new JLabel("x1"));
            labelTable.put(new Integer(js.getMaximum()), new JLabel("x2"));
            js.setLabelTable(labelTable);
            js.setPaintLabels(true);
            panel.add(js);
            int result = JOptionPane.showConfirmDialog(null, panel, "choose size", JOptionPane.YES_OPTION);

Is it even possible to do so? I thought using actionListener but I didn't succeed.

TJR
  • 454
  • 8
  • 24

1 Answers1

3

It's possible, using a ChangeListener, for example

slider.addChangeListener(new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider slider = (JSlider) e.getSource();
        int value = slider.getValue();
        ...
    }
});
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • The problem is that it doesn't update while I change the slider, but only after pressing a button(JOptionPane.YES_OPTION). – TJR Jan 21 '14 at 15:21
  • Then don't use the `JOptionPane` dialog then, just embed the panel in a regular UI. The dialog is blocking until the button is clicked :) – Reimeus Jan 21 '14 at 15:31
  • Sorry, it is my first project, how to do that? – TJR Jan 21 '14 at 15:37
  • Just add the panel to a `JFrame` instead. I suggest going through the [Swing Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/) before going any further :) – Reimeus Jan 21 '14 at 15:42