Changing fonts in a JTable header

T

Tim Benner

I've been trying to figure out how to change the font in a JTable column
header to bold. I've been accessing the TableColumnModel().getColumn(x) for
the column I want, but i don't see any getFont or setFont methods which are
available.
Can someone point me in the right direction on how to change the header
text to bold in a JTable?

Thanks!

[Tim]
 
M

Matthew Zimmer

Tim said:
I've been trying to figure out how to change the font in a JTable column
header to bold. I've been accessing the TableColumnModel().getColumn(x) for
the column I want, but i don't see any getFont or setFont methods which are
available.
Can someone point me in the right direction on how to change the header
text to bold in a JTable?

Thanks!

[Tim]

Well, there may be a simpler way to do this than what I'm about to show
you, but the basic concept will work for you. Basically what you can do
is set the header renderer on the column to a specialized
TableCellRenderer. In my example below I create a class
MyHeaderRenderer that extends TableCellRenderer. The only method in
TableCellRenderer is "getTableCellRendererComponent". You can use the
ability of JLabels to handle html code to get the bold font (or any
other html you might use) for the header. Be aware though that my
example ONLY gives you bold text. It doesn't do any of the other nice
table header views that you would normally get (like borders, colors,
etc) so you'd have to add those to the JLabel as needed. Hope this helps.

Matthew



private void initTable()
{
JTable table = new JTable(myModel);
TableColumn column = table.getColumn("MyColumn");
column.setHeaderRenderer(new MyHeaderRenderer());
}
class MyHeaderRenderer implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
String txt = value.toString();
JLabel label = new JLabel("<html><body><b>" + txt +
"</b></body></html>");
return label;
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top