Home » Java » java – Changing JTable cell ForeGround color-Exceptionshub

java – Changing JTable cell ForeGround color-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to change the JTable cell color (foreground). It is working but it’s coloring the cell+1 and not the required cell (as you see in my code).

I’m trying to change the color of the current row and column 3 but, it’s actually changing the color of next column.

This code is added in the custom code.

BaritemsTable = new javax.swing.JTable(){
@Override
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex , int columnIndex ){
    Component component = super.prepareRenderer(renderer , rowIndex , columnIndex );
    Object value = getModel().getValueAt(rowIndex , columnIndex);

    if (columnIndex == 3){

        if (value.equals("Ready")){
            BaritemsTable.setForeground(new java.awt.Color(51, 204, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Process")){
            BaritemsTable.setForeground(new java.awt.Color(51, 51, 255));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }
        if (value.equals("Queued")){
            BaritemsTable.setForeground(new java.awt.Color(255, 0, 0));
            BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
        }

    } else {
        BaritemsTable.setForeground(new java.awt.Color(0, 0, 0));
        BaritemsTable.setFont(new Font("Tahoma", Font.PLAIN, 48));
    }
    return component;
  }
};
How to&Answers:

Problem one in your code, is definitely this:

Object value = getModel().getValueAt(rowIndex , columnIndex);

The indexes you are receiving in handlers and listener, methods etc in JTable are view indexes and can only be used to index the view. In other words, you should write:

Object value = getValueAt(rowIndex , columnIndex); // Use JTable.getValueAt

The second problem: when referencing a column index directly in prepareRenderer you should be using a view index in that spot. You most likely need

if (convertColumnIndexToModel(columnIndex) == 3)

JTable.convertColumnIndexToModel makes sure you are using an index from the model. Why is all this needed, and what is a view index and model index? How do they relate? I gave a bit more explanation here.


The third problem: if you want to set colors and fonts for a row/cell you need to set them on the component returned from super.prepareRenderer, not on the table. For instance:

if (value.equals("Ready")){
    component.setForeground(new java.awt.Color(51, 204, 0));
    component.setFont(new Font("Tahoma", Font.PLAIN, 48));
}