我想在jtable派生类的标题中设置标签的垂直对齐方式。
我知道setVerticalAlignment(SwingConstants.BOTTOM);
我的标题比字体高得多,我想把文本稍微低于垂直中心。
如何在不覆盖paint()
的情况下做到这一点?
THX
一种方法是设置Renderer
, TableHeader
默认返回JLabel
,例如
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;
}
});
JTableHeader header = table.getTableHeader();
TableCellRenderer renderer = header.getDefaultRenderer();
renderer.setVerticalAlignment(SwingConstants.BOTTOM);