开发者

Dynamic Run Time Java Listeners

I was wondering how would you go about creating dynamically lets say a bunch of JSliders at runtime and adding listeners to each one of those sliders? I've tried doing this by creating an array of JSliders like the bit of code shown 开发者_开发技巧below, but not sure how to go about creating listeners for each one of those sliders built during runtime. Also obviously the below code won't compile correctly this is just the snippit of the important part of description of what I created:

private JSlider slider[] = new JSlider[100];

for(int i=1; i<=numinputed; i++)
{
    slider[i] = new JSlider();
}       

Since I haven't seen any answers to this questions on google felt like asking here on stackoverflow. This is just for learning purposes and hope someone can point me into the right direction thanks :)


You can have a listener class

class SliderChangeListener implements ChangeListener{
    public void stateChanged(ChangeEvent e){
       // use e.getSource() to get the slider instance.
    } 
}

and share an instance of the listener for your sliders.

SliderChangeListener listener = new SliderChangeListener();

for(int i=1; i<=numinputed; i++)
{
    slider[i] = new JSlider();
    slider[i].addChangeListener(listener);
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜