codice:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Andrea
*/
public class ColorRows extends JFrame {
private class MyJTable extends JTable {
private final Color rowhlcolor;
private int highLightedRow = -1;
private Rectangle dirtyRegion = null;
protected void processMouseMotionEvent(MouseEvent e) {
int row = rowAtPoint(e.getPoint());
boolean highlighted = false;
Graphics g = getGraphics();
// row changed
if(highLightedRow != row) {
if(null != dirtyRegion) {
paintImmediately( dirtyRegion );
}
for(int j = 0; j<getRowCount(); j++) {
if(row == j) {
//highlight
Rectangle firstRowRect = getCellRect(row, 0, false);
Rectangle lastRowRect = getCellRect(row, getColumnCount() - 1, false);
dirtyRegion = firstRowRect.union(lastRowRect);
g.setColor(new Color(rowhlcolor.getRed(), rowhlcolor.getGreen(), rowhlcolor.getBlue(), 30));
g.fillRect( (int)dirtyRegion.getX(), (int)dirtyRegion.getY(),
(int)dirtyRegion.getWidth(), (int)dirtyRegion.getHeight() );
highLightedRow = row;
}
}
}
}
public MyJTable(Object[][] data, Object[] columnNames, Color rowhlcolor ) {
super(data, columnNames);
this.rowhlcolor = rowhlcolor;
}
}
public ColorRows() {
super("Another test");
Object[][] data = {
{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
};
String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
MyJTable myTable = new MyJTable(data, columnNames, Color.red);
this.getContentPane().add(new JScrollPane(myTable), BorderLayout.CENTER);
this.setSize(400,400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String[] args) {
new ColorRows();
}
}