问题
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