没有从JSlider获得价值

时间:2012-06-22 09:31:00

标签: java swing jslider changelistener

我在我的程序中使用了一个JSlider,并为它实现了一个ChangeListener。

public void stateChanged(ChangeEvent e)
    {
        JSlider source=(JSlider) e.getSource();
        frame_value.setText(Integer.toString(source.getValue()));

        //Condition to change the frame_no only when user has stopped moving the slider
        if (!source.getValueIsAdjusting()) 
        {
            frame_no=(int) source.getValue()-1;
            if(frame_no<0)
                frame_no=0;
        }
        ....
}

发生的事情是,无论何时调用ChangeListener,程序都会跳过if块,然后转到代码。我不明白为什么会这样。我无法从JSlider获得正确的值。请帮忙!!

PS:我不知道是不是这个原因,但最近我设置了JSlider的UI,以便在我点击它的地方放置。我不知道是否应该对此负责。这是代码:

slider.setUI(new MetalSliderUI() {
                protected void scrollDueToClickInTrack(int direction) {
                    int value = HEVC_Analyzer.slider.getValue(); 

                   value = this.valueForXPosition(HEVC_Analyzer.slider.getMousePosition().x);
                   HEVC_Analyzer.slider.setValue(value);
                }
            });

2 个答案:

答案 0 :(得分:5)

您的代码中必定存在错误,因为在此示例中它正常工作:

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SliderChangeEffect extends JFrame
{
    private JSlider slider;
    private int count = 0;
    private ChangeListener changeListener = new ChangeListener()
    {
        public void stateChanged(ChangeEvent ce)
        {
            JSlider slider = (JSlider) ce.getSource();
            if (!slider.getValueIsAdjusting())
                System.out.println(slider.getValue());
        }
    };

    private void createAndDisplayGUI()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        JPanel contentPane = new JPanel();
        contentPane.setOpaque(true);

        slider = new JSlider(0, 10, 5);
        slider.setMajorTickSpacing(2);
        slider.setMinorTickSpacing(1);
        slider.addChangeListener(changeListener);

        contentPane.add(slider);

        getContentPane().add(contentPane);
        pack();
        setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new SliderChangeEffect().createAndDisplayGUI();
            }
        });
    }
}

答案 1 :(得分:0)

只需使用String.valueOf()和event.MouseReleased()。

 private void jSlider1MouseReleased(java.awt.event.MouseEvent evt) {                                       
    // TODO add your handling code here:
    try {

        String valueOf = String.valueOf(jSlider1.getValue());
        jLabel1.setText(valueOf);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}