我会存储一个Rectangle数组,并在点击时查找哪一个包含该点。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChessBoard extends JPanel {
public static final int SIZE = 400;
public static final int COUNT = 8;
public static final int TILE_SIZE = SIZE / COUNT;
public static final Color RED = Color.RED;
public static final Color BLUE = Color.BLUE;
public static Tile[][] tiles;
static {
ChessBoard c = new ChessBoard();
tiles = new Tile[COUNT][COUNT];
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
tiles[i][j] = c.new Tile(i * TILE_SIZE, j * TILE_SIZE,
TILE_SIZE, TILE_SIZE);
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
ChessBoard c = new ChessBoard();
f.setTitle("Chessboard Tile Click");
f.setContentPane(c);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public ChessBoard() {
setPreferredSize(new Dimension(SIZE, SIZE));
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
if (tile.contains(p)) {
JOptionPane.showMessageDialog(null,
String.format("Clicked Tile: %s", tile));
break;
}
}
}
}
});
}
@Override
protected void paintComponent(Graphics g) {
boolean flip = false;
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
g.setColor((flip = !flip) ? BLUE : RED);
g.fillRect(tile.x, tile.y, TILE_SIZE, TILE_SIZE);
g.setColor(Color.WHITE);
g.drawString(tile.toString(), tile.x + (TILE_SIZE / 2) - 8,
tile.y + (TILE_SIZE / 2) + 6);
}
flip = !flip;
}
}
private class Tile extends Rectangle {
public Tile(int x, int y, int width, int height) {
super(x, y, width, height);
}
@Override
public String toString() {
return String.format("%c%d", 'A' + x / TILE_SIZE, COUNT - y
/ TILE_SIZE);
}
}
}