Reputation: 25
I am placing a JTable
in a JPanel
, but when I am displaying, I see the table contents but not the column names.
public class Neww extends JPanel
{
Connection conn = null;
Statement st;
DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ " ", " " },
{ " ", " " },
{ " ", " " },
{ " ", " " },
{ " ", " " },
{ " ", " " }
}, new Object[] {
"ItemName",
"No of items"
});
JTable table = new JTable(model);
TableColumn ItemName = table.getColumnModel().getColumn(0);
JComboBox comboBox = new JComboBox();
Neww()
{
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.add(table);
comboBox.addItem("Spoon");
comboBox.addItem("Plate");
comboBox.addItem("Mixer");
comboBox.addItem("Glass");
ItemName.setCellEditor(new DefaultCellEditor(comboBox));
}
}
Upvotes: 2
Views: 119
Reputation: 8865
Following statement is creating problem in your code.
this.add(table);
Use scroll pane while adding table.
add(new JScrollPane(table));
Why should we use JScrollPane
?
As stated by @OscarRyz in this comment.
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.
Edit: Also look this answer for more details.
Upvotes: 1
Reputation: 36423
1) Wrap your JTable
within JScrollPane
. Like this:
JTable table=...;
JPanel container = new JPanel();
JScrollPane jsp=new JScrollPane(table);
container.add(jsp);
2) Use getTableHeader()
and add it where needed (usually north positioned though):
...
JTableHeader header = table.getTableHeader();
JPanel container = new JPanel(new BorderLayout());
// Add header at NORTH position
container.add(header, BorderLayout.NORTH);
//Add table below header
container.add(table, BorderLayout.CENTER);
Upvotes: 2
Reputation: 109823
there are two ways
(proper of ways) have to put JTable
to the JScrollPane
, then JTableHeader
is visible
get JTableHeader
from JTable
(change JPanel
s LayoutManager
to BorderLayout
) and put to NORTH area
in JPanel
Upvotes: 3