How to change each column width of a JTable in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

JTable

  • A JTable is a subclass of JComponent for displaying complex data structures.
  • A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns.
  • The DefaultTableModel class can extend AbstractTableModel and it can be used to add the rows and columns to a JTable dynamically.
  • The DefaultTableCellRenderer class can extend JLabel class and it can be used to add images, colored text and etc. inside the JTable cell.
  • A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces.
  • By default the width of a JTable is fixed, we can also change the width of each column by using table.getColumnModel().getColumn().setPreferredWidth() method of JTable class.

Example

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableTest extends JFrame {
   private JTable table;
   private JScrollPane scrollPane;
   private DefaultTableModel model;
   private DefaultTableCellRenderer cellRenderer;
   public JTableTest() {
      setTitle("JTable Test");
      setLayout(new FlowLayout());
      scrollPane = new JScrollPane();
      JTable table = new JTable();
      scrollPane.setViewportView(table);
      model = (DefaultTableModel)table.getModel();
      model.addColumn("S.No");
      model.addColumn("First Name");
      model.addColumn("Last Name");
      model.addColumn("Email");
      model.addColumn("Contact");
      for(int i = 0;i < 4; i++) {
         model.addRow(new Object[0]);
         model.setValueAt(i+1, i, 0);
         model.setValueAt("Tutorials", i, 1);
         model.setValueAt("Point", i, 2);
         model.setValueAt("@tutorialspoint.com", i, 3);
         model.setValueAt("123456789", i, 4);
      }
      // set the column width for each column
      table.getColumnModel().getColumn(0).setPreferredWidth(5);
      table.getColumnModel().getColumn(3).setPreferredWidth(100);
      cellRenderer = new DefaultTableCellRenderer();
      cellRenderer.setHorizontalAlignment(JLabel.CENTER);
      table.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);
      add(scrollPane);
      setSize(475, 250);
      setResizable(false);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTableTest();
   }
}

Output

raja
Published on 17-Jul-2019 18:59:43
Advertisements