Overriding JTable's DefaultTableCellRenderer to center all the cells in a JTable

女生的网名这么多〃 提交于 2019-12-01 09:26:37

For applying the same visual decoration to all rendering components (if that's what you really want, be careful, it might have an usability penalty!) you can override the JTable's preparedRenderer method:

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component comp = super.prepareRenderer(...);
    if (comp instanceof JLabel) {
        ((JLabel) comp).setHorizontalAlignment(...);
    }
    return comp;
}

BTW: this approach is violating the rule to not subclass JSomething for application needs. You might consider using SwingX which formally supports visually decorating rendering components. So instead of subclassing, you would register a Highlighter with the table:

JXTable table = ...
table.addHighlighter(new AlignmentHighlighter(CENTER), HighlightPredicate.ALWAYS);   
trashgod

The default cell renderer already does this for values of type Boolean.class, as shown here. If this is not sufficient, please edit your question to include an sscce that exhibits any problems you encounter.

Addendum: If you need to further customize a DefaultTableCellRenderer, specify the renderer for the applicable type using setDefaultRenderer(), as shown here.

table.setDefaultRenderer(Boolean.class, yourCellRenderer); 

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