import java.awt.*;
import java.awt.geom.Rectangle2D;

import javax.swing.*;
import javax.swing.event.*;

public class MVCExample6 extends JComponent {
  
  interface GradientBoxModel {
    void addChangeListener(ChangeListener l);
    void removeChangeListener(ChangeListener l);
    int getValue();
    int getMaximum();
    int getMinimum();
  }
  
  public MVCExample6(GradientBoxModel model) {
    this.model=model;
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        Dimension d=getSize();
        paintImmediately(0,0,d.width,d.height);
      }
    });
  }
  
  protected void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);
    
    Graphics2D g=(Graphics2D)graphics;
    Dimension d=getSize();
    
    int min=model.getMinimum();
    float value=((float)model.getValue()-min)*d.width/(model.getMaximum()-min);
    g.setPaint(new GradientPaint(0,0,Color.BLUE,
                                 value,d.height,Color.BLACK));                                                   
    g.fill(new Rectangle2D.Float(0,0,value,d.height));
    
    g.setPaint(new GradientPaint(value,0,Color.BLACK,
                                 d.width,d.height,Color.RED));                                                                        
    g.fill(new Rectangle2D.Float(value,0,d.width,d.height));
  }
  
  public Dimension getPreferredSize() {
    return new Dimension(100,20);
  }

  private final GradientBoxModel model;
  
  
  public static void main(String[] args) {
    class DefaultGradientBoxModel extends DefaultBoundedRangeModel implements GradientBoxModel {
      public DefaultGradientBoxModel(int value,int extent,int min,int max) {
        super(value,extent,min,max);
      }
    }
    
    DefaultGradientBoxModel model=new DefaultGradientBoxModel(0,1,0,100);
    
    MVCExample6 gradientBox=new MVCExample6(model);
    JSlider slider=new JSlider(model);
    
    JPanel panel=new JPanel();
    panel.add(gradientBox);
    panel.add(slider);
    
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(panel);
    frame.setSize(400,300);
    frame.show();
  }
}