I have a TableCellRenderer problem that seems to be very wierd. I seached this forum and couldn't find any discussion about this behavior. Please have a look and let me know if you have any solution.
In the following code, all the table cell contains Double.class object. It has three columns. In the second column (column = 1), I want the double to be displayed in scientific format. For example, 12345 as 1.234E4. The problem I have is that once I enter one number in any of the table, the number is displayed all over the table! Say I enter 100 at cell (0,1),
after I hit enter. The number is correctly displayed as 1E2. Then I click anywhen within the table, this number (1E2) is propagated all over the table! That is crazy! Here is the complete code:
import javax.swing.*;
import java.awt.*;
import java.text.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class Test extends JFrame {
JTable table;
Object data[][];
String[] columnNames = {"first", "second", "third"};
MyTableModel tableModel;
/** Creates new Test */
public Test() {
data = new Object[100][3];
table = new JTable(new MyTableModel(data, columnNames));
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setDefaultRenderer(Double.class, new ScientificDoubleRenderer());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
setBounds(100, 100, 300, 400);
//setVisible(true);
}
public static void main(String argv[]){
Test t = new Test();
t.setVisible(true);
}
class MyTableModel extends DefaultTableModel{
String column[];
Object data[][];
public MyTableModel(Object dat[][], String[] col){
super(dat, col);
column = col;
data = dat;
}
public Class getColumnClass(int c){
return Double.class;
}
}
class ScientificDoubleRenderer extends JLabel implements TableCellRenderer{
DecimalFormat formatSci;
DecimalFormat formatDbl;
String patternSci = "0.###E0";
String patternDbl = "#######.###";
public ScientificDoubleRenderer(){
formatSci = new DecimalFormat(patternSci);
formatDbl = new DecimalFormat(patternDbl);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column){
if (value != null) {
if(column == 1)
setText(formatSci.format(((Double)value).doubleValue()));
else
setText(formatDbl.format(((Double)value).doubleValue()));
}
return this;
}
}
}