JTable won't show column headers

I have the following code to instantiate a JTable: the table comes up with the right number of rows and columns, but there is no sign of the titles atop the columns.

public Panel1()
{
    int  nmbrRows;

    setLayout(null);
    setBackground(Color.magenta);
    Vector colHdrs;

    //create column headers

    colHdrs = new Vector(10);
    colHdrs.addElement(new String("Ticker"));

    // more statements like the above to establish all col. titles       

    nmbrRows = 25;
    DefaultTableModel tblModel = new DefaultTableModel(nmbrRows, colHdrs.size());
    tblModel.setColumnIdentifiers(colHdrs);

    scrTbl = new JTable(tblModel);
    scrTbl.setBounds(25, 50, 950, 600);
    scrTbl.setBackground(Color.gray);
    scrTbl.setRowHeight(23);    
    add(scrTbl);

//rest of constructor
...

}

Comparing this to other table-making code, I don't see any missing steps, but something must be absent.


Solution 1:

Put your JTable inside a JScrollPane. Try this:

add(new JScrollPane(scrTbl));

Solution 2:

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);