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

3

8

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

Vasomotor answered 19/6, 2013 at 9:48 Comment(0)
N
12

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));
Novelist answered 19/6, 2013 at 10:7 Comment(5)
Hi @Novelist But my problem is padding and not alignment. Could the cell padding be also adjusted using a custom TableCellRenderer?Vasomotor
@Vasomotor Yes, simply specify setBorder(BorderFactory.createEmptyBorder(5,5,5,5));Impudence
I've elaborated above on @Guillaume Polet's suggestion.Novelist
@pstanton: Can you change the HeaderRenderer?Novelist
thanks @Novelist just figured that part out too. swing is like a jigsaw puzzle sometimes.Starofbethlehem
B
12

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);
Babin answered 19/6, 2013 at 10:46 Comment(0)
A
4

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

Andonis answered 19/6, 2013 at 10:1 Comment(3)
What is setInternalSpacing?Novelist
@Novelist He probably meant javax.swing.JTable.setIntercellSpacing(Dimension)Impudence
yes I meant javax.swing.JTable.setIntercellSpacing(Dimension) which Sets the rowMargin and the columnMargin ( the height and width of the space between cells )Andonis

© 2022 - 2024 — McMap. All rights reserved.