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
| public class JTableRendererDemo {
public enum Action {
CREATE(Color.WHITE, Color.BLUE),
DELETE(Color.WHITE, Color.RED),
UPDATE(Color.BLACK, Color.ORANGE);
private final Color fg;
private final Color bg;
private Action(Color fg,Color bg) {
this.fg=fg;
this.bg=bg;
}
public Color getForeground() {
return fg;
}
public Color getBackground() {
return bg;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createTable());
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static Component createTable() {
final Object[][] data = new Object[][]{
{ Action.DELETE, "toto", "" },
{ Action.UPDATE, "", "" },
{ Action.CREATE, "tutu", "" }
};
final JTable table = new JTable(data, new String[]{"Action","Name",""});
table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if( value instanceof Action) {
setForeground(((Action)value).getForeground());
setBackground(((Action)value).getBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
});
table.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ( value instanceof String && ((String)value).isEmpty() ) {
setValue("Vide");
setFont(getFont().deriveFont(Font.ITALIC));
}
return component;
}
});
final JPanel panel = new JPanel(new BorderLayout());
final JScrollPane scrollpane = new JScrollPane(table);
/*final JViewport columnView = new JViewport();
columnView.setView(table.getTableHeader());
scrollpane.setColumnHeader(columnView);*/
panel.add(scrollpane);
return scrollpane;
}
} |