java 我想向 JTable 列添加右填充,这可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17188117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:15:09  来源:igfitidea点击:

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

javaswingjtabletablecellrenderer

提问by Chad

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

我想向 JTable 中的列添加正确的单元格填充,我该怎么做?

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

我尝试在网上搜索,但似乎找不到明确的答案。

I hope someone can help me.

我希望有一个人可以帮助我。

Regards, Chad

问候,乍得

回答by trashgod

Use a customTableCellRenderer, and specify setHorizontalAlignment(JLabel.RIGHT). There's a related example herethat illustrates JLabel.CENTER.

使用自定义TableCellRenderer,并指定setHorizontalAlignment(JLabel.RIGHT). 这里有一个相关的例子说明JLabel.CENTER.

Addendum: My problem is padding and not alignment.

附录:我的问题是 padding 而不是 alignment

If you want the padding insidethe cell, rather than betweencells, 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.

如果您希望在单元格填充而不是单元格之间填充,则可以在渲染器中使用边框,如@Guillaume Polet 所建议的那样。请注意,边框可以是不对称的;下面的示例仅在右侧填充。

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

回答by kleopatra

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:

@trashgod 正确答案的略微增强版本是将边框与填充复合:这样做可以保证默认边框(fi 焦点指示器)不会丢失:

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:

或者使用SwingX' JXTable 并用荧光笔装饰渲染器:

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

回答by Sanjaya Liyanage

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

尝试使用 JTable 的 setInternalcellSpacing(Dimension d)。这将在两侧设置空格。如果您严格希望在一侧使用渲染器,请使用此处