I have found a way to allocate the cell in a table, which seems to be a Component
JTable table = new JTable(...)
{
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// add custom rendering here
return c;
}
};
In the code, c
is the Component, but I cannot find a method in Component
to modify text alignment. Anything wrong about this approach?
Use DefaultTableCellRenderer
for that purposes, it has setHorizontalAlignment()
method :
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable arg0,Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
Component tableCellRendererComponent = super.getTableCellRendererComponent(arg0, arg1, arg2, arg3, arg4, arg5);
int align = DefaultTableCellRenderer.CENTER;
if(condition){
align = DefaultTableCellRenderer.LEFT;
}
((DefaultTableCellRenderer)tableCellRendererComponent).setHorizontalAlignment(align);
return tableCellRendererComponent;
}
};
t.getColumnModel().getColumn(COLUMN).setCellRenderer(renderer);
COLUMN
is target column, condition
is condition for switching.
(J)Component
havent this method(s) implemented in API
there are two ways
by casting (J)Component
to JLabel
set this value for class
managed by getColumnClass
.
DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer)
table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
I am going to make a conclusion.
For this specifiec problem, we can divide it into two:
To allocate the cell, my originally way and the way alex2410 should be both useful.
JTable table = new JTable(...)
{
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// add custom rendering here
return c;
}
};
another
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(arg0, arg1, arg2, arg3, arg4, arg5);
// add custom rendering here
return c;
}
};
t.getColumnModel().getColumn(COLUMN).setCellRenderer(renderer);
And for alignment, the only method I found useful is:
((DefaultTableCellRenderer)c).setHorizontalAlignment(SwingConstants.center);
In mKorbel's suggestion, you can cast the Component
c to JLabel
, but I failed to to that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.