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/main/java/dev/kske/chess/ui/BoardComponent.java

89 lines
2.2 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;
import dev.kske.chess.io.TextureUtil;
/**
* Project: <strong>Chess</strong><br>
* File: <strong>BoardComponent.java</strong><br>
* Created: <strong>01.07.2019</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.
*
* @since Chess v0.1-alpha
* @author Kai S. K. Engelbart
*/
public class BoardComponent extends JComponent {
private static final long serialVersionUID = 6771148331334310216L;
private final BoardPane boardPane;
private Board board;
/**
* Creates an instance of {@link BoardComponent}.
*
* @param boardPane the board pane inside which this board component is
* contained
*/
public BoardComponent(BoardPane boardPane) {
this.boardPane = boardPane;
setSize(boardPane.getPreferredSize());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final int tileSize = boardPane.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
);
}
/**
* @return the board rendered by this board component
*/
public Board getBoard() { return board; }
/**
* Sets the board rendered by this board component and repaints the
* component
*
* @param board the board rendered by this board component
*/
public void setBoard(Board board) {
this.board = board;
repaint();
}
}