JTable Missing Column Headers

不羁的心 提交于 2019-12-11 10:29:35

问题


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:

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.


回答1:


Change:

mainPanel.add(inventoryTable, BorderLayout.CENTER);

To

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


来源:https://stackoverflow.com/questions/22734739/jtable-missing-column-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!