1

Really simple question. Don't bash me please. :)

I created a table model by extending AbstractTableModel as follows:

public class InventoryTableModel extends AbstractTableModel {
    private static final String[] COLUMN_NAMES = { "On Sale", "Name", "Selling Price", "Description" };

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public int getRowCount() {
        return 0;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return COLUMN_NAMES[columnIndex];
      }    

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return null;
    }    
}

Next, I create a JTable using this table model and show it in a panel with layout BorderLayout:

JTable inventoryTable = new JTable(new InventoryTableModel());        
mainPanel.add(inventoryTable, BorderLayout.CENTER);

Note that mainPanel eventually ends up inside a scroll pane:

scrollPane.setViewportView(mainPanel);

For some reason I am not seeing the table headers. Here is all my program shows:

Missing Column Headers

(Note, the white space is where the table is.)

To make sure the table is being placed properly I modified the getRowCount method to return 1:

@Override
public int getRowCount() {
    return 1;
}

And now this is what I see:

Missing Column Headers - 1 Row

Can anyone tell me why my column headers are missing? I know it's something simple but my brain is fried and I just can't seem to figure it out.

Thank you.

Update, based on Josh M's answer I placed the table inside a scroll pane. That worked but this is how my application looks now:

Table Inside Scroll Pane

Note the vertical scroll bar.

Community
  • 1
  • 1
Jan Tacci
  • 3,131
  • 16
  • 63
  • 83

1 Answers1

3

Change:

mainPanel.add(inventoryTable, BorderLayout.CENTER);

To

mainPanel.add(new JScrollPane(inventoryTable), BorderLayout.CENTER);
Josh M
  • 11,611
  • 7
  • 39
  • 49
  • Does a JTable always have to live inside a scroll pane? Also, did you see my updated post that says mainPanel resides in a scroll pane? – Jan Tacci Mar 29 '14 at 18:07
  • 1
    It doesn't have to be in a `JScrollPane` but if you don't put it in one, you have to add the table header and the table separately. It's just easier to put it in a `JScrollPane`. Plus if your data exceeds the bounds of its container, you can scroll. – Josh M Mar 29 '14 at 18:08
  • Check out my updated post. Do you know why doing as you suggested causes the scroll pane (the outer scroll pane) to show the vertical scrollbar? – Jan Tacci Mar 29 '14 at 18:13