Loren Zimmer
Loren Zimmer

Reputation: 480

Column titles not appearing in JTable

Any thoughts as to why the following code would display column titles? I have tried with and without a scollpane.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JScrollPane scrollpane = new JScrollPane(table);

contentPane.add(scrollpane, "wrap, span");

tableModel = new DefaultTableModel(new Object[]{"Name","Instrument Type","Channel","Number of Channels"},0);



table = new JTable();
table.setBounds(6, 6, 697, 172);
tableModel = new DefaultTableModel(new Object[]{"Fixture Name","Fixture Type","Fixture Channel","Number of Channels"},0);
        table.setModel(tableModel);
        contentPane.add(table);

Upvotes: 1

Views: 201

Answers (2)

Amarnath
Amarnath

Reputation: 8865

tableModel = new DefaultTableModel(new Object[]{"Fixture Name","Fixture Type","Fixture   Channel","Number of Channels"},0);
    table.setModel(tableModel);
    contentPane.add(table); // This is the place that is creating problem for you.

While adding just add the JTable to the JScrollPane and add the scrollpane to the container like the following,

    **contentPane.add(new JScrollPane(table));**

See @Dan post for why to use a JScrollPane.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347194

  1. Use a layout manager
  2. Add the scroll pane to the frame, not the table...

You're code snippet is either missing it, or you example is wrong.

JScrollPane scrollpane = new JScrollPane(table);

This either means you've already created the table, in which case, you're double creating it, or it's going to generate a NullPointerException

Your code should look more like...

table = new JTable();
tableModel = new DefaultTableModel(new Object[]{"Fixture Name","Fixture Type","Fixture Channel","Number of Channels"},0);
table.setModel(tableModel);
contentPane.add(new JScrollPane(table));

Have a look through How to use Tables for more details

Upvotes: 3

Related Questions