I made this applet for my APCOMPSCIA class, it due tomorrow but I cant get it working. I need to show the animation of a sort, but it just does sort once that it, please help. I will be very great full.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class BarSelectionSort extends JApplet
{
//Variables and arrays
Rectangle[] bar_array = new Rectangle[10];
int minIndex;
private int pushes;
private JLabel label;
private JButton push;
private JLabel label2;
public void init()
{
final int NUM_BARS = 10, WIDTH = 30, MAX_HEIGHT = 300, GAP = 9;
int x = GAP, height;
bar_array = new Rectangle[10];
Random generator = new Random();
height = generator.nextInt(MAX_HEIGHT) + 1;
for (int i = 0; i < NUM_BARS; i++)
{
bar_array[i] = new Rectangle(x, MAX_HEIGHT-height, WIDTH, height);
height = generator.nextInt(MAX_HEIGHT) + 1;
x = x + WIDTH + GAP;
}
//Selection sort button
pushes = 0;
push = new JButton ("Selection sort!");
push.addActionListener (new ButtonListener());
label = new JLabel ("Pushes: " + Integer.toString (pushes));
Container cp = getContentPane();
cp.setBackground (Color.cyan);
cp.setLayout (new FlowLayout());
cp.add (push);
cp.add (label);
}
// Paints bars of varying heights, tracking the tallest and
// shortest bars, which are redrawn in color at the end.
public void paint (Graphics page)
{
final int GAP = 9;
int x;
setBackground (Color.black);
page.setColor (Color.blue);
x = GAP;
for (int i = 0; i < bar_array.length; i++)
{
Dimension d = bar_array[i].getSize();
Point p = bar_array[i].getLocation();
page.fillRect(p.x, p.y, d.width, d.height);
x = x + WIDTH + GAP;
}
}
// Sorts the specified array of rectangles using the selection
// sort algorithm.
void selectionSort()
{
for( int i = 0; i < bar_array.length - 1; i++ )
{
int minIndex = i;
for( int j = i + 1; j < bar_array.length; j++ )
{
if( bar_array[j].height < bar_array[minIndex].height )
{
minIndex = j;
}
}
if(minIndex > i)
{
Rectangle temp = bar_array[i];
bar_array[i] = bar_array[minIndex];
bar_array[minIndex] = temp;
int tempX = bar_array[i].x;
bar_array[i].x = bar_array[minIndex].x;
bar_array[minIndex].x = tempX;
}
}
}
private class ButtonListener implements ActionListener
{
// Updates the counter when the button is pushed.
public void actionPerformed (ActionEvent event)
{
pushes++;
label.setText("Amount of sorts: " + Integer.toString (pushes));
selectionSort();
repaint();
}
}
}