使用 Graphics 繪製棋盤格線,滑鼠點擊在對應格線交叉點顯示棋子,無視覺偏移。
GRID_SIZE(格寬/高)、MARGIN(邊距)、ROWS/COLS(行列數)。paintComponent(Graphics g) 循環畫橫豎線。(mx, my) → 最近格線交叉點索引 (row, col):
int col = Math.round((mx - MARGIN) / (float)GRID_SIZE);
int row = Math.round((my - MARGIN) / (float)GRID_SIZE);
0 <= row < ROWS && 0 <= col < COLS。cx = MARGIN + col * GRID_SIZE, cy = MARGIN + row * GRID_SIZE。int[][] board = new int[ROWS][COLS],0=空,1=黑,2=白。repaint(),paintComponent 遍歷 board 畫棋子(g.fillOval(cx-R, cy-R, 2R, 2R))。
public class BoardPanel extends JPanel {
static final int GRID = 40, MARGIN = 30, ROWS = 15, COLS = 15, R = 16;
int[][] board = new int[ROWS][COLS];
int currentPlayer = 1;
public BoardPanel() {
addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
int col = Math.round((e.getX() - MARGIN) / (float)GRID);
int row = Math.round((e.getY() - MARGIN) / (float)GRID);
if (row>=0 && row=0 && col2
repaint();
}
}
});
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 畫格線
for (int i=0; i<=ROWS; i++) g.drawLine(MARGIN, MARGIN+i*GRID, MARGIN+COLS*GRID, MARGIN+i*GRID);
for (int j=0; j<=COLS; j++) g.drawLine(MARGIN+j*GRID, MARGIN, MARGIN+j*GRID, MARGIN+ROWS*GRID);
// 畫棋子
for (int r=0; r
完整項目源碼可參考:Java 五子棋實現
核心秘訣:**浮點除法 + Math.round 找最近格點**,而非整數除法截斷,消除邊緣偏移,棋子精準落在格線交叉點中心。