tags:

views:

542

answers:

2

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.

Thanks in advance for any help.

+8  A: 

Put your JTable inside a JScrollPane. Try this:

add(new JScrollPane(scrTbl));
Erkan Haspulat
I've discovered (and used) this solution before, but I'm curious if anyone knows *why* this works.
Joe Carnahan
The table header it put into the JScrollPane top component ( or top view or something like that is named ) When there is no top component the JTable appears headless. This is by design.
OscarRyz
I have found this link, it might be helpful understaning this issue: http://blog.danieldee.com/2009/07/showing-jtable-header-without-using.html
Erkan Haspulat
Also from Javadoc of "configureEnclosingScrollPane" in JTable class:If this JTable is the viewportView of an enclosing JScrollPane(the usual situation),configure this ScrollPane by,amongst other things, installing the table's tableHeader as the columnHeaderView of the scroll pane. When a JTable is added to a JScrollPane in the usual way, using new JScrollPane(myTable), addNotify is called in the JTable (when the table is added to the viewport).JTable's addNotify method in turn calls this method, which is protected so that this default installation procedure can be overridden by a subclass.
sateesh
A: 

If the columns names and number of rows are hard-coded, I would advise you to use the JTable constructor which takes an array of columns names instead of creating a model you do not re-use:

JTable(Object[][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.

Guillaume Alvarez