Created
May 21, 2023 14:31
-
-
Save R3DHULK/61c9e0400f52567ec890d1ce0d5dc18e to your computer and use it in GitHub Desktop.
Chess Game Board In Java Swing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.event.*; | |
public class ChessGame extends JFrame { | |
private JPanel chessBoard; | |
private JButton[][] squares; | |
public ChessGame() { | |
setTitle("Chess Game"); | |
setSize(600, 600); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
chessBoard = new JPanel(new GridLayout(8, 8)); | |
squares = new JButton[8][8]; | |
// Create chess board with buttons representing squares | |
for (int i = 0; i < 8; i++) { | |
for (int j = 0; j < 8; j++) { | |
squares[i][j] = new JButton(); | |
chessBoard.add(squares[i][j]); | |
// Set button colors based on chess board pattern | |
if ((i + j) % 2 == 0) { | |
squares[i][j].setBackground(Color.WHITE); | |
} else { | |
squares[i][j].setBackground(Color.GRAY); | |
} | |
// Add action listener to handle button clicks | |
final int row = i; | |
final int col = j; | |
squares[i][j].addActionListener(new ActionListener() { | |
public void actionPerformed(ActionEvent e) { | |
squareClicked(row, col); | |
} | |
}); | |
} | |
} | |
add(chessBoard); | |
setVisible(true); | |
} | |
private void squareClicked(int row, int col) { | |
JOptionPane.showMessageDialog(this, "Square clicked: " + (char)('A' + col) + (8 - row)); | |
} | |
public static void main(String[] args) { | |
SwingUtilities.invokeLater(new Runnable() { | |
public void run() { | |
new ChessGame(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment