// EditableSlider.java
// $Id: EditableSlider.java,v 1.4 1999/03/05 14:48:01 bmahe Exp $
// (c) COPYRIGHT MIT, INRIA and Keio, 1999.
// Please first read the full copyright statement in file COPYRIGHT.html
 
package org.w3c.jigadmin.widgets;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JSlider;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;

/**
 * A JSlider associated to an IntegerTextField
 * @version $Revision: 1.4 $
 * @author  Benoît Mahé (bmahe@w3.org)
 * @see org.w3c.jigadmin.widgets.IntegerTextField
 */
public class EditableSlider extends JPanel {

    ChangeListener cl = new ChangeListener() {
	public void stateChanged(ChangeEvent e) {
	    if (e.getSource() == slider) {
		String newvalue = String.valueOf(slider.getValue());
		if (! newvalue.equals(textfield.getText()))
		    textfield.setText(newvalue);
	    }
	}
    };

    DocumentListener dl = new DocumentListener() {
	private void update() {
	    try {
		int newvalue = Integer.parseInt(textfield.getText());
		if ((newvalue <= slider.getMaximum()) && 
		    (newvalue >= slider.getMinimum()))
		    slider.setValue(newvalue);
	    } catch (NumberFormatException ex) {
		//nothing
	    }
	}

	public void insertUpdate(DocumentEvent e) {
	    update();
	}

	public void changedUpdate(DocumentEvent e) {
	    update();
	}

	public void removeUpdate(DocumentEvent e) {
	    update();
	}
    };

    protected JSlider          slider    = null;
    protected IntegerTextField textfield = null;

    public int getValue() {
	return slider.getValue();
    }

    public void setValue(int value) {
	slider.setValue(value);
    }

    public JSlider getSlider() {
	return slider;
    }

    public EditableSlider(int min, int max, int step, int value) {
	super(new FlowLayout());

	slider = new JSlider(min, max, value);
	slider.setMajorTickSpacing(step);
	slider.setPaintLabels(true);
	slider.setPaintTicks(true);
	slider.setPaintTrack(true);
	slider.setSnapToTicks(false);
	
	textfield = new IntegerTextField(8);
	textfield.setText(String.valueOf(value));
	textfield.setBorder(BorderFactory.createLoweredBevelBorder());
	
	slider.addChangeListener(cl);
	textfield.getDocument().addDocumentListener(dl);

	add(textfield, BorderLayout.WEST);
	add(slider, BorderLayout.CENTER);
    }
    
}
