I would like to add a right-padding to a JTable column, is it possible?

陌路散爱 提交于 2019-12-10 14:29:49

问题


I want to add right cell-padding to a column in my JTable, how do I do it?

I tried searching online but I can't seem to find a definitive answer for this.

I hope someone can help me.

Regards, Chad


回答1:


Use a custom TableCellRenderer, and specify setHorizontalAlignment(JLabel.RIGHT). There's a related example here that illustrates JLabel.CENTER.

Addendum: My problem is padding and not alignment.

If you want the padding inside the cell, rather than between cells, you can use a border in the renderer, as @Guillaume Polet suggests. Note that the border can be asymmetric; the example below pads only on the right.

setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));



回答2:


A slightly enhanced version of @trashgod's correct answer is to compound the border with the padding: doing so guarantees that the default borders (f.i. the focus indicator) are not lost:

DefaultTableCellRenderer r = new DefaultTableCellRenderer() {

    Border padding = BorderFactory.createEmptyBorder(0, 10, 0, 10);
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                row, column);
        setBorder(BorderFactory.createCompoundBorder(getBorder(), padding));
        return this;
    }

};

Or use SwingX' JXTable and decorate the renderer with a Highlighter:

BorderHighlighter hl = new BorderHighlighter(
    BorderFactory.createEmptyBorder(0, 10, 0, 10));
hl.setInner(true);
table.addHighlighter(hl);



回答3:


Give a try with setInternalcellSpacing(Dimension d) of JTable.This will set spaces in both sides.If you strictly want to have it in one side use a renderer as here



来源:https://stackoverflow.com/questions/17188117/i-would-like-to-add-a-right-padding-to-a-jtable-column-is-it-possible

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