How to center a value in JTable cell? I\'m using Netbeans.
I had a similar problem. I wanted to align a single cell depending on the value of another cell. If cell X was NULL, then cell Y should be RIGHT aligned. Else, cell Y should be LEFT aligned.
I found this solution really helpful. It consists on creating a custom Render, extending DefaultTableCellRender.
Here's the code:
public class MyRender extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column){
super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
MyTableModel mtm = (MyTableModel)table.getModel();
switch(column){
case Y :
if(mla.getValueAt(row,X)!=null)
setHorizontalAlignment(SwingConstants.RIGHT);
else
setHorizontalAlignment(SwingConstants.LEFT);
break;
}
return this;
}
}
After that, just create a new instance of MyRender and set it to column Y, in this case. I do this when I load the information on the table.
MyRender render = new MyRender();
table.getColumnModel().getColumn(Y).setCellRender(render);
Hope it's useful!