This repository has been archived on 2021-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
chess/src/dev/kske/chess/ui/BoardComponent.java

63 lines
1.7 KiB
Java

package dev.kske.chess.ui;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import dev.kske.chess.board.Board;
/**
* Project: <strong>Chess</strong><br>
* File: <strong>BoardComponent.java</strong><br>
* Created: <strong>01.07.2019</strong><br>
* Author: <strong>Kai S. K. Engelbart</strong><br>
* <br>
* A square panel for rendering the chess board. To work correctly,
* this must be added to a parent component that allows the child to decide the
* size.
*/
public class BoardComponent extends JComponent {
private static final long serialVersionUID = 6771148331334310216L;
private final BoardPane boardPane;
private Board board;
public BoardComponent(BoardPane boardPane) {
this.boardPane = boardPane;
setSize(boardPane.getPreferredSize());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final int tileSize = getTileSize();
// Draw the board
g.setColor(Color.white);
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
if (j > 0) g.setColor(g.getColor().equals(Color.white) ? Color.lightGray : Color.white);
g.fillRect(tileSize * i, tileSize * j, tileSize, tileSize);
}
// Draw the pieces if a board is present
if (board != null) for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
if (board.getBoardArr()[i][j] != null) g.drawImage(TextureUtil
.getPieceTexture(board.getBoardArr()[i][j]), i * tileSize, j * tileSize, this);
}
public int getTileSize() { return boardPane.getTileSize(); }
public Board getBoard() { return board; }
public void setBoard(Board board) {
this.board = board;
repaint();
}
}