|
Java Checkerboard
Listing 1. Java is verbose, as demonstrated by the assembly of Swing components and event listeners in JavaCheckerboard. package example;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaCheckerboard extends JPanel {
public static class BoardPanel extends JPanel {
int width, height, tileWidth, tileHeight;
int[] initX;
public BoardPanel(int width, int height,
int tileWidth, int tileHeight) {
initX = new int[2];
setBoardSize(width, height, tileWidth,
tileHeight);
}
public void setBoardSize(int width, int height,
int tileWidth, int
tileHeight)
{
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
initX[0] = 0;
initX[1] = tileWidth;
setBoardSize(width, height);
}
public void setBoardSize(int width, int height) {
Dimension size;
this.width = width*tileWidth;
this.height = height*tileHeight;
size = new Dimension(this.width, this.height);
setPreferredSize(size);
}
private void paintTiles(
Graphics g, int firstTile, Color color) {
int x, y = 0, dx = 2*tileWidth;
g.setColor(color);
while(y < height) {
x = initX[firstTile];
while(x < width) {
g.fillRect(x, y, tileWidth, tileHeight);
x+=dx;
}
y+=tileHeight;
firstTile ^= 1;
}
}
public void paint(Graphics g) {
paintTiles(g, 0, Color.WHITE);
paintTiles(g, 1, Color.BLACK);
}
}
BoardPanel board;
JScrollPane boardContainer;
public class SizeListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
String item = (String)e.getItem();
JViewport viewport;
int size;
if("2x2".equals(item))
size = 2;
else if("4x4".equals(item))
size = 4;
else if("8x8".equals(item))
size = 8;
else
size = 16;
board.setBoardSize(size, size);
viewport = boardContainer.getViewport();
viewport.setViewPosition(new Point(0, 0));
repaint();
}
}
}
public JavaCheckerboard() {
JComboBox boardSize;
board = new BoardPanel(8, 8, 50, 50);
boardContainer = new JScrollPane();
boardContainer.setViewportView(board);
boardSize = new JComboBox();
boardSize.addItem("2x2");
boardSize.addItem("4x4");
boardSize.addItem("8x8");
boardSize.addItem("16x16");
boardSize.setSelectedIndex(2);
boardSize.addItemListener(new SizeListener());
setLayout(new BorderLayout());
add(boardContainer);
add(boardSize, BorderLayout.NORTH);
}
public static final void main(String[] args) {
JFrame frame = new JFrame("Fun and Games");
frame.getContentPane().add(
new JavaCheckerboard());
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
|