my question is, how to solve following problem:
If i click on a cell in a JTable, i want to change its background. If i release the mousebutton, i want the backgroun
For doing it in the visual realm you need
some code for the listeners
MouseListener l = new MouseAdapter() {
/**
* @inherited
*/
@Override
public void mousePressed(MouseEvent e) {
JTable table = (JTable) e.getComponent();
int col = table.columnAtPoint(e.getPoint());
int row = table.rowAtPoint(e.getPoint());
if (col < 0 || row < 0) {
table.putClientProperty("pressedCell", null);
} else {
table.putClientProperty("pressedCell", new Point(col, row));
}
}
/**
* @inherited
*/
@Override
public void mouseReleased(MouseEvent e) {
((JTable) e.getComponent()).putClientProperty("pressedCell", null);
}
};
table.addMouseListener(l);
PropertyChangeListener property = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
JTable table = (JTable) evt.getSource();
Point cell = evt.getNewValue() != null ?
(Point) evt.getNewValue() : (Point) evt.getOldValue();
if (cell != null) table.repaint(table.getCellRect(cell.y, cell.x, false));
}
};
table.addPropertyChangeListener("pressedCell", property);
Highlighting the cell in SwingX (cant resist :-)
HighlightPredicate predicate = new HighlightPredicate() {
@Override
public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
Point p = (Point) adapter.getComponent().getClientProperty("pressedCell");
return p != null && p.x == adapter.column && p.y == adapter.row;
}
};
table.addHighlighter(new ColorHighlighter(predicate, Color.YELLOW, null, Color.YELLOW, null));
For core Swing, either implement a custom TableCellRenderer or subclass the JTable and override prepareRenderer to set the background color according to the cell flag, as explained in Rob's Table Row Rendering