How to create TableCellRenderer for strings?

2

I wanted to know how to do a TableCellRenderer for strings.

in this topic here:

asked by anonymous 05.11.2016 / 18:17

1 answer

2

There are two ways that stand out:

- Centralizing specific columns

You can set centralized rendering only for certain columns by setting a default renderer for this column in isolation:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
//onde está zero pode ser alterado para a coluna desejada
tabela.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

Repeat the last row for all columns in the table, either by using a loop or manually if you have fewer columns.

By applying the above code in your example, only the País column will be centered:

-Applyingtotheentiretable

Thismethodwouldchangeallcolumns,butitisdifficultforyoutochangetherenderingtocertaincolumnsinthefuture.

Todothis,you'llneedtochangethegetColumnClassmethodof < strong> TableModel of the table. In the example, I did using DefaultTableModel , passing the array of rows and columns as parameters:

DefaultTableModel model = new DefaultTableModel(dados,colunas){

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return String.class;
    }
};

Then apply your table this way:

JTable tabela = new JTable(model);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
tabela.setDefaultRenderer(String.class, centerRenderer);

Applied in your example, the result will be:

TheproblemwiththismethodisthatallcolumnswillbetreatedasString,makingitabetteroption create a TableModel itself , so the code and its table are easier to read and maintain. It is up to you which method to use.

    
05.11.2016 / 18:56