CS 151 Lecture 11

Cover page image

Cay S. Horstmann

Lab

Sliders

  1. Put this SliderDemo.java file into your lab11 directory and make a project in that directory. Run the program
  2. A slider is a user interface component that allows a user to specify a continuum of values. To be notified of slider movement, you need to attach a class that implements the ChangeListener interface type. Read the API documentation for JSlider and ChangeListener. Make a table of pattern names and actual names that shows how this is a manifestation of the observer pattern.

Not a Pattern Match

  1. Someone tells you that an Iterator is actually an observer that notifies you whenever the next value is available. Is it? Why or why not?
  2. Someone tells you that a ChangeListener is actually an iterator through a sequence of JSlider values. Show why the Iterator pattern doesn't apply.
  3. Let's make a SliderIterator that actually iterates over the slider values. Make it so that when the slider value changes, the slider value is inserted to a queue. The next method takes the next value (blocking if the queue is empty).
    public class SliderIterator implements Iterator<Integer>
    {
       public SliderIterator(JSlider slider)
       {
          slider.addChangeListener(event -> {
             JSlider source = (JSlider) event.getSource();
             int value = source.getValue();
             ...
          });
       }
       
       public boolean hasNext()
       {
          return true;
       }
       
       public Integer next()
       {      
          try
          {
             return ...
          } 
          catch (InterruptedException ex)
          {
             return null;
          }
       }
       
       public void remove()
       {
          throw new UnsupportedOperationException();
       }
       
       private BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
    }
  4. Then add such an iterator to the end of main:
    Iterator<Integer> iter = new SliderIterator(frame.getSlider(0));
    while (iter.hasNext()) {
       System.out.println(iter.next());
    }           
    
    Run the program. What happens when you adjust the first slider?
  5. What is the drawback of using an iterator in this situation?

Discussion