I wanted to know how to do a TableCellRenderer for strings.
in this topic here:
I wanted to know how to do a TableCellRenderer for strings.
in this topic here:
There are two ways that stand out:
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:
Thismethodwouldchangeallcolumns,butitisdifficultforyoutochangetherenderingtocertaincolumnsinthefuture.
Todothis,you'llneedtochangethegetColumnClass
methodof < 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.