so ändern Sie die Hintergrundfarbe einer einzelnen Zelle in JTable in java?

Suche ich in der Tabelle, wenn ich ein Spiel will ich ändern, eine Hintergrundfarbe der Zelle.
Ich habe als unten, aber immer noch nicht lösen können? Kann jeder Körper helfen, um dieses problem zu beheben?

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

   }

InformationsquelleAutor itro | 2012-05-25

Schreibe einen Kommentar