How to color specific lines of a JTable?

4

I'm developing a Java application that involves a JTable , I need to paint some red lines depending on the age and status of that line.

I'm using a DefaultTableModel to populate my table.

I do not know how to start. Could you help me?

    
asked by anonymous 06.02.2014 / 16:34

1 answer

3

This class should help you ...

Test Class

public class Teste extends JFrame {

private JPanel      contentPane;
private JScrollPane scrollPane;
private JTable      table;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                teste frame = new teste();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Teste() {
    initComponents();
}

private void initComponents() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    scrollPane = new JScrollPane();
    contentPane.add(scrollPane, BorderLayout.CENTER);

    table = new JTable();
    table.setModel(new DefaultTableModel(new Object[][] { { "", null, null, "VERMELHO" }, { null, null, null, null },
                    { null, null, null, "VERMELHO" }, { null, null, null, null }, }, new String[] { "Nome", "New column", "New column", "Cor" }));
    scrollPane.setViewportView(table);
    table.setDefaultRenderer(Object.class, new MeuModelo());
}

MyModel Class

public class MeuModelo extends DefaultTableCellRenderer {

    /**
     * 
     */
    private static final long   serialVersionUID    = 1L;

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        Color c = Color.WHITE;
        Object text = table.getValueAt(row, 3);
        if (text != null && "VERMELHO".equals(text.toString()))
            c = Color.RED;
        label.setBackground(c);
        return label;
    }
}
    
06.02.2014 / 17:00