1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableAvecFondColorie extends JTable {
private Paint backPaint;
public TableAvecFondColorie(DefaultTableModel model) {
super(model);
}
public static void main(String[] args) {
JFrame fr = new JFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableAvecFondColoried = new TableAvecFondColorie(new DefaultTableModel(3, 3));
d.setPreferredSize(new Dimension(400, 400));
d.setBackground(Color.yellow);
d.setBackPaint(Color.yellow);
JScrollPane js = new JScrollPane(d);
js.getViewport().setBackground(Color.yellow);
fr.getContentPane().add(js, BorderLayout.CENTER);
fr.pack();
fr.setVisible(true);
}
private int getTotalRowHeight() {
int h = 0;
for (int i = 0; i < getRowCount(); i++) {
h += getRowHeight(i);
}
return h;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(backPaint != null) {
Rectangle r = getBounds();
int w = getWidth();
int y = getTotalRowHeight();
int h = getHeight();
int dh = ((h-y)<0)?0:(h-y);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(backPaint);
g2d.fillRect(0, y, w, dh);
}
}
public Paint getBackPaint() {
return backPaint;
}
public void setBackPaint(Paint backPaint) {
this.backPaint = backPaint;
}
} |