// Scott DeRuiter 2/28/2003
// Sort.java
// Show a bubble sort in action
// 3/12/2013 Greenstein: Changed to JFrame version
import java.awt.*;
import javax.swing.*;
public class Sort
{
JFrame frame;
Showsort panel;
public static void main(String[] args)
{
Sort sort = new Sort();
sort.Run();
}
public void Run()
{
frame = new JFrame("Bubble Sort");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create JPanel and add to frame
panel = new Showsort();
frame.getContentPane().add(panel, BorderLayout.CENTER); // add panel to frame
frame.setSize(515, 540); // explicitly set size in pixels
frame.setVisible(true); // set to false to make invisible
}
}
class Showsort extends JPanel
{
private int [] array = new int [10];
private Font MyFont;
Showsort()
{
setBackground(Color.red);
MyFont = new Font("Serif", Font.BOLD, 26);
for ( int i = 0; i < array.length; i++ )
array[i] = (int)(Math.random() * 99 + 1);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setFont(MyFont);
int inner, outer = -1;
for (inner = 0; inner < array.length; inner++)
{
DrawNumber ( g, inner, outer );
}
for (outer = 0; outer < array.length-1; outer++)
{
for (inner = 0; inner < array.length-1; inner++)
{
if (array[inner] > array[inner+1])
{
int temp = array[inner];
array[inner] = array[inner + 1];
array[inner + 1] = temp;
}
DrawNumber ( g, inner, outer );
}
DrawNumber ( g, inner, outer );
}
}
public void DrawNumber ( Graphics g, int inner, int outer )
{
g.setColor ( Color.black );
g.fillRect ( 50 * inner + 10, 50 * outer + 60, 44, 44 );
g.setColor ( Color.blue );
g.fillRect ( 50 * inner + 12, 50 * outer + 62, 40, 40 );
if ( outer == array.length - 2 )
g.setColor ( Color.lightGray );
else if ( inner < array.length - outer - 1 )
g.setColor ( Color.white );
else
g.setColor ( Color.lightGray );
g.fillRect ( 50 * inner + 14, 50 * outer + 64, 36, 36 );
if ( outer == array.length - 2 )
g.setColor ( Color.white );
else if ( inner < array.length - outer - 1 )
g.setColor ( Color.black );
else
g.setColor ( Color.white );
g.drawString ( array[inner] + "", 50 * inner + 20, 50 * outer + 90 );
}
}
Back to Lesson 24 Examples
Back to Java Main Page