简体   繁体   English

JTable-如何更改特定列标题的字体

[英]JTable- How to change Font for a specific column header

I want to change the font for the header of the selected column on JTable . 我想更改JTable上所选列的标题的字体。 I tried to do that on my ColumnHeaderRenderer as follow : 我尝试在ColumnHeaderRenderer上执行以下操作:

public class ColumnHeaderRenderer extends JLabel implements TableCellRenderer {

public ColumnHeaderRenderer(JTable table) {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(BorderFactory.createEtchedBorder());
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    setPreferredSize(new Dimension(0, 25));

}

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {

    Color bg = UIManager.getColor("TableHeader.background");
    int selectedColumn = table.getSelectedColumn();
    if (selectedColumn == column){
        bg = new Color(107, 142, 35);
        setFont(getFont().deriveFont(Font.BOLD));// !!!!trying to do it here!!!!
    }
    setBackground(bg);
    setText(value.toString());
    return this;
}

}

But as result all column headers font is changed. 但是结果是所有列标题的字体都被更改。 So how can only change it for the selected column ? 那么,如何仅对选定的列进行更改?

You need to reset the values 您需要重置值

if (selectedColumn == column){
    bg = new Color(107, 142, 35);
    setFont(getFont().deriveFont(Font.BOLD));// !!!!trying to do it here!!!!
} else {
    setFont(UIManager.getFont("TableHeader.font"));
}

Renders are a shared resource, so all the headers share the same render. 渲染是共享资源,因此所有头均共享同一渲染。 This means if you change the state of the renderer from one pass to another, the next element rendered with the rendering will gain all the properties you used previously... 这意味着如果您将渲染器的状态从一遍更改为另一遍,则使用渲染渲染的下一个元素将获得您先前使用的所有属性...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM