简体   繁体   中英

Change the font color in specific cell in Jtable

DefaultTableCellRenderer cellRender = new DefaultTableCellRenderer();
for(int i = 0; i < tblPackage.getRowCount(); i++)
{
    if("ACTIVE".equals(tblPackage.getModel().getValueAt(i, 3).toString()))
    {
                cellRender.setForeground(Color.GREEN);
    }
}

There's 4 columns in my table...and if the 4th columns of the data is equal to "ACTIVE" word, it will become to greeen color...how can I do that?? Is it got any problem with my logic??

You should override the getTableCellRendererComponent of the DefaultTableCellRenderer :

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column)
        {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if(table.getColumnModel().getColumn(column).getIdentifier()
                    .equals(your_4th_column_identifier)) // or use getColumnAt(4)
            {
                if(value.toString().equals("ACTIVE"))
                {
                    c.setBackground(Color.GREEN);
                }
            }
            return c;
        }

You can use the following:

    Jtable jtable = new JTable(dtm)
    {

        public Component prepareRenderer(TableCellRenderer renderer,int row,int column)
        {
              Component comp=super.prepareRenderer(renderer,row, column);
              if(column==3 && "ACTIVE".equals(tblPackage.getModel().getValueAt(row, 3).toString()))
              {
                     comp.setForeground(Color.GREEN);
              }
              return comp;

        }
     } ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM