0

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;
        }
    }
}
4

1 回答 1

1

TableCellEditor看看方法stopCellEditing 。

根据 Javadoc:

告诉编辑器停止编辑并接受任何部分编辑的值作为编辑器的值。如果编辑没有停止,编辑器返回 false;这对于验证并且不能接受无效条目的编辑器很有用。

于 2013-06-06T06:28:30.187 回答