Yamen Hejazi
Yamen Hejazi

Reputation: 11

Table with JScrollPane won't show column headers

This JTable with JScrollPane won't show the column headers.

package jTable;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Main {

    JFrame frame ;
    Main()
   {       
     frame = new JFrame() ;
     String [][] names  = {
             {"1000","yamen","develeoper"},
             {"2000","aymen","data entry"},
             {"3000","mohammed","teacher"}
             };

       String[]  header = {"ID","NAME","JOB"};     
       JTable   jtb = new JTable(names,header) ;        
       JScrollPane  s = new JScrollPane(jtb);

       jtb.setBounds(40,50,300,400);
       frame.add(jtb);

       frame.setSize(400, 500);
       frame.setVisible(true);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
   }

    public static void main(String[] args) {
        new Main();
    }
}

Upvotes: 1

Views: 426

Answers (2)

Plumel
Plumel

Reputation: 45

Try creating a TableModel with the names and headers

tableModel = new DefaultTableModel(names, headers);

And then assign the JTable this TableModel

jtb.setModel(tableModel);

And then add a new JScrollPane to the frame

frame.add(new JScrollPane(jtb));

At least, this is how I did it in my program.

Upvotes: 0

trashgod
trashgod

Reputation: 205875

The scroll pane will display the header. Having created a JScrollPane with your JTable,

JTable jtb = new JTable(names, header);
JScrollPane s = new JScrollPane(jtb);

you probably meant,

frame.add(s);

See How to Use Tables: Adding a Table to a Container for details.

table image

Upvotes: 4

Related Questions