Drawing Chess Game Board in Java - Source Code

Source code for Chess Game Board in Java :


public class ChessGUI extends JFrame {
    private Board board;
    private ChessGUI() {
        board = new Board();
        setLayout(new FlowLayout());
        add(board);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        pack();
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ChessGUI();
            }
        });
    }
    class Board extends JPanel {
        public Field[][] fields = new Field[8][8];
        public Board() {
            setLayout(new GridLayout(8, 8));
            setMinimumSize(new Dimension(600, 600));
            setPreferredSize(new Dimension(600, 600));
            setBackground(Color.RED);
            fillBoard();
        }
        private void fillBoard() {
            for (int i = 0; i < 8; ++i) {
                for (int j = 0; j < 8; ++j) {
                    fields[i][j] = new Field(i, j);
                    add(fields[i][j]);
                }
            }
        }
    }
    class Field extends JLabel {
        private int x, y;
        public Field(int x, int y) {
            this.x = x;
            this.y = y;
            setOpaque(true);
            setMinimumSize(new Dimension(75, 75));
            setPreferredSize(new Dimension(75, 75));
            if ((x + y) % 2 == 0) {
                setBackground(Color.BLACK);
            } else {
                setBackground(Color.WHITE);
            }
        }
    }
}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...