Skeeter62889
Skeeter62889

Reputation: 95

JTable in Swing has no header

For some reason my JTable won't display the headers that are in my table model. Also I need the the table in a scroll pane and that seems to delete the whole table. This is in Java Swing.

package table;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

public class TableIcon extends JFrame{

    public TableIcon(){

    TableModel  tableModel = new TableModel();
    JTable table = new JTable(tableModel);

    JScrollPane spTable = new JScrollPane();
    spTable.add(table);
    this.add( spTable);
    this.add(table);
    }


    //spTable = new JScrollPane();
    //spTable.add(table);

      public static void main(String[] args)
        {
            TableIcon frame = new TableIcon();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        }


}

package table;

import javax.swing.table.AbstractTableModel;

/*** Class that sets up a table model for a downloaded batch***/
@SuppressWarnings("serial")
public class TableModel extends AbstractTableModel {



    public TableModel() {
        super();

    }

    @Override
    public int getRowCount() {
        return 5;
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public String getColumnName(int column) {

        if (column == 0) {
            return "Record Number";
        } else {
            return "happy";
        }
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {

        if (columnIndex == 0) 
            return rowIndex + 1;
        else 
            return 3;
    }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {

    }


    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {

        if (columnIndex == 0)
            return false;
        else
            return true;
    }

} 

Upvotes: 1

Views: 380

Answers (2)

Always Learning
Always Learning

Reputation: 5601

You should create your JScrollPane using the constructor that takes a JTable like this:

JScrollPane spTable = new JScrollPane(table);
this.add( spTable);

There is no need to call either spTable.add(table); or this.add(table); because spTable already includes table.

Upvotes: 3

kiheru
kiheru

Reputation: 6618

You should not add components to a scroll pane. Instead you set the view. That can be done easiest by using a constructor parameter:

JScrollPane spTable = new JScrollPane(table);
this.add(spTable);

Also, delete this row, the table is already in the scroll pane:

this.add(table);

Furthermore, it's better just to use a JFrame, instead of extending one. Finally, you should create the GUI in the event dispatch thread.

Upvotes: 4

Related Questions