import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
int[] numbers = new int[50];
int min = 20;
int max = 100;
boolean shuffle = false;
static final int ITERATION_SLEEP = 150;
public Main() {
loadArray();
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (shuffle)
loadArray();
selectionSort(numbers);
shuffle = true;
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 100);
}
private void loadArray() {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = min + (int) (Math.random() * ((max - min) + 1));
}
}
public void selectionSort(final int[] x) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < x.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < x.length; j++) {
if (x[minIndex] > x[j]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = x[i];
x[i] = x[minIndex];
x[minIndex] = temp;
}
repaint();
try {
Thread.sleep(ITERATION_SLEEP);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
private void drawPass(Graphics g) {
int rectWidth = 1;
int width = getWidth() - 1;
int height = getHeight() - 1;
int colSpan = Math.round((float) width / (float) numbers.length);
int x = 0;
for (int num : numbers) {
int colHeight = (int) ((float) height * ((float) num / (float) 100));
g.fillRect(x, height - colHeight, rectWidth, colHeight);
x += colSpan;
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawPass(g);
}
}