001package horstmann.ch09_animation1;
002import java.awt.Graphics;
003import java.awt.Graphics2D;
004import java.awt.geom.Rectangle2D;
005
006import javax.swing.JComponent;
007
008/**
009   This component draws an array and marks two elements in the
010   array.
011 */
012@SuppressWarnings("serial")
013public class ArrayComponent extends JComponent
014{
015        public synchronized void paintComponent(Graphics g)
016        {
017                if (values == null) return;
018                Graphics2D g2 = (Graphics2D) g;
019                int width = getWidth() / values.length;
020                for (int i = 0; i < values.length; i++)
021                {
022                        Double v =  values[i];
023                        Rectangle2D bar = new Rectangle2D.Double(
024                                        width * i, 0, width, v);
025                        if (v == marked1 || v == marked2)
026                                g2.fill(bar);
027                        else
028                                g2.draw(bar);
029                }
030        }
031
032        /**
033      Sets the values to be painted.
034      @param values the array of values to display
035      @param marked1 the first marked element
036      @param marked2 the second marked element
037         */
038        public synchronized void setValues(Double[] values,
039                        Double marked1, Double marked2)
040        {
041                this.values = values.clone();
042                this.marked1 = marked1;
043                this.marked2 = marked2;
044                repaint();
045        }
046
047        private Double[] values;
048        private Double marked1;
049        private Double marked2;
050}