I am learning the swing . I want to change the cell's color when the values has benn changed, eg: if the new value is more than the old value,set this cell's color to GREEN, But i don't know how to get this cell's old value in DefaultTableCellRenderer.
thanks. below is my sample code.
import java.awt.BorderLayout;
public class TableSample extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableSample frame = new TableSample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TableSample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
table = new JTable();
DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
tcr.setHorizontalAlignment(SwingConstants.RIGHT);
DefaultTableModel model = new DefaultTableModel();
model.addColumn(" column 1");
model.addColumn("column 2");
model.addRow(new String[] { "1", "1" });
model.addRow(new String[] { "2", "2" });
model.addRow(new String[] { "3", "3" });
model.addRow(new String[] { "3", "4" });
model.addRow(new String[] { "3", "5" });
model.addRow(new String[] { "3", "6" });
table.setDefaultRenderer(Object.class, tcr);
table.setModel(model);
scrollPane.setViewportView(table);
model.setValueAt("8", 5, 0);
}
static class MyDefaultTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
int v = Integer.parseInt((String) value);
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ( v > oldValue) {
super.setForeground(Color.GREEN);
} else {
super.setForeground(Color.RED);
}
return comp;
}
}
}