我知道这个问题已被问过两三次了。我查看了这些线程,但未能找到解决方案。
我只是想在JTable中创建一个棋盘图案。我有自己的渲染器,我已将其分配给单元格,如下所示:jtable cellrenderer changes backgroundcolor of cells while running
table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
在我自己的代码中,我有以下内容:
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);
}
我的自定义渲染器如下:
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;
}
当我运行此代码时,整个表格设置为深灰色。 hasFocus
部分完美无缺,但出于某种原因,每当我尝试为单个单元格设置背景时,它都会为整个表格设置它。如何使用row
和column
参数更改特定单元格的背景?