• Post Reply Bookmark Topic Watch Topic
  • New Topic

Alignment within a table?  RSS feed

 
Mike Lipay
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a table model set up to return, right now, five different fields. When I populate the table everything is left-aligned, how do I get other types of alignment (center, right)?

Here is the code snippet, trying to keep it to the minimum



Here is a picture of the output, what I am looking at doing is right-align the cost, and center the date.

>
 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out how TableCellRenderer and TableCellEditor work. Moving to our Swing forum.
 
Mike Lipay
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Check out how TableCellRenderer and TableCellEditor work. Moving to our Swing forum.


I looked at them, other than intercepting the process before the cell is drawn I don't see how to affect the alignment of the content.
 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your model knows absolutely nothing about how it is displayed. The JTable and its helper classes do that. Two of those helper classes is TableCellRenderer for displaying cell contents in the JTable and TableCellEditor for editing cell contents.

Most TableCellRenderer implementations return a JLabel as the table cell renderer component; check out DefaultTableCellRenderer for instance. You can then intercept that JLabel, change the horizontal alignment, and return it.
 
Mike Lipay
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, that makes sense. It returns a JLabel and I just modify the alignment of the label. Thanks!
 
Rob Camick
Ranch Hand
Posts: 2788
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is done by overriding the getColumnClass() method to return the proper class of data. So for dates, store a Date object in the model. For currency, store a Double object in the model. The table will choose the appropriate renderer and the renderer will choose the appropriate alignment.

However you can use custom renderers if desired. Check out the Table Format Renderers for example of how to customize the Date and Numbers. Since each renderer is just a label if you don't like the default alignment, then you can just change the horizontal alignment as is done in the number renderer.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!