OnJava8-Examples/ui/ColorBoxes.java

58 lines
1.6 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// ui/ColorBoxes.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// A visual demonstration of threading.
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;
import java.util.*;
import static onjava.SwingConsole.*;
2015-06-15 17:47:35 -07:00
class CBox extends JPanel implements Runnable {
private int pause;
private static Random rand = new Random();
private Color color = new Color(0);
public void paintComponent(Graphics g) {
g.setColor(color);
Dimension s = getSize();
g.fillRect(0, 0, s.width, s.height);
}
public CBox(int pause) { this.pause = pause; }
public void run() {
try {
while(!Thread.interrupted()) {
color = new Color(rand.nextInt(0x1000000));
repaint(); // Asynchronously request a paint()
TimeUnit.MILLISECONDS.sleep(pause);
}
} catch(InterruptedException e) {
// Acceptable way to exit
}
}
}
public class ColorBoxes extends JFrame {
private int grid = 12;
private int pause = 50;
private static ExecutorService exec =
Executors.newCachedThreadPool();
public void setUp() {
setLayout(new GridLayout(grid, grid));
for(int i = 0; i < grid * grid; i++) {
CBox cb = new CBox(pause);
add(cb);
exec.execute(cb);
}
}
public static void main(String[] args) {
ColorBoxes boxes = new ColorBoxes();
if(args.length > 0)
boxes.grid = new Integer(args[0]);
if(args.length > 1)
boxes.pause = new Integer(args[1]);
boxes.setUp();
run(boxes, 500, 400);
}
2015-09-07 11:44:36 -06:00
}