Java Swing 的 TableModel getValueAt 责任

Java Swing's TableModel getValueAt responsibility

Java Swing 的 TableModel...

有哪些责任

谁应该向用户呈现格式化显示?
有官方指导吗?

Java文档

getValueAt 的帮助说明:

Returns the value for the cell at columnIndex and rowIndex.

这里没有提到格式化。它 returns 单元格的“值”。一个Object.

我见过不同的实现 - 即使在我开发的产品中也是如此。感觉连贯性不高

例子

TableModel

DecimalFormat decimalFormat = new DecimalFormat("#.###");

@Override
public Object getValueAt(int row, int column) {
    ...
    decimalFormat.format(myObjectModel.GetFoo(row).getSomeDoubleProperty());
}


DefaultTableCellRenderer

public final class PositionDoubleCellRenderer extends DefaultTableCellRenderer {

    private final String formatPattern = "%,.03f";

    @Override
    public Component getTableCellRendererComponent(
            final JTable table, Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column
    ) {
        String formattedValue = "";

        if (value instanceof Double) {
            double numeric = (Double) value;

            if (ConstantsModel.isConstant(numeric)) {
                formattedValue = "";
            } else {
                formattedValue = String.format(formatPattern, numeric);
            }
        }

        return super.getTableCellRendererComponent(table, formattedValue, isSelected, hasFocus, row, column);
    }
}

优缺点取决于您使用的机制。我不知道还有什么其他的格式化方法,但我已经有一段时间想到这个了。

Who should present the formatted display to the user?

景色。 JTable 使用 renderers 到 format/display 数据。

in order to have consistent formatting of data in different tables for doubles, you then have to open up each table model and change for getValueAt

数据应该不会改变。因此 getValueAt(...) 方法不应更改。

一个渲染器可以被多个 table 共享。

您甚至可以通过覆盖 JTable.

getColumnClass(...) 方法来更改数据呈现给 table 的方式

table 有一些默认渲染器 Boolean.class、Number.class、Icon.class 等

因此,例如,如果您在模型中存储了一个整数值,并且如果您将 table 的 getColumnClass(...) 方法重写为 return:

  1. Integer.class - 数据将被格式化为数字并右对齐显示
  2. Object.cloass - 数据将被视为字符串并左对齐显示。

或者您甚至可以将自定义渲染器分配给 TableColumnModel 中的特定列。因此,如果您希望将整数格式化为“百分比”,您可以为此使用渲染器。

所以,最重要的是,当使用适当的渲染器时,相同的数据可以以无限多种方式显示。

查看 Table Format Renderers 以了解创建可重用格式渲染器的简单方法。