本文介绍了多个 JSlider - 识别变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以添加更改侦听器并在创建新 JSlider 时对其进行定义吗?

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

我需要创建和添加 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.

本质上:我没有命名 JSlider,但需要一种方法来识别哪个已被更改.

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

具体来说,假设我有一个 JSlider 代表最小值,一个 JSlider 代表最大值.我需要使用它来表示一系列数字,比如客户 ID,稍后将显示.

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.

推荐答案

如果您的滑块定义在范围之外(即事件侦听器无法引用变量),那么您可以为滑块提供名称",您可以查找和比较

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
        }
    }
}

但是,如果您将 JSlider 定义为类级别字段,则可以将事件源的引用与定义的滑块进行比较...

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
    }
});

这篇关于多个 JSlider - 识别变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 17:17