Search code examples
javaswingjtablejscrollpane

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);

Solution

    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