Changing the margins between JTable grid lines and cell data

You can do so with the JTable method setIntercellSpacing.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      table.setIntercellSpacing(new Dimension (10,20));
  
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing the foreground and background colors of JTable cells

Override the JTable’s cell renderer and set the fore- and background color. This example makes use of such a custom cell renderer. In the example, a cell item is of type ColoredItem that encapsulates an object and a Color.
Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   JTable table;
   MyTableModel tableModel;
 
   public Main() {
      super("Colored JTable Demonstration");
 
      tableModel = new MyTableModel(10, 5);
      table = new JTable(tableModel);
 
      DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
         public void setValue(Object value) {
            if (value instanceof ColoredItem) {
               Color fcolor = ((ColoredItem) value).getForeground();
               Color bcolor = ((ColoredItem) value).getBackground();
               this.setForeground(fcolor);
               this.setBackground(bcolor);
               setText(value.toString());
            }
         }
      };
  
      table.setDefaultRenderer(Object.class, colorRenderer);
      table.setDefaultEditor(Object.class, new DefaultCellEditor(new JTextField()));
 
      JScrollPane scrollPane = new JScrollPane(table);

      getContentPane().add(scrollPane, BorderLayout.CENTER);

      JPanel radioPanel = new JPanel(new GridLayout(1, 5));
      JRadioButton redRadio = new JRadioButton("Red");
      JRadioButton greenRadio = new JRadioButton("Green");
      JRadioButton blueRadio = new JRadioButton("Blue");
      JRadioButton yellowRadio = new JRadioButton("Yellow");
      JRadioButton blackRadio = new JRadioButton("Black");

      // Group the radio buttons.
      ButtonGroup group = new ButtonGroup();
      group.add(redRadio);
      group.add(greenRadio);
      group.add(blueRadio);
      group.add(yellowRadio);
      group.add(blackRadio);

      radioPanel.add(redRadio);
      radioPanel.add(greenRadio);
      radioPanel.add(blueRadio);
      radioPanel.add(yellowRadio);
      radioPanel.add(blackRadio);
 
      RadioListener radioListener = new RadioListener();
      redRadio.addActionListener(radioListener);
      greenRadio.addActionListener(radioListener);
      blueRadio.addActionListener(radioListener);
      yellowRadio.addActionListener(radioListener);
      blackRadio.addActionListener(radioListener);
 
      // add radiopanel to container
      JPanel panel = new JPanel(new GridLayout(2, 1));
      panel.add(new JLabel("Select color for selected cell:"));
      panel.add(radioPanel);     
      getContentPane().add(BorderLayout.SOUTH, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   class RadioListener implements ActionListener {
      public void actionPerformed(ActionEvent ae) {
         int row = table.getSelectedRow();
         int column = table.getSelectedColumn();
         ColoredItem ci = (ColoredItem) tableModel.getValueAt(row, column);
 
         if (ae.getActionCommand().equals("Red"))
            ci.setForeground(Color.red);
         else if (ae.getActionCommand().equals("Green"))
            ci.setForeground(Color.green);
         else if (ae.getActionCommand().equals("Blue"))
            ci.setForeground(Color.blue);
         else if (ae.getActionCommand().equals("Yellow"))
            ci.setForeground(Color.yellow);
         else if (ae.getActionCommand().equals("Black"))
            ci.setForeground(Color.black);
 
         // necessary to cause a fireTableCellUpdated event
         tableModel.setValueAt(ci, row, column);
      }
   }
 
   private class ColoredItem {
      private Object object;
      private Color foreground;
      private Color background;
 
      public ColoredItem(Object object, Color foreground, Color background) {
         this.object = object;
         this.foreground = foreground;
         this.background = background;
      }
  
      public void setObject(Object object) {
         this.object = object;
      }
  
      public void setForeground(Color foreground) {
         this.foreground = foreground;
      }
 
      public void setBackground(Color background) {
         this.background = background;
      }
 
      public Object getObject() {
         return object;
      }
 
      public Color getForeground() {
         return foreground;
      }
 
      public Color getBackground() {
         return background;
      }
 
      public String toString() {
         return object.toString(); 
      }
   }
 
   class MyTableModel extends AbstractTableModel {
      String [] columnNames;
      Object [][] data;
 
      MyTableModel(int rows, int columns) {
         columnNames = createColumnElements(columns);
         data = createTableElements(rows, columns);         
      }
 
      public int getColumnCount() {
         return columnNames.length;
      }
        
      public int getRowCount() {
         return data.length;
      }
 
      public String getColumnName(int col) {
         return columnNames[col];
      }
 
      public Object getValueAt(int row, int col) {
         return data[row][col];
      }
 
      public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
      }
 
      public void setValueAt(Object value, int row, int col) {
         data[row][col] = value;
         fireTableCellUpdated(row, col);
      }
 
      private String[] createColumnElements(int columns) {
         String[] data;
 
         data = new String[columns];
         for (int i=0; i<columns; i++) {
            data[i] = new String("Column " + i);
         }
 
         return data;
      }
 
      private Object[][] createTableElements(int rows, int columns) {
         ColoredItem [][]data;
         data = new ColoredItem[rows][];
         for (int i=0; i<rows; i++) {
            data[i] = new ColoredItem[columns];
            for (int j=0; j<columns; j++) {
               data[i][j] = new ColoredItem("(" + i + " , " + j + ")", Color.green, Color.white);
            }
         }
 
         return data;
      } 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}

Making the cells of a JTable transparent so that background image shows through

Author: Zafir Anjum

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
public class Table
{
   public static void main(String[] args) {
      JFrame frame = new JFrame("Table");
      frame.addWindowListener( new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            Window win = e.getWindow();
            win.setVisible(false);
            win.dispose();
            System.exit(0);
         }
      } );	
 
      // Create your own sub-class of JTable rather than using anonymous class
      JTable table = new JTable( 15, 3 ) {
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer( renderer, row, column);
            // We want renderer component to be transparent
            // so background image is visible
            if( c instanceof JComponent )
               ((JComponent)c).setOpaque(false);
               return c;
            }

            // Hard coded value. In your sub-class add a function for this.
            ImageIcon image = new ImageIcon( "codeguruwm.gif" );

            public void paint( Graphics g ) {
               // First draw the background image - tiled 
               Dimension d = getSize();
               for( int x = 0; x < d.width; x += image.getIconWidth() )
                  for( int y = 0; y < d.height; y += image.getIconHeight() ) 
                     g.drawImage( image.getImage(), x, y, null, null );
               // Now let the regular paint code do it's work
               super.paint(g);
           }
      };
 
      // Set the table transparent
      table.setOpaque(false);
		
      JScrollPane sp = new JScrollPane( table );
      frame.getContentPane().add( sp );	

      frame.pack();
      frame.show();
   }
}

Changing the color of entire rows of a JTable

Write your own cell renderer. This example colors all rows green where the price of
the wine is < 55, red otherwise.

Main.java:

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);
 
      // since we’re using values of floats and boolean here, we need
      // to set the cell renderer for every column. 
      for (int i =0; i<wineModel.getColumnCount();i++) {
         table.setDefaultRenderer(table.getColumnClass(i), new WineCellRenderer());
      }
       
      // 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 columnClasses1;
   }
 
   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 Object getValueAtRow(int row) {
      Wine wine = (Wine) data.elementAt(row);
      return wine;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class WineCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
   {
      WineTableModel wtm = (WineTableModel) table.getModel();
      Wine wine = (Wine) wtm.getValueAtRow(row);
 
      if (wine.getPrice() < 55) {
         setBackground(Color.green);
      }
      else {
         setBackground(Color.red);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Creating a JTable with fixed columns

You can call the following method:

   table.getTableHeader().setResizingAllowed(false);

However, be aware that this will disable resizing for all columns, and will still resize the columns proportionally when resizing the container in which the JTable is hosted. To fix the size of one column, you have to think about what behavior you want and override the method sizeColumnsToFit().

Main.java:

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));
 
 
      // don't allow resizing columns
      table.getTableHeader().setResizingAllowed(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 columnClasses1;
   }
 
   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;
   }
}

Creating a JTable with a multi-line header

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



MultiLineHeaderExample.java:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
  
/**
 * @version 1.0 11/09/98
 */
public class MultiLineHeaderExample extends JFrame {
  MultiLineHeaderExample() {
    super( "Multi-Line Header Example" );
 
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{{"a","b","c"},
                                    {"A","B","C"}},
                     new Object[]{"1stnalpha","2ndnbeta","3rdngamma"});
 
    JTable table = new JTable( dm );
    MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
    Enumeration enum = table.getColumnModel().getColumns();
    while (enum.hasMoreElements()) {
      ((TableColumn)enum.nextElement()).setHeaderRenderer(renderer);
    }   
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 110 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    MultiLineHeaderExample frame = new MultiLineHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}

MultiLineHeaderRenderer.java:

import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;


/**
 * @version 1.0 11/09/98
 */
public class MultiLineHeaderRenderer extends JList implements TableCellRenderer {
  public MultiLineHeaderRenderer() {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
    setCellRenderer(renderer);
  }
 
  public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
    setFont(table.getFont());
    String str = (value == null) ? "" : value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector v = new Vector();
    try {
      while ((line = br.readLine()) != null) {
        v.addElement(line);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    setListData(v);
    return this;
  }
}

Preventing a particular JTable column from being edited

Decide what column should not be editable using the method isCellEditable.
This example allows you to modify any of the cells except the column Vintage.

Main.java:

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("Color Row 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 void setName(String name)        { this.name = name; }
   public void setVintage(String vintage)  { this.vintage = vintage; }
   public void setPrice(float price)       { this.price = price; }
   public void setInStock(boolean inStock) { this.inStock = 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 columnClasses1;
   }
 
   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 void setValueAt(Object value, int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col ==0)       wine.setName(""+value);
      else if (col == 1) wine.setVintage(""+value);
      else if (col == 2) wine.setPrice(new Float(""+value).floatValue());
      else if (col == 3) wine.setInStock(((Boolean) value).booleanValue());
   }
 
   public boolean isCellEditable(int row, int col) {
      if (col == 1) return false;
 
      return true;
   }
}

Embedding a JSpinner inside a JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class JSpinnerTableExample extends JFrame {
 
  public JSpinnerTableExample(){
    super( &amp;amp;quot;JSpinnerTable Example&amp;amp;quot; );
    
    SpinnerNumberModel spinnerModel1 = new SpinnerNumberModel(10.0, -500.0, 500.0, .5);
    SpinnerDateModel spinnerModel2 = new SpinnerDateModel();
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ spinnerModel1, &amp;amp;quot;JSpinner1&amp;amp;quot; },
                                     { spinnerModel2, &amp;amp;quot;JSpinner2&amp;amp;quot; }},
                      new Object[]{&amp;amp;quot;JSpinner&amp;amp;quot;,&amp;amp;quot;String&amp;amp;quot;});
                     
    JTable table = new JTable(dtm);
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellRenderer(new SpinnerRenderer());
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellEditor(new SpinnerEditor());
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSpinnerTableExample frame = new JSpinnerTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
 
class SpinnerRenderer extends JSpinner implements TableCellRenderer {
   public SpinnerRenderer() {
      setOpaque(true);
   }
  
   public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
      setModel((SpinnerModel) value);
  
      return this;
   }
}
  
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
   protected JSpinner spinner;
  
   public SpinnerEditor() {
      spinner = new JSpinner();
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
      spinner.setModel((SpinnerModel) value);
 
      return spinner;
   }
 
   public Object getCellEditorValue() {
      SpinnerModel sm = spinner.getModel();
      return sm;
   }
}

Creating a JTable with fixed rows

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples6.html)



FixedRowExample.java:

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

/**
 * @version 1.0 03/05/99
 */
public class FixedRowExample extends JFrame {
  Object[][] data;
  Object[] column;
  JTable fixedTable,table;
  private int FIXED_NUM = 2;

  public FixedRowExample() {
    super( "Fixed Row Example" );
    
    data =  new Object[][]{
        {      "a","","","","",""},
        {      "","b","","","",""},
        {      "","","c","","",""},
        {      "","","","d","",""},
        {      "","","","","e",""},
        {      "","","","","","f"},
        {"fixed1","","","","","","",""},
        {"fixed2","","","","","","",""}};
    column = new Object[]{"A","B","C","D","E","F"};
        
    AbstractTableModel    model = new AbstractTableModel() {
      public int getColumnCount() { return column.length; }
      public int getRowCount() { return data.length - FIXED_NUM; }
      public String getColumnName(int col) {
       return (String)column[col]; 
      }
      public Object getValueAt(int row, int col) { 
        return data[row][col]; 
      }
      public void setValueAt(Object obj, int row, int col) { 
        data[row][col] = obj; 
      }
      public boolean CellEditable(int row, int col) { 
        return true; 
      }
    };
    
    AbstractTableModel fixedModel = new AbstractTableModel() {      
      public int getColumnCount() { return column.length; }
      public int getRowCount() { return FIXED_NUM; }
      public Object getValueAt(int row, int col) { 
        return data[row + (data.length - FIXED_NUM)][col]; 
      }
    };
    
    table = new JTable( model );
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
    fixedTable = new JTable( fixedModel );
    fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
    JScrollPane scroll      = new JScrollPane( table );
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    
    JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
      public void setColumnHeaderView(Component view) {} // work around
    };                                                   //
                                             // fixedScroll.setColumnHeader(null); 
    
    fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    JScrollBar bar = fixedScroll.getVerticalScrollBar();
    JScrollBar dummyBar = new JScrollBar() {
      public void paint(Graphics g) {}
    };
    dummyBar.setPreferredSize(bar.getPreferredSize());
    fixedScroll.setVerticalScrollBar(dummyBar);
    
    final JScrollBar bar1 = scroll.getHorizontalScrollBar();
    JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
    bar2.addAdjustmentListener(new AdjustmentListener() {
      public void adjustmentValueChanged(AdjustmentEvent e) {
        bar1.setValue(e.getValue());
      }
    });
    
    
    scroll.setPreferredSize(new Dimension(400, 100));
    fixedScroll.setPreferredSize(new Dimension(400, 52));  // Hmm...
    getContentPane().add(     scroll, BorderLayout.CENTER);
    getContentPane().add(fixedScroll, BorderLayout.SOUTH);    
  }

  public static void main(String[] args) {
    FixedRowExample frame = new FixedRowExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.pack();
    frame.setVisible(true);
  }
}

Have a JButton cell in a JTable

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



JButtonTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class JButtonTableExample extends JFrame {
 
  public JButtonTableExample(){
    super( "JButtonTable Example" );
    
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{{"button 1","foo"},
                                    {"button 2","bar"}},
                     new Object[]{"Button","String"});
                     
    JTable table = new JTable(dm);
    table.getColumn("Button").setCellRenderer(new ButtonRenderer());
    table.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add( scroll );
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}

ButtonRenderer.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonRenderer extends JButton implements TableCellRenderer {
 
  public ButtonRenderer() {
    setOpaque(true);
  }
  
  public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else{
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText( (value ==null) ? "" : value.toString() );
    return this;
  }
}

ButtonEditor.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonEditor extends DefaultCellEditor {
  protected JButton button;
  private String    label;
  private boolean   isPushed;
 
  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }
 
  public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else{
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value ==null) ? "" : value.toString();
    button.setText( label );
    isPushed = true;
    return button;
  }
 
  public Object getCellEditorValue() {
    if (isPushed)  {
      // 
      // 
      JOptionPane.showMessageDialog(button ,label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String( label ) ;
  }
   
  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }
 
  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}