Java Swing How to - Set column size








Question

We would like to know how to set column size.

Answer

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
//www .ja  v  a 2 s . c om
public class Main extends JPanel {

  public static void main(String[] args) {
    JFrame f = new JFrame("JTable");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setVisible(true);
  }

  public Main() {
    TableModel dataModel = new MyTableModel();
    JTable table = new JTable(dataModel);
    table.setAutoCreateRowSorter(true);
    table.getColumnModel().getColumn(0).setPreferredWidth(100);
    table.getColumnModel().getColumn(1).setPreferredWidth(150);
    table.getColumnModel().getColumn(2).setPreferredWidth(200);
    JScrollPane jsp = new JScrollPane(table);
    this.add(jsp);
  }

}

class MyTableModel extends AbstractTableModel {

  @Override
  public int getRowCount() {
    return 30;
  }

  @Override
  public int getColumnCount() {
    return 3;
  }

  @Override
  public Object getValueAt(int row, int col) {
    return Math.pow(row, col + 1);
  }

  @Override
  public Class<?> getColumnClass(int col) {
    return getValueAt(0, col).getClass();
  }
}