JTableDemo.java

 

Download JTableDemo.java source file

// Simple JTable Demo, which uses the DefaultTableModel.
// Written 9/2005 by Wayne Pollock, Tampa Florida USA.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class JTableDemo extends JFrame
{
   JTable tbl;
   TableModel model;
   public JTableDemo()
   {
      setTitle( "JTable demo" );
      setLayout( new BorderLayout() );
      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      String[] colHeads = {
         "Time", "Monday", "Tuesday", "Wednesday",
         "Thursday", "Friday", "Saturday", "  on-line  "
      };

      String[][] data = {
         { "  8 AM  ", "", "", "", "", "", "", ""},
         { "  9 AM  ", "", "", "", "", "", "", ""},
         { " 10 AM  ", "", "", "", "", "", "", ""},
         { " 11 AM  ", "", "", "", "", "", "", ""},
         { "  Noon  ", "", "", "", "", "", "", ""},
         { "  1 PM  ", "", "", "", "", "", "", ""},
         { "  2 PM  ", "", "", "", "", "", "", ""},
         { "  3 PM  ", "", "", "", "", "", "", ""},
         { "  4 PM  ", "", "", "", "", "", "", ""},
         { "  5 PM  ", "", "", "", "", "", "", ""},
         { "  6 PM  ", "", "", "", "", "", "", ""},
         { "  7 PM  ", "", "", "", "", "", "", ""},
         { "  8 PM  ", "", "", "", "", "", "", ""},
         { "  9 PM  ", "", "", "", "", "", "", ""},
         { " 10 PM  ", "", "", "", "", "", "", ""}
      };
      
      tbl = new JTable( data, colHeads );
      tbl.setDefaultEditor( Object.class, null );
      tbl.setRowSelectionAllowed( false );
      add( new JScrollPane( tbl ), BorderLayout.CENTER );
      model = tbl.getModel();
      
      JButton addBtn = new JButton( "add..." );
      JPanel btnPanel = new JPanel();
      btnPanel.add( addBtn );
      add( btnPanel, BorderLayout.SOUTH );
      pack();
      
      addBtn.addActionListener( new ActionListener() {
         public void actionPerformed ( ActionEvent e ) {
            // JOPtionPane to get item's info...
            Item dummy = new Item( "CGS2805", 1, 9 );
            model.setValueAt( dummy.toString(),
               dummy.getHour(), dummy.getDay() );
         }
      });
   }

   public static void main ( String [] args )
   {
      JFrame f = new JTableDemo();
      f.setVisible( true );
   }
}

class Item
{
   private String label;
   private int day, hour;
   // ...
   
   public Item ( String label, int day, int hour )
   {
      this.label = label;
      this.day = day;
      this.hour = hour;
   }
   
   // ...
   
   public int getDay () { return day; }
   
   public int getHour () { return hour; }
   
   public String toString () { return label; }
}