001package horstmann.ch09_animation2;
002import java.awt.BorderLayout;
003import java.util.concurrent.BlockingQueue;
004import java.util.concurrent.LinkedBlockingQueue;
005
006import javax.swing.JButton;
007import javax.swing.JFrame;
008import javax.swing.JPanel;
009
010/**
011   This program animates a sort algorithm.
012 */
013public class AnimationTester
014{
015        public static void main(String[] args)
016        {
017                JFrame frame = new JFrame();
018                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
019
020                ArrayComponent panel = new ArrayComponent();
021                frame.add(panel, BorderLayout.CENTER);
022
023                JButton stepButton = new JButton("Step");
024                final JButton runButton = new JButton("Run");
025
026                JPanel buttons = new JPanel();
027                buttons.add(stepButton);
028                buttons.add(runButton);
029                frame.add(buttons, BorderLayout.NORTH);
030                frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
031                frame.setVisible(true);
032
033                Double[] values = new Double[VALUES_LENGTH];
034                for (int i = 0; i < values.length; i++)
035                        values[i] = Math.random() * panel.getHeight();
036
037                final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
038                queue.add("Step");
039
040                final Sorter sorter = new Sorter(values, panel, queue);
041
042                stepButton.addActionListener(event -> {
043                        queue.add("Step");
044                        runButton.setEnabled(true);
045                });
046
047                runButton.addActionListener(event -> {
048                        runButton.setEnabled(false);
049                        queue.add("Run");
050                });
051
052                Thread sorterThread = new Thread(sorter);
053                sorterThread.start();
054        }
055
056        private static final int FRAME_WIDTH = 300;
057        private static final int FRAME_HEIGHT = 300;
058        private static final int VALUES_LENGTH = 30;
059}