I am trying to create a simple Sudoku game and want to change the color of a cell in a table to light gray. My TableCellRender is below. Does anyone have a way to do this?
public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) {
//Find integer value in array, convert to string and make part of label JLabel theElement = new JLabel(arrayMatrix[row][column].toString(),CENTER); setOpaque(true); theElement.setFont(theFont); setBackground(Color.BLACK);
I am not sure I understand what problem exactly you have run into. Check out the following code snippet.
Points to note: 1) You need to explicitly set the renderer to the table. The line table.setDefaultRenderer(Object.class....) means use this renderer whenever you encounter the Object type of object 2) Setting the renderer for the object class would be the best bet for your Sudoku application. The object class would work for all the data types (String as in "5" Integer/int as in 5 and even if you switch to icons/images which display the number 5) 3) Since you are rendering as a label, you dont really need to subclass JLabel and implement the TableCellRenderer interface. The default rendered component of the DefaultTableCellRenderer is the label iteself. Also this label is opaque. So no need to explicitly call label.setOpaque(true); 4) You are constructing the label value from some array matrix from inside the renderer method. This is not really a good thing to do. Always provide a TableModel or Object[][]rowData to the table. You always get a reference to the cell object in the getTableCellRendererComponent() method if you want to use it. 5) Long time back I had developed a game for my daughter (it was noughts and crosses though) where I had a similar requirement of an interactive grid like UI. After playing around I realized that using a panel with a grid layout was the best approach. You might want to consider this approach as against the JTable unless of course your requirement is that it has to be a JTable.