简体   繁体   English

在JTable列中设置右对齐

[英]Set Right Alignment in JTable Column

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列设置正确的对齐方式?

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

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;
    }
};

See Concepts: Editors and Renderers , noting " Number — rendered by a right-aligned label." 请参阅概念:编辑器和渲染器 ,注意“ Number - 由右对齐标签呈现”。 Just have your TableModel return the correct class. 让你的TableModel返回正确的类。 As a concrete example, note that Integer is a Number , while examining the implementation of getColumnClass() in this example . 作为一个具体示例,请注意Integer是一个Number ,同时在此示例中检查getColumnClass()的实现。 In this related example , the zeroth colIndex returns Object.class , which is "rendered by a label that displays the object's string value." 在此相关示例中 ,第0个colIndex返回Object.class ,它由“显示对象的字符串值的标签呈现”。 By default, the label is left-aligned. 默认情况下,标签是左对齐的。

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

左对齐

In contrast, Integer.class is "rendered by a right-aligned label." 相比之下, Integer.class是“由右对齐标签呈现的”。

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

右对齐

These are examples of using Class Literals as Runtime-Type Tokens , discussed here in the context of JTable . 这些是使用类文字作为运行时类型标记的示例, JTable的上下文中讨论。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM