lucy said:
Hi, I've used the following to set the alignment for cells in JTable...
ttt.setAlignmentX(0.5);
ttt.setAlignmentY(0.5);
where ttt is a JTable object,
but it did not work at all,... (the JTable display shows no change at
all...)
What's the problem?
The solution is to use a CellRenderer.
Create a class that extends DefaultTableCellRenderer and implement the
getTableCellRendererComponent method, something like:
public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected,
boolean hasFocus, int
row, int column) {
JLabel renderedLabel = (JLabel) super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
renderedLabel.setHorizontalAlignment(SwingConstants.RIGHT);
return renderedLabel;
}
The DefaultTableCellRenderer is actually just a JLabel which JTable uses to
render each cell (a flywieght). You can then manipulate this JLabel as you
feel (set the alignment, text, colors, icon etc).
Then you need to apply this renderer to your JTable. You can do this by
overriding the JTable.getCellRenderer method:
public class MyJTable extends JTable {
private TableCellRenderer renderer;
public MyJTable(CellRenderer renderer) {
this.renderer = renderer;
}
public TableCellRenderer getCellRenderer(int row, int column) {
return renderer;
}
}