I'm trying to implement a Swing JTable. I followed the tuorial on http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#simple
I want the table cell's not to be editable (this works) and I want the table cells to have more padding to it's borders. Like cellpadding in HTML.
This is part of my code and the cellpadding thing doesn't work.
class BoardTableCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
return this;
}
}
String[] columnNames = {"Datei",
"Zeile",
"Zeichen",
"Fehler", "test"};
Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
};
JTable table = new JTable(data, columnNames){
private static final long serialVersionUID = -4430174981226468686L;
@Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}};
table.setAutoCreateRowSorter(true);
table.getTableHeader().setReorderingAllowed(false);
table.setDefaultRenderer(String.class, new BoardTableCellRenderer());
table
is placed on a JScrollPane
. The table is displayed, the cells are not editable but the cellpadding is not applied!
Can anyone help? Thanks :)
Default implementation of getColumnClass()
in DefaultTableModel
which is used by JTable
(by default) returns Object.class
. That is the reason BoardTableCellRenderer
is not used, as you're setting it up for columns with String.class
.
You may override getColumnClass
. Or in case of this sample, replace:
table.setDefaultRenderer(String.class, new BoardTableCellRenderer());
with:
table.setDefaultRenderer(Object.class, new BoardTableCellRenderer());
to see the effect of BoardTableCellRenderer
.