Link to home
Start Free TrialLog in
Avatar of epastoor
epastoor

asked on

JTable Header

I am using a Table Model that i found to help me create a dynamic table(Based on a database).  However this model i found does not give table headers, and i cant figure out what i need to do to fix this.  I have posted the code below that they gave as an example using this table model.
Thanks!




import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
 
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      JTable table = new JTable(wineModel);
 
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it.
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; }
   public boolean getInStock() { return inStock; }
 
   public String toString() {
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
 
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses[c];
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}

Avatar of EWilliams
EWilliams

Have you run this code?
When I ran this code, I got a table with the headers:
"Name", "Vintage", "Price",and "In stock?".

These are initialized with the line:
 final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
in the WineTableModel class.
Avatar of epastoor

ASKER

yah i ran the code...i had to change the code a little because i am creating a table inside of tabs. so it is possible i messed somethign up there. i will try and clean up my actual code and post it.
package fantasybasketballleague.gui;

import fantasybasketballleague.dataStructure.*;
import fantasybasketballleague.fileData.ReadData;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
/**
 * Title:        Fantasy Basketball League
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Eric Pastoor
 * @version 1.0
 */

public class TeamRoster extends JApplet{
  private Integer teamToView;
  public JPanel p_team;
  public JFrame activeFrame;
  public ReadData readin;


  public TeamRoster(int teamNumber, ReadData dataClass) {
    teamToView=new Integer(teamNumber);
    readin=dataClass;
    p_team= new JPanel();
    TabbedPane viewRoster=new TabbedPane();
    viewRoster.init();
    p_team.add(viewRoster);
  }


class TabbedPane extends JApplet{

  JTabbedPane tabbedPane;

  public void init()
  {
    tabbedPane=new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addChangeListener(new TabbedPaneListener());


    for(int i=0; i<readin.vectorClass.ReturnNumberOfContractTypes();i++)
    {
      JPanel temppane=new JPanel();
      RosterTable temp=CreateTable(i, temppane);

      temppane.add(temp.table);
      JScrollPane scroll = new JScrollPane(temppane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

      tabbedPane.addTab(readin.vectorClass.GetContractType(i),scroll);
    }
    getContentPane().add(tabbedPane);
  }
  private RosterTable CreateTable(int contractType, JPanel pane)
  {
      RosterTable t= new RosterTable(pane, contractType);
      return t;
  }
  class TabbedPaneListener implements ChangeListener
  {
    int selectedIndex=-1;
    JTabbedPane tp;

    public void stateChanged(ChangeEvent ce)
    {
      tp= (JTabbedPane) ce.getSource();
        if(selectedIndex==-1|| selectedIndex!=tp.getSelectedIndex())
        {
          tp.setEnabledAt(tp.getSelectedIndex(),false);
          if(selectedIndex!=-1)
            tp.setEnabledAt(selectedIndex, true);
        }
        selectedIndex=tp.getSelectedIndex();
    }
  }

  class RosterTable{
    RosterModel tableModel;
    JTable table;
    public RosterTable(JPanel pane, int contractType)
    {
      tableModel = new RosterModel();
      table = new JTable(tableModel);

      // add rows to our TableModel, each row is represented as a TeamTableRoster object
      for(int i=0;i<readin.vectorClass.GetPlayerList().size();i++)
      {
        if(teamToView.equals(((Player)readin.vectorClass.GetPlayer(i)).GetTeamNumber()))
        {
          if(new Integer(contractType).equals(((Player)readin.vectorClass.GetPlayer(i)).GetContractType()))
          {
            Player copy=(Player)readin.vectorClass.GetPlayer(i);
            tableModel.addrow(new TeamTableRoster(copy));
          }
        }

      }


      }

    class TeamTableRoster
    {
      private Player player;
      public TeamTableRoster(Player rowPlayer){player=rowPlayer; }
      public String GetPositionEquivalent()
      {
          switch (player.GetPosition().intValue())
          {
            case 0: return new String("C");
            case 1: return new String("PF/C");
            case 2: return new String("PF");
            case 3: return new String("SF/PF");
            case 4: return new String("SF");
            case 5: return new String("SG/SF");
            case 6: return new String("SG");
            case 7: return new String("PG/SG");
            case 8: return new String("PG");
            default: return new String("None");
          }

      }
    }
    class RosterModel extends AbstractTableModel
    {
      // holds the strings to be displayed in the column headers of our table
      final String[] columnNames = {"First", "Last", "Position", "Salary",
                                    "Years Left", "ID#"};
      // holds the data types for all our columns
      final Class[] columnClasses = {String.class, String.class, Integer.class,
                                      Double.class, Integer.class, String.class};
      // holds our data
      final Vector data = new Vector();
      // adds a row
      public void addrow(TeamTableRoster w)
      {
        data.addElement(w);
        fireTableRowsInserted(data.size()-1, data.size()-1);
      }
      public int getColumnCount()
      {
        return columnNames.length;
      }
      public int getRowCount()
      {
        return data.size();
      }
      public String getColumnName(int col)
      {
        return columnNames[col];
      }
      public Class getColumnClass(int c)
      {
        return columnClasses[c];
      }
      public Object getValueAt(int row, int col)
      {
        TeamTableRoster teamTableRoster = (TeamTableRoster) data.elementAt(row);
        if (col == 0)      return teamTableRoster.player.GetFirstName();
        else if (col == 1) return teamTableRoster.player.GetLastName();
        else if (col == 2) return teamTableRoster.GetPositionEquivalent();
        else if (col == 3) return teamTableRoster.player.GetSalary();
        else if (col == 4) return teamTableRoster.player.GetYearsLeft();
        else if (col == 5) return teamTableRoster.player.GetIDNumber();
        else return null;
      }
      public boolean isCellEditable(int row, int col) {      return false;   }
    }
  };//end class rostertable
}//end of tabbedPane class

}

if this is difficult to follow let me know and ill try and clean it up or let you know what it is doing.
Have you run this code?
When I ran this code, I got a table with the headers:
"Name", "Vintage", "Price",and "In stock?".

These are initialized with the line:
 final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
in the WineTableModel class.
ive run my code...i have not run the other code though.  but the problem is that my code, which i thought was basically the same as the other code, still doesnt have headers.
Have you run this code?
When I ran this code, I got a table with the headers:
"Name", "Vintage", "Price",and "In stock?".

These are initialized with the line:
 final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
in the WineTableModel class.
Sorry stupid thing keeps re-entering my comment when I reload
Hello epastoor ,
    In order to get headers you need to add your Table to a ScrollPane . Without this the headers wont show. In the example you posted the Line given below adds the table to a  JScrollPane and then adds the scroll pane to the ContentPane . You have to do this to make the header visible.


JScrollPane scrollPane = new JScrollPane(table);

     // add the scroll pane to this window.
     getContentPane().add(scrollPane, BorderLayout.CENTER);


Try this.

Regards
Yaser Ansari
ok...i tried what you said...but now i lost the tabbed pane that i had.  The way it is supposed to look is to have a tabbed pane with a table inside of it.  Now i have the column headers, but tabs on the bottom.  The tables are not even showing up with the data like before.  Just the headers are there.
Here is how the code looks now.




//Code Below
package fantasybasketballleague.gui;

import fantasybasketballleague.dataStructure.*;
import fantasybasketballleague.fileData.ReadData;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
/**
 * Title:        Fantasy Basketball League
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Eric Pastoor
 * @version 1.0
 */

public class TeamRoster extends JApplet{
  private Integer teamToView;
  public JPanel p_team;
  public JFrame activeFrame;
  public ReadData readin;


  public TeamRoster(int teamNumber, ReadData dataClass) {
    teamToView=new Integer(teamNumber);
    readin=dataClass;
    p_team= new JPanel();
    TabbedPane viewRoster=new TabbedPane();
    viewRoster.init();
    p_team.add(viewRoster);
  }


class TabbedPane extends JApplet{

  JTabbedPane tabbedPane;

  public void init()
  {
    tabbedPane=new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addChangeListener(new TabbedPaneListener());


    for(int i=0; i<readin.vectorClass.ReturnNumberOfContractTypes();i++)
    {
      RosterTable temp=CreateTable(i);

      JScrollPane scroll = new JScrollPane(temp.table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

      tabbedPane.addTab(readin.vectorClass.GetContractType(i),scroll);
    }
    getContentPane().add(tabbedPane);
  }
  private RosterTable CreateTable(int contractType)
  {
      RosterTable t= new RosterTable(contractType);
      return t;
  }
  class TabbedPaneListener implements ChangeListener
  {
    int selectedIndex=-1;
    JTabbedPane tp;

    public void stateChanged(ChangeEvent ce)
    {
      tp= (JTabbedPane) ce.getSource();
        if(selectedIndex==-1|| selectedIndex!=tp.getSelectedIndex())
        {
          tp.setEnabledAt(tp.getSelectedIndex(),false);
          if(selectedIndex!=-1)
            tp.setEnabledAt(selectedIndex, true);
        }
        selectedIndex=tp.getSelectedIndex();
    }
  }

  class RosterTable{
    RosterModel tableModel;
    JTable table;
    public RosterTable(int contractType)
    {
      tableModel = new RosterModel();
      table = new JTable(tableModel);

      // add rows to our TableModel, each row is represented as a TeamTableRoster object
      for(int i=0;i<readin.vectorClass.GetPlayerList().size();i++)
      {
        if(teamToView.equals(((Player)readin.vectorClass.GetPlayer(i)).GetTeamNumber()))
        {
          if(new Integer(contractType).equals(((Player)readin.vectorClass.GetPlayer(i)).GetContractType()))
          {
            Player copy=(Player)readin.vectorClass.GetPlayer(i);
            tableModel.addrow(new TeamTableRoster(copy));
          }
        }

      }


      }

    class TeamTableRoster
    {
      private Player player;
      public TeamTableRoster(Player rowPlayer){player=rowPlayer; }
      public String GetPositionEquivalent()
      {
          switch (player.GetPosition().intValue())
          {
            case 0: return new String("C");
            case 1: return new String("PF/C");
            case 2: return new String("PF");
            case 3: return new String("SF/PF");
            case 4: return new String("SF");
            case 5: return new String("SG/SF");
            case 6: return new String("SG");
            case 7: return new String("PG/SG");
            case 8: return new String("PG");
            default: return new String("None");
          }

      }
    }
    class RosterModel extends AbstractTableModel
    {
      // holds the strings to be displayed in the column headers of our table
      final String[] columnNames = {"First", "Last", "Position", "Salary",
                                    "Years Left", "ID#"};
      // holds the data types for all our columns
      final Class[] columnClasses = {String.class, String.class, String.class,
                                      Double.class, Integer.class, String.class};
      // holds our data
      final Vector data = new Vector();
      // adds a row
      public void addrow(TeamTableRoster w)
      {
        data.addElement(w);
        fireTableRowsInserted(data.size()-1, data.size()-1);
      }
      public int getColumnCount()
      {
        return columnNames.length;
      }
      public int getRowCount()
      {
        return data.size();
      }
      public String getColumnName(int col)
      {
        return columnNames[col];
      }
      public Class getColumnClass(int c)
      {
        return columnClasses[c];
      }
      public Object getValueAt(int row, int col)
      {
        TeamTableRoster teamTableRoster = (TeamTableRoster) data.elementAt(row);
        if (col == 0)      return teamTableRoster.player.GetFirstName();
        else if (col == 1) return teamTableRoster.player.GetLastName();
        else if (col == 2) return teamTableRoster.GetPositionEquivalent();
        else if (col == 3) return teamTableRoster.player.GetSalary();
        else if (col == 4) return teamTableRoster.player.GetYearsLeft();
        else if (col == 5) return teamTableRoster.player.GetIDNumber();
        else return null;
      }
      public boolean isCellEditable(int row, int col) {      return true;   }
    }
  };//end class rostertable
}//end of tabbedPane class

}

can anyone help???
ASKER CERTIFIED SOLUTION
Avatar of doronb
doronb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks doron. im working on your code right now.
first i had to add the jscrollpane to the container so that it showed up.
and i also did not get a scroll bar so i added a piece of code when i created the scrollpane object.
that looks like
jScrollPane= new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

however the scroll pane does not move up and down the table.
heres what the code looks like now

package fantasybasketballleague.gui;

import fantasybasketballleague.dataStructure.*;
import fantasybasketballleague.fileData.ReadData;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
/**
 * Title:        Fantasy Basketball League
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Eric Pastoor
 * @version 1.0
 */

public class TeamRoster extends JApplet{
  private Integer teamToView;
  public JPanel p_team;
  public JFrame activeFrame;
  public ReadData readin;

  private JPanel jPanel;
  private JScrollPane jScrollPane;

  private Vector scrolls[][];
  private JTabbedPane tabbedPane;

  public TeamRoster(int teamNumber, ReadData dataClass) {


    jPanel = new JPanel(false);
    jScrollPane= new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jScrollPane.getViewport().add(jPanel);
    jPanel.setLayout(new BorderLayout(5,5));


    teamToView=new Integer(teamNumber);
    readin=dataClass;
    p_team= new JPanel();
    TabbedPane viewRoster=new TabbedPane();
    viewRoster.init();
    p_team.add(jScrollPane);
  }


class TabbedPane extends JApplet{

  public void init()
  {
    tabbedPane=new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addChangeListener(new TabbedPaneListener());


      int i=8;
      RosterTable temp=CreateTable(i);
      jPanel.add(temp.table, BorderLayout.CENTER);
      jScrollPane.setColumnHeaderView(temp.table.getTableHeader());

  }
  private RosterTable CreateTable(int contractType)
  {
      RosterTable t= new RosterTable(contractType);
      return t;
  }
  class TabbedPaneListener implements ChangeListener
  {
    int selectedIndex=-1;
    JTabbedPane tp;

    public void stateChanged(ChangeEvent ce)
    {
      tp= (JTabbedPane) ce.getSource();
        if(selectedIndex==-1|| selectedIndex!=tp.getSelectedIndex())
        {
          tp.setEnabledAt(tp.getSelectedIndex(),false);
          if(selectedIndex!=-1)
            tp.setEnabledAt(selectedIndex, true);
        }
        selectedIndex=tp.getSelectedIndex();
    }
  }

  class RosterTable{
    RosterModel tableModel;
    JTable table;
    public RosterTable(int contractType)
    {
      tableModel = new RosterModel();
      table = new JTable(tableModel);

      // add rows to our TableModel, each row is represented as a TeamTableRoster object
      for(int i=0;i<readin.vectorClass.GetPlayerList().size();i++)
      {
        if(teamToView.equals(((Player)readin.vectorClass.GetPlayer(i)).GetTeamNumber()))
        {
          if(new Integer(contractType).equals(((Player)readin.vectorClass.GetPlayer(i)).GetContractType()))
          {
            Player copy=(Player)readin.vectorClass.GetPlayer(i);
            tableModel.addrow(new TeamTableRoster(copy));
          }
        }

      }


      }

    class TeamTableRoster
    {
      private Player player;
      public TeamTableRoster(Player rowPlayer){player=rowPlayer; }
      public String GetPositionEquivalent()
      {
          switch (player.GetPosition().intValue())
          {
            case 0: return new String("C");
            case 1: return new String("PF/C");
            case 2: return new String("PF");
            case 3: return new String("SF/PF");
            case 4: return new String("SF");
            case 5: return new String("SG/SF");
            case 6: return new String("SG");
            case 7: return new String("PG/SG");
            case 8: return new String("PG");
            default: return new String("None");
          }

      }
    }
    class RosterModel extends AbstractTableModel
    {
      // holds the strings to be displayed in the column headers of our table
      final String[] columnNames = {"First", "Last", "Position", "Salary",
                                    "Years Left", "ID#"};
      // holds the data types for all our columns
      final Class[] columnClasses = {String.class, String.class, String.class,
                                      Double.class, Integer.class, String.class};
      // holds our data
      final Vector data = new Vector();
      // adds a row
      public void addrow(TeamTableRoster w)
      {
        data.addElement(w);
        fireTableRowsInserted(data.size()-1, data.size()-1);
      }
      public int getColumnCount()
      {
        return columnNames.length;
      }
      public int getRowCount()
      {
        return data.size();
      }
      public String getColumnName(int col)
      {
        return columnNames[col];
      }
      public Class getColumnClass(int c)
      {
        return columnClasses[c];
      }
      public Object getValueAt(int row, int col)
      {
        TeamTableRoster teamTableRoster = (TeamTableRoster) data.elementAt(row);
        if (col == 0)      return teamTableRoster.player.GetFirstName();
        else if (col == 1) return teamTableRoster.player.GetLastName();
        else if (col == 2) return teamTableRoster.GetPositionEquivalent();
        else if (col == 3) return teamTableRoster.player.GetSalary();
        else if (col == 4) return teamTableRoster.player.GetYearsLeft();
        else if (col == 5) return teamTableRoster.player.GetIDNumber();
        else return null;
      }
      public boolean isCellEditable(int row, int col) {      return true;   }
    }
  };//end class rostertable
}//end of tabbedPane class

}

in that last code snipet ive taken out the tabbedpane portion of the code to eliminate one possible error causer.  So basically the problem that i listed above the code where the scroll pane is not actually scrolling down the page is an issue but not reflective on the tabbed pane. i figure ill implement that as soon as i get this working to start with.
i also checked to make sure that there were enough elements in the pane to need to scroll up or down. and when i put more elements in the pane, it just made the pane larger than the application window.
Sorry about the confusion. My problem was that i didnt define a layout for the panel and thus everything was not showing properly. once i did that, i had no problems and even my scroll pane was working properly!

thanks so much for your help!
   
You dont need a scroll pane:

http://javaalmanac.com/egs/javax.swing.table/ShowHead.html

    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    JTableHeader header = table.getTableHeader();
   
    container.setLayout(new BorderLayout());
   
    // Add header in NORTH slot
    container.add(header, BorderLayout.NORTH);
   
    // Add table itself to CENTER slot
    container.add(table, BorderLayout.CENTER);