java 如何在滑块移动时调用动作侦听器,而不仅仅是在松开鼠标时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4369077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:04:19  来源:igfitidea点击:

How do I call an actionlistener while the slider is moving, not just when I let go of the mouse?

javaswing

提问by user525479

class AngleSlider implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();
        if (!source.getValueIsAdjusting()) {

            double dAngle = (double)source.getValue();
            pnlCannon.dCannonAngle=Math.toRadians(dAngle);
            pnlCannon.repaint();

        }
    }
}

This is our current event listener. Is there a different listener required to do what I want?

这是我们当前的事件监听器。是否需要不同的听众来做我想做的事?

回答by dacwe

No, you will only need to removethe getValueIsAdjusting()check. So, this will repaint your cannon when you move your mouse:

不,你只需要删除getValueIsAdjusting()检查。因此,当您移动鼠标时,这将重新绘制您的大炮:

class AngleSlider implements ChangeListener {
    public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider) e.getSource();

        double dAngle = (double)source.getValue();
        pnlCannon.dCannonAngle=Math.toRadians(dAngle);
        pnlCannon.repaint();
    }
}

This is another example that shows the same, it will print the value of the slider as you move it:

这是另一个显示相同内容的示例,它会在您移动滑块时打印滑块的值:

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");

    JSlider slider = new JSlider();

    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent ce) {
            System.out.println(((JSlider) ce.getSource()).getValue());
        }
    });

    frame.add(slider);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}

回答by MikelRascher

The !source.getValueIsAdjusting()is preventing the update code form executing.

!source.getValueIsAdjusting()是防止在更新代码的形式执行。

Why do you think that condition is necessary?

为什么你认为这个条件是必要的?