简体   繁体   English

使用单元格格式获取 JTable Integer 单元格值

[英]Get JTable Integer cell values with cell formatting

I have a JTable with a column containing integer values which are formatted to add a thousands separator.我有一个 JTable 列,其中包含 integer 值,这些值的格式设置为添加千位分隔符。 I am able to get the value of the columns using model.getValueAt() or table.getValueAt() but the values don't have the formatting.我可以使用model.getValueAt()table.getValueAt()获取列的值,但这些值没有格式。 How can I get the cell value with the formatting?如何获取具有格式的单元格值?

Code to format the cell:格式化单元格的代码:

table.getColumnModel().getColumn(5).setCellRenderer(new NumberTableCellRenderer());

Code for the class which handles the cell formatting:处理单元格格式的 class 的代码:

public static class NumberTableCellRenderer extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 1L;
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (value instanceof Number) {
           value = NumberFormat.getNumberInstance().format(value);
        
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }

}

How can I get the cell value with the formatting?如何获取具有格式的单元格值?

You would need to reapply the rendering logic.您需要重新应用渲染逻辑。 Something like:就像是:

TableCellRenderer renderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(renderer, row, column);

if (c instanceof JLabel)
{
    JLabel label = (JLabel)c;
    String formatted = label.getText();
}

However, this will only get you the String value.但是,这只会为您提供 String 值。 It will not get any color rendering since a String does not contain information like that.它不会得到任何颜色渲染,因为字符串不包含这样的信息。

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

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