Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 290
Chad Avatar asked Jun 19 '13 09:06

Chad


People also ask

How can we add insert a JButton to JTable cell in Java?

We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method.

Which of the following methods would you use to set a column width in JTable?

By default the width of a JTable is fixed, we can also change the width of each column by using table. getColumnModel(). getColumn(). setPreferredWidth() method of JTable class.

How do I change the appearance of data in a JTable cell?

We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.


2 Answers

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));
like image 81
trashgod Avatar answered Sep 30 '22 11:09

trashgod


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);
like image 35
kleopatra Avatar answered Sep 30 '22 10:09

kleopatra