简体   繁体   中英

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. I am able to get the value of the columns using model.getValueAt() or table.getValueAt() but the values don't have the formatting. 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:

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. It will not get any color rendering since a String does not contain information like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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