简体   繁体   中英

JTable Missing Column Headers

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:

缺少列标题

(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:

缺少列标题-1行

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:

表格内部滚动窗格

Note the vertical scroll bar.

Change:

mainPanel.add(inventoryTable, BorderLayout.CENTER);

To

mainPanel.add(new JScrollPane(inventoryTable), BorderLayout.CENTER);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM