SE450: Algorithm Animation [35/36] Previous pageContentsNext page


file:horstmann/ch09_animation1/ArrayComponent.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package horstmann.ch09_animation1;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;

/**
   This component draws an array and marks two elements in the
   array.
 */
@SuppressWarnings("serial")
public class ArrayComponent extends JComponent
{
  public synchronized void paintComponent(Graphics g)
  {
    if (values == null) return;
    Graphics2D g2 = (Graphics2D) g;
    int width = getWidth() / values.length;
    for (int i = 0; i < values.length; i++)
    {
      Double v =  values[i];
      Rectangle2D bar = new Rectangle2D.Double(
          width * i, 0, width, v);
      if (v == marked1 || v == marked2)
        g2.fill(bar);
      else
        g2.draw(bar);
    }
  }

  /**
      Sets the values to be painted.
      @param values the array of values to display
      @param marked1 the first marked element
      @param marked2 the second marked element
   */
  public synchronized void setValues(Double[] values,
      Double marked1, Double marked2)
  {
    this.values = values.clone();
    this.marked1 = marked1;
    this.marked2 = marked2;
    repaint();
  }

  private Double[] values;
  private Double marked1;
  private Double marked2;
}

file:horstmann/ch09_animation1/AnimationTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package horstmann.ch09_animation1;
import java.awt.BorderLayout;

import javax.swing.JFrame;

/**
   This program animates a sort algorithm.
 */
public class AnimationTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ArrayComponent panel = new ArrayComponent();
    frame.add(panel, BorderLayout.CENTER);

    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setVisible(true);

    Double[] values = new Double[VALUES_LENGTH];
    for (int i = 0; i < values.length; i++)
      values[i] = Math.random() * panel.getHeight();

    Runnable r = new Sorter(values, panel);
    Thread t = new Thread(r);
    t.start();
  }

  private static final int VALUES_LENGTH = 30;
  private static final int FRAME_WIDTH = 300;
  private static final int FRAME_HEIGHT = 300;
}

Previous pageContentsNext page