如何在java中改变JTable中单个单元格的背景颜色?

时间:2012-05-25 13:56:54

标签: java swing jtable tablecellrenderer

我在表格中搜索,当我找到匹配项时,我想要更改该单元格的bg颜色。 我做了如下,但仍然无法修复它?任何人都可以帮助解决这个问题吗?

public class SearchTable extends JTable {
JTable table;
JTextField textField;

public SearchTable(JTable table, JTextField textField) {
    this.table = table;
    this.textField = textField;

    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            search();
        }
    });

    textField.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            search();
        }
        public void removeUpdate(DocumentEvent e) {
            search();
        }
        public void changedUpdate(DocumentEvent e) {
            search();
        }
    });
}

private void search() {
    String target = textField.getText();
    for (int row = 0; row < table.getRowCount(); row++)
        for (int col = 0; col < table.getColumnCount(); col++) {
            String next = (String) table.getValueAt(row, col);
            if (next.equals(target)) {
                changeBackgroundColor(row, col);
                return;
            }
        }
    table.repaint();
}

private void changeBackgroundColor(int row, int col) {
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);
    boolean toggle = false;
    boolean extend = false;
    table.changeSelection(row, col, toggle, extend);
    //first atempt sets bg color for all cells, it is not OK
    //table.setSelectionBackground(Color.green);

    //second atempt getting no result
    table.getCellEditor(row,col).getTableCellEditorComponent(table,table.getValueAt(row,col),true,row,col).setForeground(Color.red);

    //3th atempt getting no result
    //Component c = table.getCellRenderer(row, col).getTableCellRendererComponent(table, table.getValueAt(row, col), true, true, row, col);
    //c.setForeground(Color.red);

    //4th atempt getting no result
    //DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) table.getCellRenderer(row, col).getTableCellRendererComponent(table, table.getValueAt(row, col), true, true, row, col).;
      //renderer.setBorder(new LineBorder(Color.red));
}

   }

2 个答案:

答案 0 :(得分:3)

您可以使用XxxCellRenderer,更好,最简单的方法是使用prepareRenderer()

对于正确的代码,您必须覆盖或测试内部if-else跟随patameters

  • isSelected

  • hasFocus

请查看answersquestion关于similair问题,有两个简单的方法,抱歉我在FRI交通,brrrrr

答案 1 :(得分:0)

您需要先将单元格渲染器设置为列 -

col.setCellRenderer( new TableCellRenderer() {
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) 
                {
                    Component cell = centerRenderer.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
    cell.setForeground(Color.green);
}
});