• Post Reply Bookmark Topic Watch Topic
  • New Topic

Table Header Alignment  RSS feed

 
Frank Li
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to get the JTable Header Label left aligned with following code:
DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer();
leftRenderer.setHorizontalAlignment(JLabel.LEFT);
JTableHeader header = table.getTableHeader();
leftRenderer.setForeground(header.getForeground());
leftRenderer.setBackground(header.getBackground());
leftRenderer.setFont(header.getFont());
leftRenderer.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
header.getColumnModel().getColumn(0).setHeaderRenderer(leftRenderer);
The alignment is fine now. However, I lost the border of the header. The header does not look like a header now.
Can anyone tell me what's the problem and how can I fix it?
Many thanks in advance!
 
Jason Dobies
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try subclassing DefaultTableCellRenderer (for example, HeaderCellRenderer) and simply add something like the following:

Then assign that to the header row:

That should allow the renderer to perform whatever default rendering operations it wants while you simply override the alignment. Assigning it to the table header row should result in all of the formatting that makes it look like a header.
 
Frank Li
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jason.
That works but I need to add :
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setForeground(table.getTableHeader().getForeground());
setBackground(table.getTableHeader().getBackground());
in HeaderCellRenderer class. Otherwise the header is white and no border.
Thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!