get JSlider's input and changes

偶尔善良 提交于 2019-12-02 19:25:21

问题


I need to use JSlider with getting input live, meaning that it will return an input without pressing any button. I have this piece of code for the slider:

JPanel panel = new JPanel();
            JSlider js = new JSlider(JSlider.VERTICAL, 0, 20, 10);
            js.setMajorTickSpacing(2);
            js.setPaintTicks(true);
            Hashtable labelTable = new Hashtable();
            labelTable.put(new Integer(js.getMinimum()), new JLabel("x0"));
            labelTable.put(new Integer((js.getMinimum() + js.getMaximum()) / 2), new JLabel("x1"));
            labelTable.put(new Integer(js.getMaximum()), new JLabel("x2"));
            js.setLabelTable(labelTable);
            js.setPaintLabels(true);
            panel.add(js);
            int result = JOptionPane.showConfirmDialog(null, panel, "choose size", JOptionPane.YES_OPTION);

Is it even possible to do so? I thought using actionListener but I didn't succeed.


回答1:


It's possible, using a ChangeListener, for example

slider.addChangeListener(new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider slider = (JSlider) e.getSource();
        int value = slider.getValue();
        ...
    }
});


来源:https://stackoverflow.com/questions/21261506/get-jsliders-input-and-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!