001package jmri.jmrit.symbolicprog;
002
003import javax.swing.BoundedRangeModel;
004import javax.swing.DefaultBoundedRangeModel;
005import javax.swing.JSlider;
006import javax.swing.JTextField;
007import javax.swing.event.ChangeEvent;
008import javax.swing.event.ChangeListener;
009import org.slf4j.Logger;
010import org.slf4j.LoggerFactory;
011
012/* Extends a JSlider so that its color & value are consistent with
013 * an underlying variable; we return one of these in DecValVariable.getNewRep.
014 *
015 * @author   Bob Jacobsen   Copyright (C) 2001
016 */
017public class DecVarSlider extends JSlider implements ChangeListener {
018
019    DecVarSlider(DecVariableValue var, int min, int max) {
020        super(new DefaultBoundedRangeModel(min, 0, min, max));
021        _var = var;
022
023        this.getAccessibleContext().setAccessibleName(_var.label());
024
025        // get the original color right
026        setBackground(_var.getColor());
027        if (_var.getColor() == _var.getDefaultColor()) {
028            setOpaque(false);
029        } else {
030            setOpaque(true);
031        }
032        // set the original value
033        setValue(Integer.parseInt(_var.getValueString()));
034        // listen for changes here
035        addChangeListener(this);
036        // listen for changes to associated variable
037        _var.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
038            @Override
039            public void propertyChange(java.beans.PropertyChangeEvent e) {
040                originalPropertyChanged(e);
041            }
042        });
043    }
044
045    @Override
046    public void stateChanged(ChangeEvent e) {
047        // called for new values of a slider - set the variable value as needed
048        // e.getSource() points to the JSlider object - find it in the list
049        JSlider j = (JSlider) e.getSource();
050        BoundedRangeModel r = j.getModel();
051
052        _var.setIntValue(r.getValue());
053        _var.setState(AbstractValue.ValueState.EDITED);
054    }
055
056    DecVariableValue _var;
057
058    void originalPropertyChanged(java.beans.PropertyChangeEvent e) {
059        if (log.isDebugEnabled()) {
060            log.debug("VarSlider saw property change: {}", e);
061        }
062        // update this color from original state
063        if (e.getPropertyName().equals("State")) {
064            setBackground(_var.getColor());
065            if (_var.getColor() == _var.getDefaultColor()) {
066                setOpaque(false);
067            } else {
068                setOpaque(true);
069            }
070        }
071        if (e.getPropertyName().equals("Value")) {
072            int newValue = Integer.parseInt(((JTextField) _var.getCommonRep()).getText());
073            setValue(newValue);
074        }
075    }
076
077    // initialize logging
078    private final static Logger log = LoggerFactory.getLogger(DecVarSlider.class);
079
080}