I would like to center the text in some of my columns. So far, the only way I have found to do this is to create a new CellRenderer which extends JLabel and implements TableCellRenderer. I then add this cell renderer to the appropriate column. This sure does seem like a complicated solution to do something simple. Am I missing something?
Nope, you aren't missing anything. I went searching for the same answer and I landed up using the tableCellRenderer classes to accomplish this. It does seem like overkill, but when you do it a couple of times it is actually quite fast to incorporate into the code.
Don Kiddick wrote:You don't necessarily have to do that. DefaultTableCellRenderer *extends* JLabel so you can do :
Sorry to drag up an ages-old post, but could someone help me understand how this advice is implemented? Where do I declare the DefaultTableCellRenderer and how do I actually apply it to cells in the jTable?
Adam Price wrote:Sorry to drag up an ages-old post, but could someone help me understand how this advice is implemented? Where do I declare the DefaultTableCellRenderer and how do I actually apply it to cells in the jTable?
Have you gone through the Sun Swing tutorial, specifically the JTable section? It's all pretty much laid out for you there.
That is very helpful - thank you. I am using netbeans* and based on your tip, I added
as pre-creation code on the main panel in which the JTable resides. Then I used the Table Contens ->Columns -> renderer option to set the custom renderer as dtcr. That works for the column data, and I think it points me in the right direction to figure out how to center the column headers as well.
*I know that isn't a good way to learn Java, but I am not trying to learn java - I am trying to write a program that will help me with my graduate school research on chemical adsorption isotherms.