import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public final class ChessPanel extends JPanel {
private int width = 20;
private int n = 19;
private int[][] chess;
private int current = 1; public static void main(String[] args) {
JFrame aFrame = new JFrame();
aFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
aFrame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
aFrame.getContentPane().add(new ChessPanel());
aFrame.setSize(450, 450);
aFrame.show();
}
public ChessPanel() {
chess = new int[n][n];
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int i = (e.getX() + width / 2) / width - 1;
int j = (e.getY() + width / 2) / width - 1;
if (chess[i][j] == 0) {
chess[i][j] = current;
current = -current;
ChessPanel.this.repaint();
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i <= n; i++) {
g.drawLine(width, (i + 1) * width, (n + 1) * width, (i + 1) * width);
}
for (int i = 0; i <= n; i++) {
g.drawLine((i + 1) * width, width, (i + 1) * width, (n + 1) * width);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (chess[i][j] == 1) {
Color oldColor = g.getColor();
g.setColor(Color.BLACK);
g.fillOval((i + 1) * width + 1 - width / 2, (j + 1) * width + 1 - width / 2, width - 2, width - 2);
g.setColor(oldColor);
} else if (chess[i][j] == -1) {
Color oldColor = g.getColor();
g.setColor(Color.WHITE);
g.fillOval((i + 1) * width + 1 - width / 2, (j + 1) * width + 1 - width / 2, width - 2, width - 2);
g.setColor(oldColor);
}
}
}
}
}
给个棋盘你