如何在JTable中绘制具有不同颜色的特定列?

时间:2018-06-06 23:01:32

标签: java swing jtable

我有一个JTable,我想根据单元格的颜色绘制一个具有不同颜色的列。要做到这一点,我试图创建一个'TableCellRender',但不能使它工作,值似乎隐藏在'setDefaultRenderer'之后。

我怎么能这样做?

试图

的TableModel

public class PartidasTableModel extends AbstractTableModel{
    private List<Partida> lista;
    private String[] colunas = {"Data ", "Casa x Visitante ", "Banca Inicial ", "Banca Final ", "Saldo ",  "Green/Red "};
    private ControlaDatas cDatas = new ControlaDatas(); 


    public PartidasTableModel(){
       this.lista = new ArrayList<Partida>();
    }

    public PartidasTableModel(List<Partida> lista){
        this();
        this.lista.addAll(lista);
    }

    @Override
    public int getRowCount() {
        return this.lista.size();
    }

    @Override
    public int getColumnCount() {
        return this.colunas.length;
    }

    //private String[] colunas = {"Data ", "Casa x Visitante ", "Banca Inicial ", "Banca Final ", "Saldo ",  "Green/Red "};
    public String getColumnName(int column){
        if(colunas[column] == "Data "){
            return "Data ";
        }else if(colunas[column] == "Casa x Visitante "){
            return "Casa x Visitante ";
        }else if(colunas[column] == "Banca Inicial "){
            return "Banca Inicial ";
        }else if(colunas[column] == "Banca Final "){
            return "Banca Final ";
        }else if(colunas[column] == "Saldo "){
            return "Saldo ";
        }else if(colunas[column] == "Green/Red "){
            return "Green/Red ";
        }
        return "";
    }

    //private String[] colunas = {"Data ", "Casa x Visitante ", "Banca Inicial ", "Banca Final ", "Saldo ",  "Green/Red "};
    public Class getColumnClass(int column){
        if(colunas[column] == "Data "){
            return String.class;
        }if(colunas[column] == "Casa x Visitante "){
            return String.class;
        }else if(colunas[column] == "Banca Inicial "){
            return String.class;
        }else if(colunas[column] == "Banca Final "){
            return String.class;
        }else if(colunas[column] == "Saldo "){
            return String.class;
        }else if(colunas[column] == "Green/Red "){
            return String.class;
        }
        return String.class;
    }

    //private String[] colunas = {"Conta ", "Vencto. ", "Capital R$ ", "Juros R$ "};
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Partida e = (Partida)lista.get(rowIndex);
        switch(columnIndex){
            case 0: return cDatas.getDataFormatada(e.getDtLancamento());
            case 1: return e.getTimeCasa() + " x " + e.getTimeVisitante();
            case 2: return FormataValorMonetario.getValorFormatado(e.getValorInicialBanca()); 
            case 3: return FormataValorMonetario.getValorFormatado(e.getValorFinalBanca()); 
            case 4: return FormataValorMonetario.getValorFormatado(e.getSaldo());  
            case 5: return isGreenOrRed(e.getGreenRed());
            default: return new String();
        }
    }

    private String isGreenOrRed(int value){
        if(value == 1){
            return "GREEN";
        }
        if (value == 2){
            return "RED";
        }
        return "";
    }

    /** retorna o objeto */
    public Partida getObject(int row){
        return lista.get(row);
    }

    /** remove registro da tabela */
    public void removeRow(int row){
        this.lista.remove(row);
        fireTableDataChanged();
    }

    /** altera a tabela */
    public void changeTabela(List<Partida> novaLista){
        this.lista = novaLista;
        fireTableDataChanged();
    }

}

的TableCellRenderer

public class PartidaCustomRenderer implements TableCellRenderer{
    private JLabel label;

    public PartidaCustomRenderer() {
        label = new JLabel();
        label.setOpaque(true);
    }



    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        Object obj = table.getValueAt(row, 5);//
        String redGreen = (String)obj;
        //pinta red/green        
        if(column == 5 && redGreen == "RED"){                      
            label.setBackground(Color.red);
        }else if(column == 5 && redGreen == "GREEN"){
            label.setBackground(Color.green);
        }



        return label;
    }

    private int getAlinhamento(int coluna){
        switch (coluna) {  
           case 0:  
               return SwingConstants.CENTER;  
           case 1:  
               return SwingConstants.LEFT;  
           case 2:  
           default:  
               return SwingConstants.RIGHT;  
       }  
    }
}

public class ViewPartidas extends javax.swing.JDialog {
    private PartidaDAO dao = new PartidaDAO();
    private List<Partida> lista = new ArrayList<Partida>();
    private PartidasTableModel model;

    public ViewPartidas(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        init();
    }

     private void init(){
        //table  
        lista = dao.findAll(Partida.FIND_ALL, Partida.class);
        model = new PartidasTableModel(lista);
        tabela.setModel(model); 
        tabela.setDefaultRenderer(Object.class, new PartidaCustomRenderer());
        tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tabela.setAutoCreateColumnsFromModel(false); 
        tabela.getTableHeader().setFont(new Font("Tahoma" , Font.BOLD, 11));
        tabela.getTableHeader().setReorderingAllowed(false);  
        tabela.setFont(new Font("Tahoma", Font.BOLD, 10));

    }

}

2 个答案:

答案 0 :(得分:1)

由于您的渲染器现在充当所有列的默认渲染,您还需要考虑如何处理它们......

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

    Object obj = table.getValueAt(row, 5);//
    String redGreen = (String)obj;
    //pinta red/green        
    if(column == 5 && redGreen == "RED"){                      
        label.setBackground(Color.red);
    }else if(column == 5 && redGreen == "GREEN"){
        label.setBackground(Color.green);
    }
    // No default fall through functionality
    // for the other columns


    return label;
}

成功实现这很复杂。更好的解决方案是将渲染设置为要在其上使用它的列...

tabela.getColumnModel().getColumn(5).setCellRenderer(new PartidaCustomRenderer());

我还建议使用DefaultTableCellRenderer,因为它针对JTable进行了优化,并基于JLabel

public class PartidaCustomRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        super.getTableCellRendererComponent(table, null, isSelected, hasFocus, row, column);

        String text = (String)value;
        if (column == 5 && text.equals("RED")) {
            setBackground(Color.red);
        } else if (column == 5 && text.equals("GREEN")) {
            setBackground(Color.green);
        }

        return this;
    }

    private int getAlinhamento(int coluna) {
        switch (coluna) {
            case 0:
                return SwingConstants.CENTER;
            case 1:
                return SwingConstants.LEFT;
            case 2:
            default:
                return SwingConstants.RIGHT;
        }
    }
}

答案 1 :(得分:1)

从本教程:

https://tips4java.wordpress.com/2010/01/24/table-row-rendering/

我们得到这段代码:

import { Component, OnInit } from '@angular/core'
import { FormGroup, FormBuilder} from '@angular/forms';

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss'],
})

export class FormComponent implements OnInit {
    formulario: FormGroup

    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
        this.formulario = this.formBuilder.group({
            pesquisa: [null],
        })
    }
    teste() {
        console.log(this.formulario.value.pesquisa)
    }
}

哪些应该很容易适应列而不是行,或特定列而不是交替列。

因此,为了解决这个问题,您需要创建自己的JTable子类,然后重写prepareRenderer方法。您仍然委托超级班级&#39;实现,然后你拿它给你的组件,并根据行和列进行特定的更改。