TableCellRenderer

Anybody know why the number column,Value1 andValue2 are not rendered properly?

import java.text.*;

import javax.swing.*;

import javax.swing.table.*;

publicclass JTableTest{

private JTable table;

public JTableTest(){

String[] columnNames ={"Name","Value1","Value2"};

Object[][] data ={

{"X",new Integer(12500),new Integer(13000)},

{"Y",new Integer(36000),new Integer(25000)},

{"Z",new Integer(21500),new Integer(20000)}

};

JFrame frame =new JFrame("Testing JTable Renderer");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

table =new JTable(data, columnNames);

table.setDefaultRenderer(java.lang.Number.class,

new NumberCellRenderer(SwingConstants.RIGHT));

frame.getContentPane().add(table);

frame.pack();

frame.setVisible(true);

}

publicstaticvoid main(String[] a){

new JTableTest();

}

}

class NumberCellRendererextends DefaultTableCellRenderer{

protectedint align;

protectedstatic NumberFormat formatter = NumberFormat.getInstance();

public NumberCellRenderer(int align){

super();

this.align = align;

}

protectedvoid setValue(Object value){

if (value !=null){

formatter.setGroupingUsed(true);

formatter.setMaximumIntegerDigits(11);

formatter.setMaximumFractionDigits(0);

formatter.setMinimumFractionDigits(0);

setText(formatter.format(value));

}else{

super.setValue(value);

}

setHorizontalAlignment(align);

}

}

[3694 byte] By [William.Anthonya] at [2007-11-27 3:56:32]
# 1

By default the getColumnClass(...) method returns Object as the column type, so the table doesn't know you have Integers stored in the table. So you need to override the method to return the appropriate class for each column.

Or the other approach is to assign the renderer directly to the column:

table.getColumnModel().getColumn(...).setCellRenderer( ... );

camickra at 2007-7-12 9:00:46 > top of Java-index,Desktop,Core GUI APIs...
# 2

the thing is, that your setValue()-method is never call by the renderer.

You must put the method in the public Component getTableCellRendererComponent(JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column) {

method

but first call super.getTableCellRendererComponent(...)

Oleka at 2007-7-12 9:00:46 > top of Java-index,Desktop,Core GUI APIs...
# 3
Thanks for the answers.
William.Anthonya at 2007-7-12 9:00:46 > top of Java-index,Desktop,Core GUI APIs...