Reputation: 1
I have the below shown code:
if ("1".equals(tmp.get(h))) {
tmp2[0][h] = 1;
for (int j = 0; j < truthTable.getModel().getColumnCount(); j++) {
renderer = (DefaultTableCellRenderer) truthTable.getCellRenderer(0,
j);
renderer.setBackground(Color.yellow);
}
}
The getCellRenderer
method contains the parameter row and column and is supposed to set the row 0 with a yellow background but instead it sets the whole table in yellow background. I'm confused so what is the best solution for this?
Upvotes: 0
Views: 1164
Reputation: 168825
Point the mouse at the table.
package test;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class SingleCellColor {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String[][] data = {
{"a", "1","2","3"},
{"b", "3","4","5"},
{"c", "6","7","8"}
};
String[] columns = {
"Letter", "Num 1", "Num2 ", "Num 3"
};
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
final SingleCellRenderer renderer = new SingleCellRenderer();
final JTable table = new JTable(tableModel);
table.setDefaultRenderer(new Object().getClass(), renderer);
table.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
Point p = me.getPoint();
renderer.setColumnHightlight(table.columnAtPoint(p));
renderer.setRowHighlight(table.rowAtPoint(p));
table.repaint();
}
});
JScrollPane tableScroll = new JScrollPane(table);
JOptionPane.showMessageDialog(null, tableScroll);
}
});
}
}
class SingleCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
int rowHighlight = -1;
int colHighlight = -1;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
c.setBackground(Color.ORANGE);
if (c instanceof JComponent) {
boolean isFocused = (colHighlight == column && rowHighlight == row);
((JComponent)c).setOpaque(isFocused);
}
return c;
}
public void setColumnHightlight(int colHighlight) {
this.colHighlight = colHighlight;
}
public void setRowHighlight(int rowHighlight) {
this.rowHighlight = rowHighlight;
}
}
Upvotes: 2
Reputation: 285405
JTable cell renderers are not components but rather something more akin to rubber stamps that use a component to draw itself multiple times in your JTable. If you set the renderer's background to yellow and don't unset it if it's not the cell of interest, then it will remain yellow when drawing all cells.
Upvotes: 2