问题
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.
回答1:
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
}
});
来源:https://stackoverflow.com/questions/15513195/multiple-jsliders-identifying-changes