Link to home
Start Free TrialLog in
Avatar of johnmarco
johnmarco

asked on

Add JButton to the code

I know how to add a JBUTTON, I did it several times in several small projects and did not have any issue.

Can someone please help me to a simple stupid JBUTTON to the code below, it is really not important how it will be called, I just want to see a JBUTTON on this code below, I have the skills to add functionalities to the code:


 Please do not gie links, saying that check that out, I have hunders of tutorials saying how to a JBUTTON and they do work, but my try-outs on this code did not work and I already spent almost a day, Thank you

package tmanfe.spreadsheet;

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

public class SpreadSheet extends JTable {

    /**
     * Set this field to true and recompile
     * to get debug traces
     */
    public static final boolean DEBUG = true;

    private JScrollPane      _scp;
    private CellMenu         _popupMenu;
    private SpreadSheetModel _model;
    private int              _numRow;
    private int              _numCol;

    private int _editedModelRow;
    private int _editedModelCol;
   
    /*
     * GUI components used to tailored
     * the SpreadSheet.
     */
    private CellRenderer _renderer;
    private Font         _cellFont;
  //private FontMetrics  _metrics;

    // Cells selected.
    private Object [] _selection;

   /**
     * Start the spreadsheet into a JFrame.
     * @param String[] The options passed on the command
     *        line. Not used.
     */
    public static void main(String[] args) {


        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.3") < 0) {
          System.out.println("Please use Java 1.3 or above.");
        //System.exit(1);
      }

      try {
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
      } catch(Exception ex) {
        System.out.println("Can't set look and feel MetalLookAndFeel");
        System.exit(2);
      }

      JFrame frame = new JFrame("A Simple Spreadsheet");
      
      /*
       * Allows the user to exit the application
       * from the window manager's dressing.
       */
      frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) { System.exit(0); }
          });
      
      SpreadSheet sp = new SpreadSheet(40, 40);

      /**
      SheetCell[][] cells = new SheetCell[3][2];
      cells[0][0] = new SheetCell(0 , 0, "1", null);
      cells[1][0] = new SheetCell(0 , 1, "2", null);
      cells[2][0] = new SheetCell(0 , 2, "3", null);
      cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
      cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
      cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
      SpreadSheet sp = new SpreadSheet(cells);
      **/


      frame.getContentPane().add(sp.getScrollPane());
      frame.pack();
      frame.setVisible(true);
      
    }

    /**
     * Build SpreadSheet of numCol columns and numRow rows.
     *
     * @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
     *             It must be a two dimensional rectangular array. If null, the cells are
     *             automatically created.
     * @param numRow The number of rows
     * @param numCol The number of columns
     *              
     */
    private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {

        super();

      SheetCell foo[][];

      if (cells!=null)
        foo = cells;
      else {
        foo = new SheetCell[numRow][numCol];
        for (int ii=0; ii<numRow; ii++) {
          for (int jj=0; jj<numCol; jj++)
            foo[ii][jj] = new SheetCell(ii, jj);
        }
      }
        
      _numRow = numRow;
      _numCol = numCol;

      _cellFont = new Font("Times", Font.PLAIN, 20);

      // Create the JScrollPane that includes the Table
      _scp = new JScrollPane(this);

      // Create the rendeder for the cells
      _renderer = new CellRenderer();
      try {
          setDefaultRenderer(Class.forName("java.lang.Object" ), _renderer );
      } catch (ClassNotFoundException ex) {
          if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer");
      }

      _model = new SpreadSheetModel(foo, this);
      setModel(_model);

      /*
       * Tune the selection mode
       */

      // Allows row and collumn selections to exit at the same time
      setCellSelectionEnabled(true);

      setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

      getSelectionModel().addListSelectionListener( new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent ev) {

          int selRow[] = getSelectedRows();
          int selCol[] = getSelectedColumns();
            
          _selection = new Object[selRow.length*selCol.length];
            
          int indice = 0;
          for  (int r=0; r<selRow.length; r++) {
            for (int c=0; c<selCol.length; c++) {
            _selection[indice] =_model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])];
            indice++;
            }
          }
          
        }
      });

      // Create a row-header to display row numbers.
      // This row-header is made of labels whose Borders,
      // Foregrounds, Backgrounds, and Fonts must be
      // the one used for the table column headers.
      // Also ensure that the row-header labels and the table
      // rows have the same height.
      TableColumn       aColumn   = getColumnModel().getColumn(0);
      TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer();
      if (aRenderer==null) {
        System.out.println(" Aouch !");
        aColumn   = getColumnModel().getColumn(0);
        aRenderer = aColumn.getHeaderRenderer();
        if (aRenderer==null) {
          System.out.println(" Aouch Aouch !");
          System.exit(3);
        }
      }
      Component aComponent = aRenderer.getTableCellRendererComponent(this,
                                                  aColumn.getHeaderValue(),
                                                  false, false, -1, 0);
      Font  aFont       = aComponent.getFont();
      Color aBackground = aComponent.getBackground();
      Color aForeground = aComponent.getForeground();
       
      Border      border  = (Border)UIManager.getDefaults().get("TableHeader.cellBorder");
      Insets      insets  = border.getBorderInsets(tableHeader);
      FontMetrics metrics = getFontMetrics(_cellFont);
      rowHeight           = insets.bottom + metrics.getHeight() + insets.top;

      /*
       * Creating a panel to be used as the row header.
       *
       * Since I'm not using any LayoutManager,
       * a call to setPreferredSize().
       */
      JPanel pnl = new JPanel((LayoutManager)null);
      Dimension dim = new Dimension( metrics.stringWidth("999")+insets.right+insets.left,
                                rowHeight*_numRow);
      pnl.setPreferredSize(dim);

      // Adding the row header labels
      dim.height = rowHeight;
      for (int ii=0; ii<_numRow; ii++) {
        JLabel lbl = new JLabel(Integer.toString(ii+1), SwingConstants.CENTER);
        lbl.setFont(aFont);
        lbl.setBackground(aBackground);
        lbl.setForeground(aForeground);
        lbl.setBorder(border);
        lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
        pnl.add(lbl);
      }

      JViewport vp = new JViewport();
      dim.height = rowHeight*_numRow;
      vp.setViewSize(dim);
      vp.setView(pnl);
      _scp.setRowHeader(vp);

      // Set resize policy and make sure
      // the table's size is tailored
      // as soon as it gets drawn.
      setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      Dimension dimScpViewport = getPreferredScrollableViewportSize();
      if (_numRow>30) dimScpViewport.height = 30*rowHeight;
      else           dimScpViewport.height  = _numRow*rowHeight;
      if (_numCol>15)
        dimScpViewport.width = 15*getColumnModel().getTotalColumnWidth()/_numCol;
      else
        dimScpViewport.width = getColumnModel().getTotalColumnWidth();
      setPreferredScrollableViewportSize(dimScpViewport);
      resizeAndRepaint();
    }


    /**
     * Build a numRow by numColumn SpreadSheet included
     * in a JScrollPane. The associated model and the cells
     * are automatically created.
     *
     * @param numRow The number of row in the spreadsheet
     * @param numColumn The number of column in the spreadsheet
     */
    public SpreadSheet(int numRow, int numColumn) {
      this(null, numRow, numColumn);
    }


    /**
     * Build a SpreadSheet included in a JScrollPane
     * from the cells given as argument.
     *
     * @param cells[numRow][numColumn] A two dimensional rectangular
     *                                 array of cells to be used when
     *                                 creating the spreadsheet.
     */
    public SpreadSheet(SheetCell cells[][]) {
      this(cells, cells.length, cells[0].length);
    }

    /**
     * Invoked when a cell edition starts.
     * This method overrides and calls that of its super class.
     *
     * @param int The row to be edited
     * @param int The column to be edited
     * @param EventObject The firing event
     * @return boolean false if for any reason the cell cannot be edited.
     */
    public boolean editCellAt( int row, int column, EventObject ev) {

      if (_editedModelRow != -1)
      _model.setDisplayMode(_editedModelRow, _editedModelCol);

      _editedModelRow = row;
      _editedModelCol = convertColumnIndexToModel(column);

      _model.setEditMode(row, convertColumnIndexToModel(column));
      return super.editCellAt(row, column, ev);

    }


    /**
     * Invoked by the cell editor when a cell edition stops.
     * This method override and calls that of its super class.
     *
     */
    public void editingStopped(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingStopped(ev);
    }
   

    /**
     * Invoked by the cell editor when a cell edition is cancelled.
     * This method override and calls that of its super class.
     *
     */
    public void editingCanceled(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingCanceled(ev);
    }

    protected JScrollPane getScrollPane() { return _scp; }

    public void processMouseEvent(MouseEvent ev) {

      int type      = ev.getID();
      int modifiers = ev.getModifiers();

      if ( (type==MouseEvent.MOUSE_RELEASED) && (modifiers==InputEvent.BUTTON3_MASK) ) {

          if (_selection!=null) {
            if (_popupMenu==null) _popupMenu = new CellMenu(this);
        
            if (_popupMenu.isVisible())
            _popupMenu.setVisible(false);
            else {
            _popupMenu.setTargetCells(_selection);
            Point p = getLocationOnScreen();
            _popupMenu.setLocation(p.x+ev.getX()+1, p.y+ev.getY()+1);
            _popupMenu.setVisible(true);
            }
          }
          
      }
      super.processMouseEvent(ev);
    }
 
    protected void release() { _model = null; }
   
    public void setVisible(boolean flag) { _scp.setVisible(flag); }

   
    /*
     * This class is used to customize the cells rendering.
     */
    public class CellRenderer extends JLabel implements TableCellRenderer  {

      private LineBorder  _selectBorder;
      private EmptyBorder _emptyBorder;
      private Dimension   _dim;

      public CellRenderer() {
      super();
      _emptyBorder  = new EmptyBorder(1, 2, 1, 2);
      _selectBorder = new LineBorder(Color.red);
      setOpaque(true);
      setHorizontalAlignment(SwingConstants.CENTER);
      _dim = new Dimension();
      _dim.height = 22;
      _dim.width  = 100;
      setSize(_dim);
      };

      /**
       *
       * Method defining the renderer to be used
       * when drawing the cells.
       *
       */
      public Component getTableCellRendererComponent (JTable table, Object value,
                                          boolean isSelected,
                                          boolean hasFocus,
                                          int row, int column) {

      SheetCell sc = (SheetCell)value;

      setFont(_cellFont);
      setText(sc.toString());
      setForeground(sc.foreground);
      setBackground(sc.background);

      if (isSelected) {
        setBorder(_selectBorder);
        setToolTipText("Right-click to change the cell's colors.");
        
      } else {
        setBorder(_emptyBorder);
        setToolTipText("Single-Click to select a cell, " +
                   "double-click to edit.");
      }

      return this;

      }
      
    }

}
Avatar of rama_krishna580
rama_krishna580
Flag of United States of America image

Hi,

checkout here..
http://www.jroller.com/page/dhall/20050825

/**
 * This simple application creates a GUI for a spreadsheet application.
 */

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

public class Spreadsheet implements ActionListener {
    CellEditor editor;
    JButton recomputeButton;

    public static Border cellNormalBorder;
    public static Border cellSelectedBorder;
    public static Dimension cellPreferredSize = new Dimension(76, 12);

    public static final int ROWS = 25;
    public static final int COLUMNS = 10;
    public static final String[] COLUMN_LETTER = {
      "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };

    /**
     * Create a spreadsheet.
     */
    public Spreadsheet() {
        // Create and set up the window.
        JFrame mainFrame = new JFrame("Spreadsheet in Java");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Create and set up the above panel.  This panel contains the
      // cell editor, and the recomputation button.
      JPanel abovePanel = new JPanel();
      abovePanel.setLayout(new BoxLayout(abovePanel, BoxLayout.LINE_AXIS));

      editor = new CellEditor();
      recomputeButton = new JButton("Recompute");
      recomputeButton.addActionListener(this);

      abovePanel.add(editor);
      abovePanel.add(Box.createHorizontalGlue());
      abovePanel.add(recomputeButton);

        // Create and set up the panel containing the cells.  The
        // topmost row contains column labels, and the leftmost column
        // contain row labels.
        JPanel cellsPanel = new JPanel(new GridLayout(ROWS+1, COLUMNS+1));

      // Make the first row.
      cellsPanel.add(newHeader(""));
      for (int col = 1; col <= COLUMNS; col++)
          cellsPanel.add(newHeader(COLUMN_LETTER[col-1]));

      // Make the other rows.
      for (int row = 1; row <= ROWS; row++) {
          cellsPanel.add(newHeader(Integer.toString(row)));
          for (int col = 1; col <= COLUMNS; col++)
            cellsPanel.add(new Cell(col, row, editor));
      }

        // Add the panels to the main window.
      mainFrame.getContentPane().add(abovePanel, BorderLayout.PAGE_START);
        mainFrame.getContentPane().add(cellsPanel, BorderLayout.CENTER);

        // Display the window.
        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    /**
     * Create a row or column header.
     */
    private JComponent newHeader(String text) {
      JLabel header = new JLabel(text, SwingConstants.CENTER);
      header.setBorder(cellNormalBorder);
      return header;
    }

    /**
     * This is called when the user clicks on button "Recompute".
     */
    public void actionPerformed(ActionEvent event) {
      // currently forces the editor to write back its current cell.
      editor.validate();
    }

    /**
     * Create the GUI and show it.  For thread safety, this method
     * should be invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        // Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

      // Initialise cellNormalBorder and cellSelectedBorder.
      Border thinline = BorderFactory.createLineBorder(Color.black);
      Border thinspace = BorderFactory.createEmptyBorder(2, 2, 2, 2);
      cellNormalBorder = BorderFactory.createCompoundBorder(thinline,
                                                thinspace);
      cellSelectedBorder = BorderFactory.createMatteBorder(3, 3, 3, 3,
                                               Color.black);

      // Create an instance of Spreadsheet
        Spreadsheet ss = new Spreadsheet();
    }

    /**
     * This is where the application starts.
     */
    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread: creating
        // and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

R.K
Avatar of johnmarco
johnmarco

ASKER

Please adjust the JButton in my code, if you can not do it, please do not respond anything or post anything.

Apply the JBUTTON code in my code, do not come with completely another code,

Cheers
Avatar of Curtis Shull
Knowing WHERE you want the JButton would really help (unless you said the location and I missed it)
In any case look at lines 28, 224-242 and 417-448 Hope this Helps!!!
=================================================================================
package tmanfe.spreadsheet;

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

public class SpreadSheet extends JTable {

    /**
     * Set this field to true and recompile
     * to get debug traces
     */
    public static final boolean DEBUG = true;

    private JScrollPane      _scp;
    private CellMenu         _popupMenu;
    private SpreadSheetModel _model;
    private int              _numRow;
    private int              _numCol;

    private int _editedModelRow;
    private int _editedModelCol;
   
   // Declare your JButton to allow some interaction
   private JButton yourFileJButton;
   
    /*
     * GUI components used to tailored
     * the SpreadSheet.
     */
    private CellRenderer _renderer;
    private Font         _cellFont;
  //private FontMetrics  _metrics;

    // Cells selected.
    private Object [] _selection;

   /**
     * Start the spreadsheet into a JFrame.
     * @param String[] The options passed on the command
     *        line. Not used.
     */
    public static void main(String[] args) {


        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.3") < 0) {
          System.out.println("Please use Java 1.3 or above.");
       //System.exit(1);
     }

     try {
       UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     } catch(Exception ex) {
       System.out.println("Can't set look and feel MetalLookAndFeel");
       System.exit(2);
     }

     JFrame frame = new JFrame("A Simple Spreadsheet");
     
     /*
      * Allows the user to exit the application
      * from the window manager's dressing.
      */
     frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) { System.exit(0); }
         });
     
     SpreadSheet sp = new SpreadSheet(40, 40);

     /**
     SheetCell[][] cells = new SheetCell[3][2];
     cells[0][0] = new SheetCell(0 , 0, "1", null);
     cells[1][0] = new SheetCell(0 , 1, "2", null);
     cells[2][0] = new SheetCell(0 , 2, "3", null);
     cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
     cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
     cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
     SpreadSheet sp = new SpreadSheet(cells);
     **/


     frame.getContentPane().add(sp.getScrollPane());
     frame.pack();
     frame.setVisible(true);
     
    }

    /**
     * Build SpreadSheet of numCol columns and numRow rows.
     *
     * @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
     *             It must be a two dimensional rectangular array. If null, the cells are
     *             automatically created.
     * @param numRow The number of rows
     * @param numCol The number of columns
     *              
     */
    private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {

        super();

     SheetCell foo[][];

     if (cells!=null)
       foo = cells;
     else {
       foo = new SheetCell[numRow][numCol];
       for (int ii=0; ii<numRow; ii++) {
         for (int jj=0; jj<numCol; jj++)
           foo[ii][jj] = new SheetCell(ii, jj);
       }
     }
       
     _numRow = numRow;
     _numCol = numCol;

     _cellFont = new Font("Times", Font.PLAIN, 20);

     // Create the JScrollPane that includes the Table
     _scp = new JScrollPane(this);

     // Create the rendeder for the cells
     _renderer = new CellRenderer();
     try {
         setDefaultRenderer(Class.forName("java.lang.Object" ), _renderer );
     } catch (ClassNotFoundException ex) {
         if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer");
     }

     _model = new SpreadSheetModel(foo, this);
     setModel(_model);

     /*
      * Tune the selection mode
      */

     // Allows row and collumn selections to exit at the same time
     setCellSelectionEnabled(true);

     setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

     getSelectionModel().addListSelectionListener( new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent ev) {

         int selRow[] = getSelectedRows();
         int selCol[] = getSelectedColumns();
           
         _selection = new Object[selRow.length*selCol.length];
           
         int indice = 0;
         for  (int r=0; r<selRow.length; r++) {
           for (int c=0; c<selCol.length; c++) {
          _selection[indice] =_model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])];
          indice++;
           }
         }
         
       }
     });

     // Create a row-header to display row numbers.
     // This row-header is made of labels whose Borders,
     // Foregrounds, Backgrounds, and Fonts must be
     // the one used for the table column headers.
     // Also ensure that the row-header labels and the table
     // rows have the same height.
     TableColumn       aColumn   = getColumnModel().getColumn(0);
     TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer();
     if (aRenderer==null) {
       System.out.println(" Aouch !");
       aColumn   = getColumnModel().getColumn(0);
       aRenderer = aColumn.getHeaderRenderer();
       if (aRenderer==null) {
         System.out.println(" Aouch Aouch !");
         System.exit(3);
       }
     }
     Component aComponent = aRenderer.getTableCellRendererComponent(this,
                                          aColumn.getHeaderValue(),
                                          false, false, -1, 0);
     Font  aFont       = aComponent.getFont();
     Color aBackground = aComponent.getBackground();
     Color aForeground = aComponent.getForeground();
       
     Border      border  = (Border)UIManager.getDefaults().get("TableHeader.cellBorder");
     Insets      insets  = border.getBorderInsets(tableHeader);
     FontMetrics metrics = getFontMetrics(_cellFont);
     rowHeight           = insets.bottom + metrics.getHeight() + insets.top;

     /*
      * Creating a panel to be used as the row header.
      *
      * Since I'm not using any LayoutManager,
      * a call to setPreferredSize().
      */
     JPanel pnl = new JPanel((LayoutManager)null);
     Dimension dim = new Dimension( metrics.stringWidth("999")+insets.right+insets.left,
                           rowHeight*_numRow);
     pnl.setPreferredSize(dim);

     // Adding the row header labels
     dim.height = rowHeight;
     for (int ii=0; ii<_numRow; ii++) {
       JLabel lbl = new JLabel(Integer.toString(ii+1), SwingConstants.CENTER);
       lbl.setFont(aFont);
       lbl.setBackground(aBackground);
       lbl.setForeground(aForeground);
       lbl.setBorder(border);
       lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
       pnl.add(lbl);
     }

     JViewport vp = new JViewport();
     dim.height = rowHeight*_numRow;
     vp.setViewSize(dim);
     vp.setView(pnl);
     _scp.setRowHeader(vp);
     
           // This sets up yourFileJButton
           // Not Sure WHERE you wanted it but you place the block where you want
      yourFileJButton = new JButton();
      yourFileJButton.setBounds( 5, 600, 130, 40 );
      yourFileJButton.setText( "your button" );
      contentPane.add( yourFileJButton );
      yourFileJButton.addActionListener(

         new ActionListener() // anonymous inner class
         {
            // event handler called when yourFileJButton is clicked
            public void actionPerformed( ActionEvent event )
            {
               yourFileJButtonActionPerformed( event );
            }

         } // end anonymous inner class

      ); // end call to addActionListener
     
     // Set resize policy and make sure
     // the table's size is tailored
     // as soon as it gets drawn.
     setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     Dimension dimScpViewport = getPreferredScrollableViewportSize();
     if (_numRow>30) dimScpViewport.height = 30*rowHeight;
     else           dimScpViewport.height  = _numRow*rowHeight;
     if (_numCol>15)
       dimScpViewport.width = 15*getColumnModel().getTotalColumnWidth()/_numCol;
     else
       dimScpViewport.width = getColumnModel().getTotalColumnWidth();
     setPreferredScrollableViewportSize(dimScpViewport);
     resizeAndRepaint();
    }


    /**
     * Build a numRow by numColumn SpreadSheet included
     * in a JScrollPane. The associated model and the cells
     * are automatically created.
     *
     * @param numRow The number of row in the spreadsheet
     * @param numColumn The number of column in the spreadsheet
     */
    public SpreadSheet(int numRow, int numColumn) {
      this(null, numRow, numColumn);
    }


    /**
     * Build a SpreadSheet included in a JScrollPane
     * from the cells given as argument.
     *
     * @param cells[numRow][numColumn] A two dimensional rectangular
     *                                 array of cells to be used when
     *                                 creating the spreadsheet.
     */
    public SpreadSheet(SheetCell cells[][]) {
      this(cells, cells.length, cells[0].length);
    }

    /**
     * Invoked when a cell edition starts.
     * This method overrides and calls that of its super class.
     *
     * @param int The row to be edited
     * @param int The column to be edited
     * @param EventObject The firing event
     * @return boolean false if for any reason the cell cannot be edited.
     */
    public boolean editCellAt( int row, int column, EventObject ev) {

      if (_editedModelRow != -1)
     _model.setDisplayMode(_editedModelRow, _editedModelCol);

      _editedModelRow = row;
      _editedModelCol = convertColumnIndexToModel(column);

      _model.setEditMode(row, convertColumnIndexToModel(column));
      return super.editCellAt(row, column, ev);

    }


    /**
     * Invoked by the cell editor when a cell edition stops.
     * This method override and calls that of its super class.
     *
     */
    public void editingStopped(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingStopped(ev);
    }
   

    /**
     * Invoked by the cell editor when a cell edition is cancelled.
     * This method override and calls that of its super class.
     *
     */
    public void editingCanceled(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingCanceled(ev);
    }

    protected JScrollPane getScrollPane() { return _scp; }

    public void processMouseEvent(MouseEvent ev) {

     int type      = ev.getID();
     int modifiers = ev.getModifiers();

     if ( (type==MouseEvent.MOUSE_RELEASED) && (modifiers==InputEvent.BUTTON3_MASK) ) {

         if (_selection!=null) {
           if (_popupMenu==null) _popupMenu = new CellMenu(this);
       
           if (_popupMenu.isVisible())
          _popupMenu.setVisible(false);
           else {
          _popupMenu.setTargetCells(_selection);
          Point p = getLocationOnScreen();
          _popupMenu.setLocation(p.x+ev.getX()+1, p.y+ev.getY()+1);
          _popupMenu.setVisible(true);
          }
         }
         
     }
     super.processMouseEvent(ev);
    }
 
    protected void release() { _model = null; }
   
    public void setVisible(boolean flag) { _scp.setVisible(flag); }

   
    /*
     * This class is used to customize the cells rendering.
     */
    public class CellRenderer extends JLabel implements TableCellRenderer  {

      private LineBorder  _selectBorder;
      private EmptyBorder _emptyBorder;
      private Dimension   _dim;

      public CellRenderer() {
     super();
     _emptyBorder  = new EmptyBorder(1, 2, 1, 2);
     _selectBorder = new LineBorder(Color.red);
     setOpaque(true);
     setHorizontalAlignment(SwingConstants.CENTER);
     _dim = new Dimension();
     _dim.height = 22;
     _dim.width  = 100;
     setSize(_dim);
      };

      /**
       *
       * Method defining the renderer to be used
       * when drawing the cells.
       *
       */
      public Component getTableCellRendererComponent (JTable table, Object value,
                                    boolean isSelected,
                                    boolean hasFocus,
                                    int row, int column) {

     SheetCell sc = (SheetCell)value;

     setFont(_cellFont);
     setText(sc.toString());
     setForeground(sc.foreground);
     setBackground(sc.background);

     if (isSelected) {
       setBorder(_selectBorder);
       setToolTipText("Right-click to change the cell's colors.");
       
     } else {
       setBorder(_emptyBorder);
       setToolTipText("Single-Click to select a cell, " +
                "double-click to edit.");
     }

     return this;

      }
     
    }

}

/*   // Then you could use a method for the button
 *   // You said you already knew how to do this
 *   // But I placed an example here anyway (commented out)
 *
 *
   private void openFileJButtonActionPerformed( ActionEvent event )
   {
         
         // Method action to try here
         try
         {
            // Something
           
            // change state of JButton if you want
            yourFileJButton.setEnabled( false );
      ;
           
         }
         catch ( IOException exception )
         {
            JOptionPane.showMessageDialog(null,
            "Sorry there is problem with something",
            "Blah Blah Blah something isn't right",JOptionPane.INFORMATION_MESSAGE);

         }

       // end open file

      // reset JButton to initial state
      resetUserInput();

   } // end method yourFileJButtonActionPerformed*/
The location of the button is not that important, it can on the top or at the bottom.

When I run your code, I get an error message at these 2 lines:

contentPane.add( yourFileJButton );

yourFileJButtonActionPerformed( event );

Please correct
Exception in thread "main" java.lang.NullPointerException
      at tmanfe.spreadsheet.SpreadSheet.<init>(SpreadSheet.java:232)
      at tmanfe.spreadsheet.SpreadSheet.<init>(SpreadSheet.java:272)
      at tmanfe.spreadsheet.SpreadSheet.main(SpreadSheet.java:76)

Did you try running it? Please modify and adjust and let it run, thanks.
This compiled fine for me (I did have to make some changes-created specific class and interface method for the content pane)
Remember there is an example of the button usage at the bottom but again you SAID you were well versed with skillz to implement your buttons!
The interface method can be called from the event thread if need be.
Hope this helps!
===============================================================================================
package tmanfe.spreadsheet;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;

public class SpreadSheet extends JTable {

    /**
     * Set this field to true and recompile
     * to get debug traces
     */
    public static final boolean DEBUG = true;

    private JScrollPane      _scp;
    private CellMenu         _popupMenu;
    private SpreadSheetModel _model;
    private int              _numRow;
    private int              _numCol;

    private int _editedModelRow;
    private int _editedModelCol;
   
    /*
     * GUI components used to tailored
     * the SpreadSheet.
     */
    private CellRenderer _renderer;
    private Font         _cellFont;
  //private FontMetrics  _metrics;

    // Cells selected.
    private Object [] _selection;

   /**
     * Start the spreadsheet into a JFrame.
     * @param String[] The options passed on the command
     *        line. Not used.
     */
    public static void main(String[] args) {


        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.3") < 0) {
          System.out.println("Please use Java 1.3 or above.");
       //System.exit(1);
     }

     try {
       UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     } catch(Exception ex) {
       System.out.println("Can't set look and feel MetalLookAndFeel");
       System.exit(2);
     }

     JFrame frame = new JFrame("A Simple Spreadsheet");
     
     /*
      * Allows the user to exit the application
      * from the window manager's dressing.
      */
     frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) { System.exit(0); }
         });
     
     SpreadSheet sp = new SpreadSheet(40, 40);

     /**
     SheetCell[][] cells = new SheetCell[3][2];
     cells[0][0] = new SheetCell(0 , 0, "1", null);
     cells[1][0] = new SheetCell(0 , 1, "2", null);
     cells[2][0] = new SheetCell(0 , 2, "3", null);
     cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
     cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
     cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
     SpreadSheet sp = new SpreadSheet(cells);
     **/


     frame.getContentPane().add(sp.getScrollPane());
     frame.pack();
     frame.setVisible(true);
     
    }

    /**
     * Build SpreadSheet of numCol columns and numRow rows.
     *
     * @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
     *             It must be a two dimensional rectangular array. If null, the cells are
     *             automatically created.
     * @param numRow The number of rows
     * @param numCol The number of columns
     *              
     */
    private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {

        super();

     SheetCell foo[][];

     if (cells!=null)
       foo = cells;
     else {
       foo = new SheetCell[numRow][numCol];
       for (int ii=0; ii<numRow; ii++) {
         for (int jj=0; jj<numCol; jj++)
           foo[ii][jj] = new SheetCell(ii, jj);
       }
     }
       
     _numRow = numRow;
     _numCol = numCol;

     _cellFont = new Font("Times", Font.PLAIN, 20);

     // Create the JScrollPane that includes the Table
     _scp = new JScrollPane(this);

     // Create the rendeder for the cells
     _renderer = new CellRenderer();
     try {
         setDefaultRenderer(Class.forName("java.lang.Object" ), _renderer );
     } catch (ClassNotFoundException ex) {
         if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer");
     }

     _model = new SpreadSheetModel(foo, this);
     setModel(_model);

     /*
      * Tune the selection mode
      */

     // Allows row and collumn selections to exit at the same time
     setCellSelectionEnabled(true);

     setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

     getSelectionModel().addListSelectionListener( new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent ev) {

         int selRow[] = getSelectedRows();
         int selCol[] = getSelectedColumns();
           
         _selection = new Object[selRow.length*selCol.length];
           
         int indice = 0;
         for  (int r=0; r<selRow.length; r++) {
           for (int c=0; c<selCol.length; c++) {
          _selection[indice] =_model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])];
          indice++;
           }
         }
         
       }
     });

     // Create a row-header to display row numbers.
     // This row-header is made of labels whose Borders,
     // Foregrounds, Backgrounds, and Fonts must be
     // the one used for the table column headers.
     // Also ensure that the row-header labels and the table
     // rows have the same height.
     TableColumn       aColumn   = getColumnModel().getColumn(0);
     TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer();
     if (aRenderer==null) {
       System.out.println(" Aouch !");
       aColumn   = getColumnModel().getColumn(0);
       aRenderer = aColumn.getHeaderRenderer();
       if (aRenderer==null) {
         System.out.println(" Aouch Aouch !");
         System.exit(3);
       }
     }
     Component aComponent = aRenderer.getTableCellRendererComponent(this,
                                          aColumn.getHeaderValue(),
                                          false, false, -1, 0);
     Font  aFont       = aComponent.getFont();
     Color aBackground = aComponent.getBackground();
     Color aForeground = aComponent.getForeground();
       
     Border      border  = (Border)UIManager.getDefaults().get("TableHeader.cellBorder");
     Insets      insets  = border.getBorderInsets(tableHeader);
     FontMetrics metrics = getFontMetrics(_cellFont);
     rowHeight           = insets.bottom + metrics.getHeight() + insets.top;

     /*
      * Creating a panel to be used as the row header.
      *
      * Since I'm not using any LayoutManager,
      * a call to setPreferredSize().
      */
     JPanel pnl = new JPanel((LayoutManager)null);
     Dimension dim = new Dimension( metrics.stringWidth("999")+insets.right+insets.left,
                           rowHeight*_numRow);
     pnl.setPreferredSize(dim);

     // Adding the row header labels
     dim.height = rowHeight;
     for (int ii=0; ii<_numRow; ii++) {
       JLabel lbl = new JLabel(Integer.toString(ii+1), SwingConstants.CENTER);
       lbl.setFont(aFont);
       lbl.setBackground(aBackground);
       lbl.setForeground(aForeground);
       lbl.setBorder(border);
       lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
       pnl.add(lbl);
     }

     JViewport vp = new JViewport();
     dim.height = rowHeight*_numRow;
     vp.setViewSize(dim);
     vp.setView(pnl);
     _scp.setRowHeader(vp);
     
     // create and position GUI components; register event handlers
   
   class  ExampleButton extends JFrame{
   
   // Declare your JButton to allow some interaction
   private JButton yourFileJButton;
   
   private void createUserInterface()
   {
      // get content pane for attaching GUI components
      Container contentPane = getContentPane();

      // enable explicit positioning of GUI components
      contentPane.setLayout( null );

   
      // set up yourFileJButton
      yourFileJButton = new JButton();
      yourFileJButton.setBounds( 5, 600, 130, 40 );
      yourFileJButton.setText( "your button" );
      contentPane.add( yourFileJButton );
      yourFileJButton.addActionListener(

         new ActionListener() // anonymous inner class
         {
            // event handler called when yourFileJButton is clicked
            public void actionPerformed( ActionEvent event )
            {
               //yourFileJButtonActionPerformed( event );
            }

         } // end anonymous inner class

      ); // end call to addActionListener

   } // end method createUserInterface
     
   }
     // Set resize policy and make sure
     // the table's size is tailored
     // as soon as it gets drawn.
     setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     Dimension dimScpViewport = getPreferredScrollableViewportSize();
     if (_numRow>30) dimScpViewport.height = 30*rowHeight;
     else           dimScpViewport.height  = _numRow*rowHeight;
     if (_numCol>15)
       dimScpViewport.width = 15*getColumnModel().getTotalColumnWidth()/_numCol;
     else
       dimScpViewport.width = getColumnModel().getTotalColumnWidth();
     setPreferredScrollableViewportSize(dimScpViewport);
     resizeAndRepaint();
    }


    /**
     * Build a numRow by numColumn SpreadSheet included
     * in a JScrollPane. The associated model and the cells
     * are automatically created.
     *
     * @param numRow The number of row in the spreadsheet
     * @param numColumn The number of column in the spreadsheet
     */
    public SpreadSheet(int numRow, int numColumn) {
      this(null, numRow, numColumn);
    }


    /**
     * Build a SpreadSheet included in a JScrollPane
     * from the cells given as argument.
     *
     * @param cells[numRow][numColumn] A two dimensional rectangular
     *                                 array of cells to be used when
     *                                 creating the spreadsheet.
     */
    public SpreadSheet(SheetCell cells[][]) {
      this(cells, cells.length, cells[0].length);
    }

    /**
     * Invoked when a cell edition starts.
     * This method overrides and calls that of its super class.
     *
     * @param int The row to be edited
     * @param int The column to be edited
     * @param EventObject The firing event
     * @return boolean false if for any reason the cell cannot be edited.
     */
    public boolean editCellAt( int row, int column, EventObject ev) {

      if (_editedModelRow != -1)
     _model.setDisplayMode(_editedModelRow, _editedModelCol);

      _editedModelRow = row;
      _editedModelCol = convertColumnIndexToModel(column);

      _model.setEditMode(row, convertColumnIndexToModel(column));
      return super.editCellAt(row, column, ev);

    }


    /**
     * Invoked by the cell editor when a cell edition stops.
     * This method override and calls that of its super class.
     *
     */
    public void editingStopped(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingStopped(ev);
    }
   

    /**
     * Invoked by the cell editor when a cell edition is cancelled.
     * This method override and calls that of its super class.
     *
     */
    public void editingCanceled(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingCanceled(ev);
    }

    protected JScrollPane getScrollPane() { return _scp; }

    public void processMouseEvent(MouseEvent ev) {

     int type      = ev.getID();
     int modifiers = ev.getModifiers();

     if ( (type==MouseEvent.MOUSE_RELEASED) && (modifiers==InputEvent.BUTTON3_MASK) ) {

         if (_selection!=null) {
           if (_popupMenu==null) _popupMenu = new CellMenu(this);
       
           if (_popupMenu.isVisible())
          _popupMenu.setVisible(false);
           else {
          _popupMenu.setTargetCells(_selection);
          Point p = getLocationOnScreen();
          _popupMenu.setLocation(p.x+ev.getX()+1, p.y+ev.getY()+1);
          _popupMenu.setVisible(true);
          }
         }
         
     }
     super.processMouseEvent(ev);
    }
 
    protected void release() { _model = null; }
   
    public void setVisible(boolean flag) { _scp.setVisible(flag); }

   
    /*
     * This class is used to customize the cells rendering.
     */
    public class CellRenderer extends JLabel implements TableCellRenderer  {

      private LineBorder  _selectBorder;
      private EmptyBorder _emptyBorder;
      private Dimension   _dim;

      public CellRenderer() {
     super();
     _emptyBorder  = new EmptyBorder(1, 2, 1, 2);
     _selectBorder = new LineBorder(Color.red);
     setOpaque(true);
     setHorizontalAlignment(SwingConstants.CENTER);
     _dim = new Dimension();
     _dim.height = 22;
     _dim.width  = 100;
     setSize(_dim);
      };

      /**
       *
       * Method defining the renderer to be used
       * when drawing the cells.
       *
       */
      public Component getTableCellRendererComponent (JTable table, Object value,
                                    boolean isSelected,
                                    boolean hasFocus,
                                    int row, int column) {

     SheetCell sc = (SheetCell)value;

     setFont(_cellFont);
     setText(sc.toString());
     setForeground(sc.foreground);
     setBackground(sc.background);

     if (isSelected) {
       setBorder(_selectBorder);
       setToolTipText("Right-click to change the cell's colors.");
       
     } else {
       setBorder(_emptyBorder);
       setToolTipText("Single-Click to select a cell, " +
                "double-click to edit.");
     }

     return this;

      }
     
    }

}

/*   // Then you could use a method for the button
 *   // You said you already knew how to do this
 *   // But I placed an example here anyway (commented out)
 *
 *
   private void openFileJButtonActionPerformed( ActionEvent event )
   {
         
         // Method action to try here
         try
         {
            // Something
           
            // change state of JButton if you want
            yourFileJButton.setEnabled( false );
      ;
           
         }
         catch ( IOException exception )
         {
            JOptionPane.showMessageDialog(null,
            "Sorry there is problem with something",
            "Blah Blah Blah something isn't right",JOptionPane.INFORMATION_MESSAGE);

         }

       // end open file

      // reset JButton to initial states
      resetUserInput();

   } // end method yourFileJButtonActionPerformed*/
Yep, you are right, it compiled without any problem. But when I run, I can not see any button anywhere. That was my problem and that is why I could not figure it out. Do you think that the cause is not using "Layout", that is really wierd. Heeelp !!!
Ah I C now what you REALLY need. Didn't quite UNDERSTAND the scope of what you wanted just thought you wanted to see if the JButton COULD be added period.

Ok.. here's the deal.
What you have to do is to provide a TableCellRenderer implementation if you want to display buttons in the JTable. The TableCellRenderer interface contains only one method, getTableCellRendererComponent(...), which returns a java.awt.Component that knows how to draw the contents of a specific cell- this is required so that you can SEE the button!

I'll post some code in a fe minutes that demonstrates this (with YOUR CODE).
Before we get into renderers try this!
=======================================================================================
package tmanfe.spreadsheet;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;

public class SpreadSheet extends JTable {

    /**
     * Set this field to true and recompile
     * to get debug traces
     */
    public static final boolean DEBUG = true;

    private JScrollPane      _scp;
    private CellMenu         _popupMenu;
    private SpreadSheetModel _model;
    private int              _numRow;
    private int              _numCol;

    private int _editedModelRow;
    private int _editedModelCol;
   
    /*
     * GUI components used to tailored
     * the SpreadSheet.
     */
    private CellRenderer _renderer;
    private Font         _cellFont;
  //private FontMetrics  _metrics;

    // Cells selected.
    private Object [] _selection;

   /**
     * Start the spreadsheet into a JFrame.
     * @param String[] The options passed on the command
     *        line. Not used.
     */
    public static void main(String[] args) {


        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.3") < 0) {
          System.out.println("Please use Java 1.3 or above.");
       //System.exit(1);
     }

     try {
       UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     } catch(Exception ex) {
       System.out.println("Can't set look and feel MetalLookAndFeel");
       System.exit(2);
     }

     JFrame frame = new JFrame("A Simple Spreadsheet");
     
     /*
      * Allows the user to exit the application
      * from the window manager's dressing.
      */
     frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) { System.exit(0); }
         });
     
     SpreadSheet sp = new SpreadSheet(40, 40);

     /**
     SheetCell[][] cells = new SheetCell[3][2];
     cells[0][0] = new SheetCell(0 , 0, "1", null);
     cells[1][0] = new SheetCell(0 , 1, "2", null);
     cells[2][0] = new SheetCell(0 , 2, "3", null);
     cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
     cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
     cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
     SpreadSheet sp = new SpreadSheet(cells);
     **/


     frame.getContentPane().add(sp.getScrollPane());
     frame.pack();
     frame.setVisible(true);
     
    }

    /**
     * Build SpreadSheet of numCol columns and numRow rows.
     *
     * @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
     *             It must be a two dimensional rectangular array. If null, the cells are
     *             automatically created.
     * @param numRow The number of rows
     * @param numCol The number of columns
     *              
     */
    private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {

        super();

     SheetCell foo[][];

     if (cells!=null)
       foo = cells;
     else {
       foo = new SheetCell[numRow][numCol];
       for (int ii=0; ii<numRow; ii++) {
         for (int jj=0; jj<numCol; jj++)
           foo[ii][jj] = new SheetCell(ii, jj);
       }
     }
       
     _numRow = numRow;
     _numCol = numCol;

     _cellFont = new Font("Times", Font.PLAIN, 20);

     // Create the JScrollPane that includes the Table
     _scp = new JScrollPane(this);

     // Create the rendeder for the cells
     _renderer = new CellRenderer();
     try {
         setDefaultRenderer(Class.forName("java.lang.Object" ), _renderer );
     } catch (ClassNotFoundException ex) {
         if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer");
     }

     _model = new SpreadSheetModel(foo, this);
     setModel(_model);

     /*
      * Tune the selection mode
      */

     // Allows row and collumn selections to exit at the same time
     setCellSelectionEnabled(true);

     setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

     getSelectionModel().addListSelectionListener( new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent ev) {

         int selRow[] = getSelectedRows();
         int selCol[] = getSelectedColumns();
           
         _selection = new Object[selRow.length*selCol.length];
           
         int indice = 0;
         for  (int r=0; r<selRow.length; r++) {
           for (int c=0; c<selCol.length; c++) {
          _selection[indice] =_model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])];
          indice++;
           }
         }
         
       }
     });

     // Create a row-header to display row numbers.
     // This row-header is made of labels whose Borders,
     // Foregrounds, Backgrounds, and Fonts must be
     // the one used for the table column headers.
     // Also ensure that the row-header labels and the table
     // rows have the same height.
     TableColumn       aColumn   = getColumnModel().getColumn(0);
     TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer();
     if (aRenderer==null) {
       System.out.println(" Aouch !");
       aColumn   = getColumnModel().getColumn(0);
       aRenderer = aColumn.getHeaderRenderer();
       if (aRenderer==null) {
         System.out.println(" Aouch Aouch !");
         System.exit(3);
       }
     }
     Component aComponent = aRenderer.getTableCellRendererComponent(this,
                                          aColumn.getHeaderValue(),
                                          false, false, -1, 0);
     Font  aFont       = aComponent.getFont();
     Color aBackground = aComponent.getBackground();
     Color aForeground = aComponent.getForeground();
       
     Border      border  = (Border)UIManager.getDefaults().get("TableHeader.cellBorder");
     Insets      insets  = border.getBorderInsets(tableHeader);
     FontMetrics metrics = getFontMetrics(_cellFont);
     rowHeight           = insets.bottom + metrics.getHeight() + insets.top;

     /*
      * Creating a panel to be used as the row header.
      *
      * Since I'm not using any LayoutManager,
      * a call to setPreferredSize().
      */
     JPanel pnl = new JPanel((LayoutManager)null);
     Dimension dim = new Dimension( metrics.stringWidth("999")+insets.right+insets.left,
                           rowHeight*_numRow);
     pnl.setPreferredSize(dim);

     // Adding the row header labels
     dim.height = rowHeight;
     for (int ii=0; ii<_numRow; ii++) {
       JLabel lbl = new JLabel(Integer.toString(ii+1), SwingConstants.CENTER);
       lbl.setFont(aFont);
       lbl.setBackground(aBackground);
       lbl.setForeground(aForeground);
       lbl.setBorder(border);
       lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
       pnl.add(lbl);
     }

     JViewport vp = new JViewport();
     dim.height = rowHeight*_numRow;
     vp.setViewSize(dim);
     vp.setView(pnl);
     _scp.setRowHeader(vp);
     
     // create and position GUI components; register event handlers
   
   class YourButton extends JPanel {
   
    public YourButton() {
        JButton aButton = new JButton("Button");
       aButton.getAccessibleContext().        
                setAccessibleName("Button");    
        String desc = "Here's your button button";
        aButton.getAccessibleContext().        
                setAccessibleDescription(desc);
        add(aButton);
    }

    void buttonInterface(){
        JFrame frame = new JFrame(
                                 "YourButton");
        frame.getContentPane().
                          add(new YourButton(),
                                  BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

     // Set resize policy and make sure
     // the table's size is tailored
     // as soon as it gets drawn.
     setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     Dimension dimScpViewport = getPreferredScrollableViewportSize();
     if (_numRow>30) dimScpViewport.height = 30*rowHeight;
     else           dimScpViewport.height  = _numRow*rowHeight;
     if (_numCol>15)
       dimScpViewport.width = 15*getColumnModel().getTotalColumnWidth()/_numCol;
     else
       dimScpViewport.width = getColumnModel().getTotalColumnWidth();
     setPreferredScrollableViewportSize(dimScpViewport);
     resizeAndRepaint();
    }


    /**
     * Build a numRow by numColumn SpreadSheet included
     * in a JScrollPane. The associated model and the cells
     * are automatically created.
     *
     * @param numRow The number of row in the spreadsheet
     * @param numColumn The number of column in the spreadsheet
     */
    public SpreadSheet(int numRow, int numColumn) {
      this(null, numRow, numColumn);
    }


    /**
     * Build a SpreadSheet included in a JScrollPane
     * from the cells given as argument.
     *
     * @param cells[numRow][numColumn] A two dimensional rectangular
     *                                 array of cells to be used when
     *                                 creating the spreadsheet.
     */
    public SpreadSheet(SheetCell cells[][]) {
      this(cells, cells.length, cells[0].length);
    }

    /**
     * Invoked when a cell edition starts.
     * This method overrides and calls that of its super class.
     *
     * @param int The row to be edited
     * @param int The column to be edited
     * @param EventObject The firing event
     * @return boolean false if for any reason the cell cannot be edited.
     */
    public boolean editCellAt( int row, int column, EventObject ev) {

      if (_editedModelRow != -1)
     _model.setDisplayMode(_editedModelRow, _editedModelCol);

      _editedModelRow = row;
      _editedModelCol = convertColumnIndexToModel(column);

      _model.setEditMode(row, convertColumnIndexToModel(column));
      return super.editCellAt(row, column, ev);

    }


    /**
     * Invoked by the cell editor when a cell edition stops.
     * This method override and calls that of its super class.
     *
     */
    public void editingStopped(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingStopped(ev);
    }
   

    /**
     * Invoked by the cell editor when a cell edition is cancelled.
     * This method override and calls that of its super class.
     *
     */
    public void editingCanceled(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingCanceled(ev);
    }

    protected JScrollPane getScrollPane() { return _scp; }

    public void processMouseEvent(MouseEvent ev) {

     int type      = ev.getID();
     int modifiers = ev.getModifiers();

     if ( (type==MouseEvent.MOUSE_RELEASED) && (modifiers==InputEvent.BUTTON3_MASK) ) {

         if (_selection!=null) {
           if (_popupMenu==null) _popupMenu = new CellMenu(this);
       
           if (_popupMenu.isVisible())
          _popupMenu.setVisible(false);
           else {
          _popupMenu.setTargetCells(_selection);
          Point p = getLocationOnScreen();
          _popupMenu.setLocation(p.x+ev.getX()+1, p.y+ev.getY()+1);
          _popupMenu.setVisible(true);
          }
         }
         
     }
     super.processMouseEvent(ev);
    }
 
    protected void release() { _model = null; }
   
    public void setVisible(boolean flag) { _scp.setVisible(flag); }

   
    /*
     * This class is used to customize the cells rendering.
     */
    public class CellRenderer extends JLabel implements TableCellRenderer  {

      private LineBorder  _selectBorder;
      private EmptyBorder _emptyBorder;
      private Dimension   _dim;

      public CellRenderer() {
     super();
     _emptyBorder  = new EmptyBorder(1, 2, 1, 2);
     _selectBorder = new LineBorder(Color.red);
     setOpaque(true);
     setHorizontalAlignment(SwingConstants.CENTER);
     _dim = new Dimension();
     _dim.height = 22;
     _dim.width  = 100;
     setSize(_dim);
      };

      /**
       *
       * Method defining the renderer to be used
       * when drawing the cells.
       *
       */
      public Component getTableCellRendererComponent (JTable table, Object value,
                                    boolean isSelected,
                                    boolean hasFocus,
                                    int row, int column) {

     SheetCell sc = (SheetCell)value;

     setFont(_cellFont);
     setText(sc.toString());
     setForeground(sc.foreground);
     setBackground(sc.background);

     if (isSelected) {
       setBorder(_selectBorder);
       setToolTipText("Right-click to change the cell's colors.");
       
     } else {
       setBorder(_emptyBorder);
       setToolTipText("Single-Click to select a cell, " +
                "double-click to edit.");
     }

     return this;

      }
     
    }

}

/*   // Then you could use a method for the button
 *   // You said you already knew how to do this
 *   // But I placed an example here anyway (commented out)
 *
 *
   private void openFileJButtonActionPerformed( ActionEvent event )
   {
         
         // Method action to try here
         try
         {
            // Something
           
            // change state of JButton if you want
            yourFileJButton.setEnabled( false );
      ;
           
         }
         catch ( IOException exception )
         {
            JOptionPane.showMessageDialog(null,
            "Sorry there is problem with something",
            "Blah Blah Blah something isn't right",JOptionPane.INFORMATION_MESSAGE);

         }

       // end open file

      // reset JButton to initial states
      resetUserInput();

   } // end method yourFileJButtonActionPerformed*/
I still can not see any button on the code, It runs sucessfully. I appreciate your effort and help but please give one more try, we are almost there.
Here ya go, buttons from renderering class and a cell editor also in case u need it :>)
==============================================================================================
package tmanfe.spreadsheet;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;

public class SpreadSheet extends JTable {

    /**
     * Set this field to true and recompile
     * to get debug traces
     */
    public static final boolean DEBUG = true;

    private JScrollPane      _scp;
    private CellMenu         _popupMenu;
    private SpreadSheetModel _model;
    private int              _numRow;
    private int              _numCol;

    private int _editedModelRow;
    private int _editedModelCol;
   
    /*
     * GUI components used to tailored
     * the SpreadSheet.
     */
    private CellRenderer _renderer;
    private Font         _cellFont;
  //private FontMetrics  _metrics;

    // Cells selected.
    private Object [] _selection;

   /**
     * Start the spreadsheet into a JFrame.
     * @param String[] The options passed on the command
     *        line. Not used.
     */
    public static void main(String[] args) {


        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.3") < 0) {
          System.out.println("Please use Java 1.3 or above.");
       //System.exit(1);
     }

     try {
       UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     } catch(Exception ex) {
       System.out.println("Can't set look and feel MetalLookAndFeel");
       System.exit(2);
     }

     JFrame frame = new JFrame("A Simple Spreadsheet");
     
     /*
      * Allows the user to exit the application
      * from the window manager's dressing.
      */
     frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) { System.exit(0); }
         });
     
     SpreadSheet sp = new SpreadSheet(40, 40);

     /**
     SheetCell[][] cells = new SheetCell[3][2];
     cells[0][0] = new SheetCell(0 , 0, "1", null);
     cells[1][0] = new SheetCell(0 , 1, "2", null);
     cells[2][0] = new SheetCell(0 , 2, "3", null);
     cells[0][1] = new SheetCell(1 , 0, "1", "=A1");
     cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2");
     cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3");
     SpreadSheet sp = new SpreadSheet(cells);
     **/


     frame.getContentPane().add(sp.getScrollPane());
     frame.pack();
     frame.setVisible(true);
     
    }

    /**
     * Build SpreadSheet of numCol columns and numRow rows.
     *
     * @param cells[numRow][numColumn] If not null, the cells to be used in the spreadsheet.
     *             It must be a two dimensional rectangular array. If null, the cells are
     *             automatically created.
     * @param numRow The number of rows
     * @param numCol The number of columns
     *              
     */
    private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) {

        super();

     SheetCell foo[][];

     if (cells!=null)
       foo = cells;
     else {
       foo = new SheetCell[numRow][numCol];
       for (int ii=0; ii<numRow; ii++) {
         for (int jj=0; jj<numCol; jj++)
           foo[ii][jj] = new SheetCell(ii, jj);
       }
     }
       
     _numRow = numRow;
     _numCol = numCol;

     _cellFont = new Font("Times", Font.PLAIN, 20);

     // Create the JScrollPane that includes the Table
     _scp = new JScrollPane(this);

     // Create the rendeder for the cells
     _renderer = new CellRenderer();
     try {
         setDefaultRenderer(Class.forName("java.lang.Object" ), _renderer );
     } catch (ClassNotFoundException ex) {
         if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer");
     }

     _model = new SpreadSheetModel(foo, this);
     setModel(_model);

     /*
      * Tune the selection mode
      */

     // Allows row and collumn selections to exit at the same time
     setCellSelectionEnabled(true);

     setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

     getSelectionModel().addListSelectionListener( new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent ev) {

         int selRow[] = getSelectedRows();
         int selCol[] = getSelectedColumns();
           
         _selection = new Object[selRow.length*selCol.length];
           
         int indice = 0;
         for  (int r=0; r<selRow.length; r++) {
           for (int c=0; c<selCol.length; c++) {
          _selection[indice] =_model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])];
          indice++;
           }
         }
         
       }
     });

     // Create a row-header to display row numbers.
     // This row-header is made of labels whose Borders,
     // Foregrounds, Backgrounds, and Fonts must be
     // the one used for the table column headers.
     // Also ensure that the row-header labels and the table
     // rows have the same height.
     TableColumn       aColumn   = getColumnModel().getColumn(0);
     TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer();
     if (aRenderer==null) {
       System.out.println(" Aouch !");
       aColumn   = getColumnModel().getColumn(0);
       aRenderer = aColumn.getHeaderRenderer();
       if (aRenderer==null) {
         System.out.println(" Aouch Aouch !");
         System.exit(3);
       }
     }
     Component aComponent = aRenderer.getTableCellRendererComponent(this,
                                          aColumn.getHeaderValue(),
                                          false, false, -1, 0);
     Font  aFont       = aComponent.getFont();
     Color aBackground = aComponent.getBackground();
     Color aForeground = aComponent.getForeground();
       
     Border      border  = (Border)UIManager.getDefaults().get("TableHeader.cellBorder");
     Insets      insets  = border.getBorderInsets(tableHeader);
     FontMetrics metrics = getFontMetrics(_cellFont);
     rowHeight           = insets.bottom + metrics.getHeight() + insets.top;

     /*
      * Creating a panel to be used as the row header.
      *
      * Since I'm not using any LayoutManager,
      * a call to setPreferredSize().
      */
     JPanel pnl = new JPanel((LayoutManager)null);
     Dimension dim = new Dimension( metrics.stringWidth("999")+insets.right+insets.left,
                           rowHeight*_numRow);
     pnl.setPreferredSize(dim);

     // Adding the row header labels
     dim.height = rowHeight;
     for (int ii=0; ii<_numRow; ii++) {
       JLabel lbl = new JLabel(Integer.toString(ii+1), SwingConstants.CENTER);
       lbl.setFont(aFont);
       lbl.setBackground(aBackground);
       lbl.setForeground(aForeground);
       lbl.setBorder(border);
       lbl.setBounds(0, ii*dim.height, dim.width, dim.height);
       pnl.add(lbl);
     }

     JViewport vp = new JViewport();
     dim.height = rowHeight*_numRow;
     vp.setViewSize(dim);
     vp.setView(pnl);
     _scp.setRowHeader(vp);
     
     // create and position GUI components; register event handlers
   JTable table = new JTable( 6,4 )
            {
                  public TableCellRenderer getCellRenderer(int row, int column) {
                        TableColumn tableColumn = getColumnModel().getColumn(column);
                        TableCellRenderer renderer = tableColumn.getCellRenderer();
                        if (renderer == null) {
                              Class c = getColumnClass(column);
                              if( c.equals(Object.class) )
                              {
                                    Object o = getValueAt(row,column);
                                    if( o != null )
                                          c = getValueAt(row,column).getClass();
                              }
                              renderer = getDefaultRenderer(c);
                        }
                        return renderer;
                  }
                  
                  public TableCellEditor getCellEditor(int row, int column) {
                        TableColumn tableColumn = getColumnModel().getColumn(column);
                        TableCellEditor editor = tableColumn.getCellEditor();
                        if (editor == null) {
                              Class c = getColumnClass(column);
                              if( c.equals(Object.class) )
                              {
                                    Object o = getValueAt(row,column);
                                    if( o != null )
                                          c = getValueAt(row,column).getClass();
                              }
                              editor = getDefaultEditor(c);
                        }
                        return editor;
                  }
                  
            };
            
            // Buttons
            table.setValueAt( new JButton("Button"), 0, 0 );
            table.setValueAt( new JButton("Button"), 0, 1 );




     // Set resize policy and make sure
     // the table's size is tailored
     // as soon as it gets drawn.
     setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
     Dimension dimScpViewport = getPreferredScrollableViewportSize();
     if (_numRow>30) dimScpViewport.height = 30*rowHeight;
     else           dimScpViewport.height  = _numRow*rowHeight;
     if (_numCol>15)
       dimScpViewport.width = 15*getColumnModel().getTotalColumnWidth()/_numCol;
     else
       dimScpViewport.width = getColumnModel().getTotalColumnWidth();
     setPreferredScrollableViewportSize(dimScpViewport);
     resizeAndRepaint();
    }


    /**
     * Build a numRow by numColumn SpreadSheet included
     * in a JScrollPane. The associated model and the cells
     * are automatically created.
     *
     * @param numRow The number of row in the spreadsheet
     * @param numColumn The number of column in the spreadsheet
     */
    public SpreadSheet(int numRow, int numColumn) {
      this(null, numRow, numColumn);
    }


    /**
     * Build a SpreadSheet included in a JScrollPane
     * from the cells given as argument.
     *
     * @param cells[numRow][numColumn] A two dimensional rectangular
     *                                 array of cells to be used when
     *                                 creating the spreadsheet.
     */
    public SpreadSheet(SheetCell cells[][]) {
      this(cells, cells.length, cells[0].length);
    }

    /**
     * Invoked when a cell edition starts.
     * This method overrides and calls that of its super class.
     *
     * @param int The row to be edited
     * @param int The column to be edited
     * @param EventObject The firing event
     * @return boolean false if for any reason the cell cannot be edited.
     */
    public boolean editCellAt( int row, int column, EventObject ev) {

      if (_editedModelRow != -1)
     _model.setDisplayMode(_editedModelRow, _editedModelCol);

      _editedModelRow = row;
      _editedModelCol = convertColumnIndexToModel(column);

      _model.setEditMode(row, convertColumnIndexToModel(column));
      return super.editCellAt(row, column, ev);

    }


    /**
     * Invoked by the cell editor when a cell edition stops.
     * This method override and calls that of its super class.
     *
     */
    public void editingStopped(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingStopped(ev);
    }
   

    /**
     * Invoked by the cell editor when a cell edition is cancelled.
     * This method override and calls that of its super class.
     *
     */
    public void editingCanceled(ChangeEvent ev) {
      _model.setDisplayMode(_editedModelRow, _editedModelCol);
      super.editingCanceled(ev);
    }

    protected JScrollPane getScrollPane() { return _scp; }

    public void processMouseEvent(MouseEvent ev) {

     int type      = ev.getID();
     int modifiers = ev.getModifiers();

     if ( (type==MouseEvent.MOUSE_RELEASED) && (modifiers==InputEvent.BUTTON3_MASK) ) {

         if (_selection!=null) {
           if (_popupMenu==null) _popupMenu = new CellMenu(this);
       
           if (_popupMenu.isVisible())
          _popupMenu.setVisible(false);
           else {
          _popupMenu.setTargetCells(_selection);
          Point p = getLocationOnScreen();
          _popupMenu.setLocation(p.x+ev.getX()+1, p.y+ev.getY()+1);
          _popupMenu.setVisible(true);
          }
         }
         
     }
     super.processMouseEvent(ev);
    }
 
    protected void release() { _model = null; }
   
    public void setVisible(boolean flag) { _scp.setVisible(flag); }

   
    /*
     * This class is used to customize the cells rendering.
     */
    public class CellRenderer extends JLabel implements TableCellRenderer  {

      private LineBorder  _selectBorder;
      private EmptyBorder _emptyBorder;
      private Dimension   _dim;

      public CellRenderer() {
     super();
     _emptyBorder  = new EmptyBorder(1, 2, 1, 2);
     _selectBorder = new LineBorder(Color.red);
     setOpaque(true);
     setHorizontalAlignment(SwingConstants.CENTER);
     _dim = new Dimension();
     _dim.height = 22;
     _dim.width  = 100;
     setSize(_dim);
      };

      /**
       *
       * Method defining the renderer to be used
       * when drawing the cells.
       *
       */
      public Component getTableCellRendererComponent (JTable table, Object value,
                                    boolean isSelected,
                                    boolean hasFocus,
                                    int row, int column) {

     SheetCell sc = (SheetCell)value;

     setFont(_cellFont);
     setText(sc.toString());
     setForeground(sc.foreground);
     setBackground(sc.background);

     if (isSelected) {
       setBorder(_selectBorder);
       setToolTipText("Right-click to change the cell's colors.");
       
     } else {
       setBorder(_emptyBorder);
       setToolTipText("Single-Click to select a cell, " +
                "double-click to edit.");
     }

     return this;

      }
     
    }

}

Great  effort, I ran the code and still no button, did you run the code before you posted?

When I say a button, I mean a normal button, where you press and it does something. My purpose is to add buttons to this application like "Open", "Save", "New", "Quit".

Thanks again billions, I know that it will come, please one more try.
Cheers
????? YES, I ran the last three post codes.

I understand the buttons and what you want - I need to know if you ran the LAST code sent.
And IF the buttons SHOW, once I know they show the hooks can be written (even you say you understand the button behavior structure-so no worries there right)

We just need to SHOW the buttons?

Do want the buttons in CELL?

A panel  or a frame??

What do you need oh GREAT one LOL.
I need just the buttons, ofcourse not on the cells, it can be on the panel or on the frame.
Yees, we just need to show the buttons. It might be above all the cells or below all the cells.
I need to know if you ran the LAST code sent - I would be REALLY suprised if THAT didn't work for you as I can see the buttons clearly on my compiler.
That is really strange, please provide me a screenshot how the buttons are shown, I did run it but can not see any buttons.
ASKER CERTIFIED SOLUTION
Avatar of Curtis Shull
Curtis Shull
Flag of United States of America image

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
Well...???
Well, it still does not work. I tried the code on my friend's machine, it also does not work there.

But I do appreciate all your help, effort and patience.

I give you already 500 points, for me you deserved more than that but 500 is the maximum.
Whenever you come to Belgium, let me know, I will offer you Belgian bier :-)
Belgium???        DUDE, I stayed in St Truden for a YEAR.
Uesed to go to Hasselt to party all the time - also to Borgloon

Hoe ist et met yer?  Hoe gat ut?

WOW!!!  You're awesome!


So sorry I could not help you - TRIED my BEST - if you get it fixed PLEASE lemme know what you did.