2

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));
    }
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130

3 Answers3

3

there are two ways

  • (proper of ways) have to put JTable to the JScrollPane, then JTableHeader is visible

  • get JTableHeader from JTable (change JPanels LayoutManager to BorderLayout) and put to NORTH area in JPanel

mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

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);
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
1

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.

Community
  • 1
  • 1
Amarnath
  • 8,736
  • 10
  • 54
  • 81