Reputation: 87
I am using a JTable to display numerical data and strings. The numerical data default formats to the right hand side of the JTable, and the strings format to the left. I want both to be formatted into the center of the cell. I am using Nedbeans to develop the GUI but it does not seem to help with this issue.
My attempt was to create a cell renderer class that overrides the JTable default cell renderer, but I don't know the line of code to actually change the formatting in the new cell renderer.
Any help would be appreciated.
Upvotes: 0
Views: 747
Reputation: 339
Your thinking is correct. Within the custom TableCellRenderer, you can actually check which column/row/cell is rendered and subsequently assign a column/row/cell specific formatting.
public static class CustomTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellRenderer c = (DefaultTableCellRenderer) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
// center everything in the first column
if (column == 0) {
c.setHorizontalAlignment(JLabel.CENTER);
}
// the background and border of the first cell should be gray
if (column == 0 && row == 0) {
c.setBackground(Color.GRAY);
c.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 5, Color.GRAY));
}
return c;
}
}
Please note that the DefaultTableCellRenderer
is called for each individual cell.
All available formatting functions are well described in the respective documentation: https://docs.oracle.com/javase/10/docs/api/javax/swing/table/DefaultTableCellRenderer.html
Upvotes: 1