JTable header alignment
16,019
Solution 1
one of ways is to set Renderer
, TableHeader
by default returns JLabel
, for example
final TableCellRenderer tcrOs = myTable.getTableHeader().getDefaultRenderer();
myTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel lbl = (JLabel) tcrOs.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
lbl.setForeground(AppVariables.textColor);
lbl.setBorder(BorderFactory.createCompoundBorder(lbl.getBorder(),
BorderFactory.createEmptyBorder(0, 5, 0, 0)));
lbl.setHorizontalAlignment(SwingConstants.LEFT);
if (isSelected) {
lbl.setForeground(Color.red);
lbl.setBackground(Color.lightGray);
} else {
lbl.setForeground(Color.blue);
lbl.setBackground(Color.black);
}
return lbl;
}
});
Solution 2
JTableHeader header = table.getTableHeader();
TableCellRenderer renderer = header.getDefaultRenderer();
renderer.setVerticalAlignment(SwingConstants.BOTTOM);
Author by
Adam
Updated on June 28, 2022Comments
-
Adam almost 2 years
I would like to set the vertical alignment of the label in the header of my JTable-derrived class.
I am aware of
setVerticalAlignment(SwingConstants.BOTTOM);
My header is much higher than the font and I would like to place the text slightly below the vertical centre.
How can I do this, without overriding
paint()
?THX
-
Adam over 12 yearsThis is NOT an answer to my question. Read the question more carefully.
-
Adam over 12 yearsThanks mKobel! kleo it IS related. The trick I needed is burried in there. All I needed was: setBorder(BorderFactory.createCompoundBorder(getBorder(), BorderFactory.createEmptyBorder(6, 0, 0, 0)));
-
kleopatra over 12 yearsokay, I stand corrected, actually overlooked that line in all the clutter ;-)
-
camickr over 12 yearsStill a lot of random code to simply add a Border to a renderer. Sometimes it is hard to see the tree through the forest because you always add so much unnecessary code.
-
camickr over 12 years@Adam, I read the question 3 times. I still posted what I thought was the answer you where looking for. Usually I can read read between the lines for a poorly worded question, but I guess not this time. Next time post a proper SSCCE so we don't have to guess.
-
1000ml over 7 yearsThere's no method
setVerticalAlignment()
in theTableCellRenderer
interface. The renderer has to be cast toDefaultTableCellRenderer
. -
Kenny Dabiri almost 4 yearssetVerticalAlignment cannot be found. thus code isn't Not working