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 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| public class Demo {
private final static Color[] COLORS = {Color.RED,Color.BLUE,Color.GREEN};
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = createJTable();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(table, BorderLayout.CENTER);
panel.add(new JButton(new AbstractAction("Change data") {
private final Random random = new Random();
@Override
public void actionPerformed(ActionEvent e) {
TableModel model = table.getModel();
int rowCount = model.getRowCount();
for(int row=0; row<rowCount; row++) {
model.setValueAt(new BarData(random.nextInt(100), COLORS[row]),row, 2);
}
}
}),BorderLayout.SOUTH);
frame.getContentPane().add(panel);
frame.pack();
//frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JTable createJTable() {
JTable table = new JTable(new DefaultTableModel(new Object[][] {
{ 10, "truc", new BarData(30, Color.RED) },
{ 10, "bidule", new BarData(75, Color.BLUE) },
{ 10, "truc", new BarData(10, Color.GREEN) }
},
new String[] {"Col1", "Col2", "Col3"} ) {
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Integer.class;
case 1:
return String.class;
case 2:
return BarData.class;
default:
break;
}
return Object.class;
}
});
table.setDefaultRenderer(BarData.class, new BarDataCellRenderer());
return table;
}
private static class BarData {
private int value;
private Color color;
public BarData(int value, Color color) {
this.value=value;
this.color=color;
}
}
private static class BarDataCellRenderer extends Canvas implements TableCellRenderer {
private int value;
private Color color;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if ( value instanceof BarData ) {
BarData data = (BarData) value;
this.value = data.value;
this.color = data.color;
}
else {
this.value=0;
}
return this;
}
@Override
public void paint(Graphics g) {
super.paint(g);
if ( value>0 ) {
g.setColor(color);
g.fillRect(0, 0, (int)(getWidth()*(value/100d)), getHeight());
}
}
}
} |
Partager