Home Segments Top Top Previous Next

990: Mainline

While you are attending to the look and feel of a table, you might also wish to vary the column widths. Your program can extract the column model from your table, using the getColumnModel method, then pick, with the getColumn method, the instance that represents a particular column, and then call the setPreferredWidth method appropriately.

For example, you might decide that your table looks better if you make the title column five times wider than the other columns.

You can arrange for your program to do all the work when the table is constructed. If the total width of the table will be 750 pixels, and the title column will be five times as wide as the four other columns, then the preferred size of the title column is 417, and the preferred size of each of the other columns is 83:

import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class RatingTable extends JTable {
 public RatingTable (Vector rows, Vector columns) {
  super(new RatingTableModel(rows, columns));
  TableColumnModel model = getColumnModel();    
  for (int i = 0; i < columns.size(); ++i) {    
   TableColumn column = model.getColumn(i);     
   if (i == 0) {                                
    column.setPreferredWidth(417);              
   }                                            
   else {                                       
    column.setPreferredWidth(83);               
   }                                            
  } 
 } 
}