• 0

[JAVA] JTable


Question

Hi guys,

I have a problem and hope some of you guys can help me out..

I am doing a search function and have a JTable for displaying the results.. Now, I will like to adjust the column width of each column based on the LONGEST value that is in that particular column.

I can't fix the value because every time i click on SEARCH, it will generate new data in the JTable and the data will change frequently.

Any idea how can i accomplish this?

Don

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Hi.. this is another question regarding JTable... instead of creating another thread i thought i'll just post here.

I am using this set of codes to align the values in a cell to CENTER. I think this code from some site..

private void alignTableCells(int column, int align )

{

DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();

dtcr.setHorizontalAlignment( align );

TableColumnModel tcm = table.getColumnModel();

TableColumn tc = tcm.getColumn( column );

tc.setCellRenderer( dtcr );

}

But this code requires me to set it column by column... therefore i need to do this.

alignTableCells(0,JLabel.CENTER);

alignTableCells(1,JLabel.CENTER);

alignTableCells(2,JLabel.CENTER);

alignTableCells(3,JLabel.CENTER);

alignTableCells(4,JLabel.CENTER);

alignTableCells(5,JLabel.CENTER);

alignTableCells(6,JLabel.CENTER);

alignTableCells(7,JLabel.CENTER);

alignTableCells(8,JLabel.CENTER);

alignTableCells(9,JLabel.CENTER);

alignTableCells(10,JLabel.CENTER);

So now i am wondering if there is a way i can SET it once only rather than the above code.

Thanks

Link to comment
Share on other sites

  • 0
I have seen this example but i don't really understand. Actually, i just need the concept but not the actual codes...

Concept is: Your table has a DefaultRenderer which formats each value to whatever form it's being displayed in. You search down the column, using the DefaultRenderer to do a "dummy" formatting of each value, and you get the PreferredSize.width of each formatted value, and keep the highest. At the end, the highest value you have kept is the width needed to hold the widest formatted value in that column, so you use it to set the column width.

It may sound a bit heavy, but unless your table is absolutely vast it executes instantaneously.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.