Java JTable - Add Column Headers

java crud

Hi,welcome to our Java JTable Add Column Headers tutorial.

The Plan

  • Simple JTable With several columns and Rows.
  • We render a column header on top of all our columns.
  • I have used Eclipse Lunar IDE.

Overview

  • JTable derives from Javax.Swing.JComponent.
  • Implements a couple of interfaces including ListSeelectionListener, CellEditorListener, TableModelListener, Scrollable among others.
  • It’s used to edit and display regular two-dimensional data in cells.
  • It doesn’t cache data, just displays it.
  • It allows a lot of customizations in terms of its rendering.
  • They are typically contained inside a JScrollpane.
  • Can enable filtering and sorting using Rowsorter.
  • DefaultTableModel is a model implementation using, yes, Vector of Vectors of Objects to store the values of cells.

Our Project

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

public class ColumnHeader  extends JFrame{

  //CONSTRUCT
    public ColumnHeader()
    {

    //TITLE,CLOSE
        super("JTABLE TUTOR");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

      //SET DATA
        Object[][] data=
          {
              {"1","Man Utd","Luis Van gaal","86"},
                  {"2","Chelsea","Jose Mourinho","84"},
                  {"3","Man City","Manuele Pelegrini","82"},
                  {"4","Arsenal","Arsene Wenger","80"},
                  {"5","Liverpool","Brendan Rodgers","78"},
          };

      //COLUMN HEADERS
        String[] columnHeaders={"Position","Team","manager","Points"};

        //CREATE TABLE
        JTable table=new JTable(data,columnHeaders);
        table.setPreferredScrollableViewportSize(new Dimension(500,80));

        //CUSTOM WIDTH
        TableColumn col0=table.getColumnModel().getColumn(0);
        TableColumn col1=table.getColumnModel().getColumn(1);
        TableColumn col2=table.getColumnModel().getColumn(2);

        col0.setPreferredWidth(5);
        col1.setPreferredWidth(300);
        col2.setPreferredWidth(150);

        //SCROLLPNAE
        JScrollPane pane=new JScrollPane(table);
        getContentPane().add(pane);

    }

    //MAIN METHOD
    public static void main(String[] args) {
      ColumnHeader c=new ColumnHeader();
      c.setVisible(true);
    }
}

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post