对于纯色,请考虑使用纯色Icon
(例如实现为ColorIcon
)。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class CheckerBoard {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
gui.setBackground(Color.RED.darker().darker());
int w = 9;
int h = 3;
gui.setLayout(new GridLayout(h, w, 2, 2));
for (int ii=0; ii<w*h; ii++) {
Color c = ii%2==0 ? Color.RED : Color.ORANGE;
gui.add(new JLabel(new ColorIcon(c, 16)));
}
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ColorIcon implements Icon {
Color color;
int preferredSize = -1;
private ColorIcon() {
}
public ColorIcon(Color color, int preferredSize) {
this.color = color;
this.preferredSize = preferredSize;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(0, 0, preferredSize, preferredSize);
}
@Override
public int getIconWidth() {
return preferredSize;
}
@Override
public int getIconHeight() {
return preferredSize;
}
}