0

Am I able to add a change listener and define it on creation of a new JSlider?

The order in which I need to create and add JSliders means I can't define them beforehand, so I don't really have a way to store them beforehand.

Essentially: I don't have named JSliders, but need a way to identify which one has been altered.

Will add to this with some example code later if it's not too clear what I am questioning about

EDIT:

Specifically, imagine I have one JSlider to represent a minimum value, and one JSlider to represent a maximum value. I need to use this to represent a range of numbers, lets say customer IDs, that will be displayed later on.

user1079404
  • 308
  • 1
  • 5
  • 15
  • [getSource()](http://docs.oracle.com/javase/6/docs/api/java/util/EventObject.html#getSource()) Should help explain. –  Mar 20 '13 at 00:46

1 Answers1

4

If your sliders are defined out of scope (ie the event listener has no way to reference the variable), then you can supply the slider with a "name", which you can look up and compare

JSlider slider = new JSlider();
slider.setName("funky");

//...//

public void stateChanged(ChangeEvent e) {
    Object source = e.getSource();
    if (source instanceof JSlider) {
        JSlider slider = (JSlider)source;
        String name = slider.getName();
        if ("funky".equals(name)) {
            // Do funky stuff
        }
    }
}

However, if you define you JSlider as class level field, you can compare the reference of the event source to the defined slider...

private JSlider slider;

//...//

slider = new JSlider();
slider.setName("funky");

//...//

public void stateChanged(ChangeEvent e) {
    if (slider == e.getSource()) {
        // Do funky stuff
    }
}

Realistically, if you can, you should be giving each slider it's own listener and dealing with it directly from the source...

JSlider slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        JSlider slider= (Slider)e.getSource();
        // Do funky stuff
    }
});
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Yes, I do believe this last suggestion is exactly what I was looking for. Being able to give each slider it's own listener like that should probably work better than what I was attempting to do for a fix. I will reply back with my success tomorrow when I have implemented this – user1079404 Mar 20 '13 at 01:41
  • 1
    +1 for separate listeners, which may make preserving `max > min` easier. Also consider a [range slider](http://ernienotes.wordpress.com/2010/12/27/creating-a-java-swing-range-slider/). – trashgod Mar 20 '13 at 01:58