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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| public class MyFrame extends JFrame {
private MyTable myTable = new MyTable();
private JButton button = new JButton("Change les couleurs");
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
}
public MyFrame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(button, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(myTable));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Thread t = new Thread() {
public void run() {
for(int i = 0; i <20;i++){
myTable.changeCellsColor();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
});
this.pack();
this.show();
}
class MyTable extends JTable {
private int[][] colorIndexes = new int[5][5];
public MyTable() {
super(5, 5);
initColorIndexes();
this.setDefaultRenderer(
Object.class,
new MyCellRenderer(colorIndexes));
}
private void initColorIndexes() {
Random random = new Random();
for (int i = 0; i < colorIndexes.length; i++) {
for (int j = 0; j < colorIndexes[i].length; j++) {
colorIndexes[i][j] = random.nextInt(2);
}
}
}
public void changeCellsColor() {
initColorIndexes();
this.setDefaultRenderer(
Object.class,
new MyCellRenderer(colorIndexes));
updateUI();
}
} //:-
class MyCellRenderer extends DefaultTableCellRenderer {
private int[][] colorIndexes;
public MyCellRenderer(int[][] colors) {
super();
this.colorIndexes = colors;
}
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);
switch (colorIndexes[row][column]) {
case 0 :
c.setBackground(Color.GRAY);
break;
case 1 :
c.setBackground(Color.RED);
break;
default :
{
if (!isSelected)
c.setBackground(
UIManager.getLookAndFeelDefaults().getColor(c));
}
}
c.setForeground(Color.BLACK);
return c;
}
} //:-
} ///:- |
Partager