Java 在 JTable 列中设置右对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3467052/
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-08-14 01:01:27  来源:igfitidea点击:

Set Right Alignment in JTable Column

javaswingjtable

提问by Arivu2020

I am creating an application for a billing facility. I want the amount column to display with right alignment. How do I set the right alignment for a JTable column?

我正在为计费工具创建应用程序。我希望金额列以右对齐方式显示。如何为 JTable 列设置正确的对齐方式?

回答by trashgod

See Concepts: Editors and Renderers, noting "Number— rendered by a right-aligned label." Just have your TableModelreturn the correct class. As a concrete example, note that Integeris a Number, while examining the implementation of getColumnClass()in this example. In this related example, the zeroth colIndexreturns Object.class, which is "rendered by a label that displays the object's string value." By default, the label is left-aligned.

请参阅概念:编辑器和渲染器,注意“ Number— 由右对齐标签渲染”。只需让您TableModel返回正确的课程即可。作为一个具体的例子,在检查这个例子中的实现时,请注意它Integer是。在这个相关示例中,第零个返回,它“由显示对象字符串值的标签呈现”。默认情况下,标签左对齐。NumbergetColumnClass()colIndexObject.class

switch (colIndex) {
    case 0: return Object.class;
    …
}

left-aligned

左对齐

In contrast, Integer.classis "rendered by a right-aligned label."

相比之下,Integer.class是“由右对齐标签呈现”。

switch (colIndex) {
    case 0: return Integer.class;
    …
}

right-aligned

右对齐

These are examples of using Class Literals as Runtime-Type Tokens, discussed herein the context of JTable.

这些是使用的示例类常量作为运行时类型令牌,讨论在这里的背景下JTable

回答by YoK

You will have to get DefaultTableCellRenderer for table cells and call setHorizontalAlignment(alignment).

您必须为表格单元格获取 DefaultTableCellRenderer 并调用 setHorizo​​ntalAlignment(alignment)。

Example can be found on links:

可以在链接上找到示例:

http://www.techrepublic.com/article/how-to-justify-data-in-a-jtable-cell/5032692/

http://www.techrepublic.com/article/how-to-justify-data-in-a-jtable-cell/5032692/

http://www.coderanch.com/t/337549/GUI/java/align-data-columns-JTable

http://www.coderanch.com/t/337549/GUI/java/align-data-columns-JTable

回答by Emil

Try this:

尝试这个:

JTable tbl = new JTable(3,3) {
    DefaultTableCellRenderer renderRight = new DefaultTableCellRenderer();

    { // initializer block
        renderRight.setHorizontalAlignment(SwingConstants.RIGHT);
    }

    @Override
    public TableCellRenderer getCellRenderer (int arg0, int arg1) {
        return renderRight;
    }
};

回答by sathya

DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
table.getColumnModel().getColumn(4).setCellRenderer(rightRenderer);