I know this question has been asked two or three times. I've viewed those threads and have not been able to reach a solution.
I'm simply trying to create a checkerboard pattern in a JTable. I have my own renderer that I've assigned to the cells as shown here: jtable cellrenderer changes backgroundcolor of cells while running
table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
In my own code, I have the following:
public void initGUI(){
//allocate the components
frame = new JFrame();
gamePanel = new JPanel();
gameBoard = new BoardTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
//adjust the chessboard's look
for(int i = 0; i < 8; i++){
gameBoard.getColumnModel().getColumn(i).setMinWidth(SQUARE_CELL);
gameBoard.getColumnModel().getColumn(i).setPreferredWidth(SQUARE_CELL);
gameBoard.getColumnModel().getColumn(i).setMaxWidth(SQUARE_CELL);
gameBoard.getColumnModel().getColumn(i).setCellRenderer(customRender);
}
gameBoard.setRowHeight(SQUARE_CELL);
gameBoard.setFont(new Font(Font.SERIF, Font.PLAIN, 30));
//adjust the panel's look
gamePanel.setBackground(new Color(112, 128, 144));
//put the pieces on the board
updateBoard();
//fit everything together
gamePanel.add(gameBoard);
frame.add(gamePanel);
frame.setMinimumSize(new Dimension(500, 500));
frame.setVisible(true);
}
My custom renderer is as follows:
public class BoardCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(SwingConstants.CENTER);
if(row == 7)
setBackground(new Color(100, 100, 100));
if(hasFocus)
setBorder(new MatteBorder(2, 2, 2, 2, Color.RED));
return this;
}
When I run this code, the entire table is set to a dark gray. The hasFocus
portion works flawlessly, but for some reason whenever I try to set the background for a single cell, it sets it for the entire table. How can I change the background for a specific cell using the row
and column
parameters?