import java.awt.*; import javax.swing.*; /* */ public class BubbleSort1 extends JApplet implements Runnable { int[] args = {10, 3, 46, 7, 23, 34, 8, 12, 4, 45, 44, 52}; Color[] cs = {Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE}; Thread thread = null; @Override public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } @Override public void stop() { thread = null; } @Override public void paint(Graphics g) { int i; super.paint(g); for (i = 0; i < args.length; i++) { g.setColor(cs[args[i] % cs.length]); g.fillRect(0, i * 10, args[i] * 5, 10); } } public void run() { Thread thisThread = Thread.currentThread(); while (true) { int i, j; for (i = 0; i < args.length - 1; i++) { for (j = args.length - 1; j > i && thread == thisThread; j--) { if (args[j - 1] > args[j]) { // スワップする。 int tmp = args[j - 1]; args[j - 1] = args[j]; args[j] = tmp; } repaint(); try { // repaintの後でしばらく止まる Thread.sleep(500); } catch (InterruptedException e) {} } } } } public static void main(String[] args) { JFrame frame = new JFrame(""); JApplet applet = new BubbleSort1(); applet.setPreferredSize(new Dimension(300, 200)); frame.add(applet); frame.pack(); frame.setVisible(true); applet.init(); applet.start(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }