Creating row headers for JTable at run time

泄露秘密 提交于 2019-12-06 09:50:21

I hope my interpretation of the question is correct. To display a row header you need to create a new cell renderer and set it on the required column. For example, here is a basic renderer that mocks a table header:

static class RowHeaderRenderer extends DefaultTableCellRenderer {
    public RowHeaderRenderer() {
        setHorizontalAlignment(JLabel.CENTER);
    }

    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        if (table != null) {
            JTableHeader header = table.getTableHeader();

            if (header != null) {
                setForeground(header.getForeground());
                setBackground(header.getBackground());
                setFont(header.getFont());
            }
        }

        if (isSelected) {
            setFont(getFont().deriveFont(Font.BOLD));
        }

        setValue(value);
        return this;
    }
}

To set it up you can do the following:

table.getColumnModel().getColumn(0).setCellRenderer(new RowHeaderRenderer());

Here is how it looks like based on the posted code:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!