How can we implement the word wrap JTableHeader of a JTable in Java?

JavaObject Oriented ProgrammingProgrammingSwing

JTableHeader

  • A JTableHeader is a subclass of JComponent class.
  • When we create a JTable object, the constructor creates a new JTableHeader object to manage the table component's header.
  • The JTableHeader object associated with the table component's column model so that its UI delegate can drag the columns and render each column's header cell.
  • A JTable supplies a setTableHeader() method that establishes the table header component's JTableHeader object and a getTableHeader() method that returns a reference to the table header component's JTableHeader object.

We can implement the word-wrap table header of a JTable by customizing the DefaultTableModel class or AbstractTableModel class.

Example

import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class WordWrappingTableHeaderTest extends JFrame {
   private JTable table;
   public WordWrappingTableHeaderTest() {
      setTitle("WordWrappingTableHeader Test");
      DefaultTableColumnModel tableColumnModel = new DefaultTableColumnModel() {
         public void addColumn(TableColumn column) {
            column.setHeaderRenderer(new JTableHeader().getDefaultRenderer());
            super.addColumn(column);
         }
      };
      table = new JTable();
      table.setFillsViewportHeight(true);
      table.setColumnModel(tableColumnModel);
      table.setModel(new DemoTableModel(Arrays.asList("Word Wrapping TableHeader Test", "Word Wrapping TableHeader Test", "Word Wrapping TableHeader Test"), 20));
      add(new JScrollPane(table));
      setSize(450, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setResizable(false);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   class DemoTableModel extends AbstractTableModel {
      private ArrayList wrappedColumnNames = new ArrayList();
      private int numRows;
      DemoTableModel(List columnNames, int numRows) {
         for (String name: columnNames)
            wrappedColumnNames.add("" + name + "");
            this.numRows = numRows;
      }
      public int getRowCount() {
         return numRows;
      }
      public int getColumnCount() {
         return wrappedColumnNames.size();
      }
      public Object getValueAt(int rowIndex, int columnIndex) {
         return Integer.valueOf(10000 + (rowIndex + 1)*(columnIndex + 1));
      }
      public String getColumnName(int column) {
         return wrappedColumnNames.get(column);
      }
      public Class getColumnClass(int columnIndex) {
         return Integer.class;
      }
   }
   public static void main(String[] args) {
     new WordWrappingTableHeaderTest();
   }
}

Output

raja
Published on 18-Jul-2019 12:22:54
Advertisements