Home » Java » java – JTable cell text color changing-Exceptionshub

java – JTable cell text color changing-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I´m rather new to Java and programming itself, so excuse me for the question. What I´m trying to do is the following:

I´m making a bookkeeping program. On the column where the income/outcome is displayed, I want it so when the user enters a negative number (eg. -1.150€),
the number turns red( or any color really, but red is what most bookkeeping programs use). only that specific cell on that column only. I have not started with a code yet so I cannot input one here. I also do not need it to be right-aligned since I have already done that.

PS. Sorry if this post/question already exists, I searched but I found nothing that could help me much.

How to&Answers:

A small example with double values in a single column. This version uses JTable.setDefaultRenderer for Double.class.

You can also set colors

import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;

@SuppressWarnings("serial")
public class TableWithColors {
    protected static JTable createTable() {
        Object[][] rows = new Object[][] {{1.23d},{-20.5d},{5.87d},{2.23d},{-7.8d},{-8.99d},{9d},{16.25d},{4.23d},{-26.22d},{-14.14d}};
        Object[] cols = new Object[]{"Balance"};
        JTable t = new JTable(rows,cols) {
            @Override
            public Class<?> getColumnClass(int column) {
                if(convertColumnIndexToModel(column)==0) return Double.class;
                return super.getColumnClass(column);
            }
        };
        t.setDefaultRenderer(Double.class, new DefaultTableCellRenderer(){
            @Override
            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);
                c.setForeground(((Double) value)>0 ? Color.BLUE : Color.RED);
                return c;
            }
        });
        return t;
    }

    private static JFrame createFrame() {
        JFrame f = new JFrame("Table with colors");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new BorderLayout());
        f.add(new JScrollPane(createTable()),BorderLayout.CENTER);
        f.setSize(new Dimension(60,255));
        return f;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createFrame().setVisible(true);
            }
        });
    }
}

Goes like:

Change a balance from negative to positive and vice versa