/Users/lyon/j4p/src/ip/gui/frames/ColorGridFrame.java
|
1 package ip.gui.frames;
2
3 import java.awt.*;
4 import java.awt.image.ColorModel;
5 import java.awt.image.IndexColorModel;
6 import java.util.Random;
7
8 public final class ColorGridFrame extends ClosableFrame {
9 private ColorGridCanvas cgrid;
10 private Label label = new Label();
11 private Frame f;
12 private int r,g,b,a;
13
14
15 public static Font[] getAllFonts() {
16 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
17 return ge.getAllFonts();
18 }
19
20 public static Color getColor() {
21 return
22 javax.swing.JColorChooser.showDialog(
23 new Frame(), "Choose a color", Color.white);
24 }
25
26 // ip.gui.ColorGridFrame
27 public static void main(String args[]) {
28 System.out.println(getColor());
29 }
30
31 public ColorGridFrame(Frame f_) {
32 super("Color Grid");
33
34 f = f_;
35
36 ColorModel colorModel = Toolkit.getDefaultToolkit().getColorModel();
37 int bitsize = colorModel.getPixelSize();
38
39 if (colorModel instanceof IndexColorModel) {
40 // index color model
41 cgrid = new ColorGridCanvas(1 << bitsize);
42 for (int i = 0; i < 1 << bitsize; i++)
43 cgrid.setColor(i, colorModel.getRGB(i));
44 } else {
45 // direct color model
46 Random r = new Random();
47 cgrid = new ColorGridCanvas(256);
48 for (int i = 0; i < 256; i++)
49 cgrid.setColor(i, r.nextInt());
50 } // end else
51 add("Center", cgrid);
52 add("North", label);
53
54 setSize(300, 300);
55 show();
56 }
57
58 }
59
60 // This class displays a grid that is used for displaying colors.
61
62 class ColorGridCanvas extends Canvas {
63 int rows, cols;
64 int colors[];
65
66 ColorGridCanvas(int numColors) {
67 colors = new int[numColors];
68 cols = Math.min(16, numColors);
69 rows = (numColors - 1) / cols + 1;
70 }
71
72 // Sets the color at the cell located at position 'i'.
73 // 'rgb' is a color in the default RGB color model.
74 void setColor(int i, int rgb) {
75 colors[i] = rgb;
76 }
77
78 // Returns the pixel value at (x, y). The pixel value is encoded
79 // using the default color model.
80 int getRGB(int x, int y) {
81 Dimension r = getSize();
82 int cellW = r.width / cols;
83 int cellH = r.height / rows;
84
85 x /= cellW;
86 y /= cellH;
87
88 // Return the last color if out of bounds.
89 return colors[Math.min(colors.length - 1, y * cols + x)];
90 }
91
92 public void paint(Graphics g) {
93 Dimension rec = getSize();
94 int cellW = rec.width / cols;
95 int cellH = rec.height / rows;
96
97 for (int i = 0; i < colors.length; i++) {
98 int r = i / cols;
99 int c = i % cols;
100
101 g.setColor(new Color(colors[i]));
102 g.fillRect(c * cellW, r * cellH, cellW, cellH);
103 }
104 }
105 }
106
107