1

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);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Loren Zimmer
  • 482
  • 1
  • 6
  • 29

2 Answers2

3
  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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1
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.

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