Facebook
From Reliable Meerkat, 2 Years ago, written in Java.
This paste is a reply to Untitled from Social Ibis - view diff
Embed
Download Paste or View Raw
Hits: 62
  1. /*
  2.  * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  *   - Redistributions of source code must retain the above copyright
  9.  *     notice, this list of conditions and the following disclaimer.
  10.  *
  11.  *   - Redistributions in binary form must reproduce the above copyright
  12.  *     notice, this list of conditions and the following disclaimer in the
  13.  *     documentation and/or other materials provided with the distribution.
  14.  *
  15.  *   - Neither the name of Oracle or the names of its
  16.  *     contributors may be used to endorse or promote products derived
  17.  *     from this software without specific prior written permission.
  18.  *
  19.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20.  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21.  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30.  */
  31.  
  32. package components;
  33.  
  34. /*
  35.  * TableRenderDemo.java requires no other files.
  36.  */
  37.  
  38. import javax.swing.DefaultCellEditor;
  39. import javax.swing.JComboBox;
  40. import javax.swing.JFrame;
  41. import javax.swing.JPanel;
  42. import javax.swing.JScrollPane;
  43. import javax.swing.JTable;
  44. import javax.swing.table.AbstractTableModel;
  45. import javax.swing.table.DefaultTableCellRenderer;
  46. import javax.swing.table.TableCellRenderer;
  47. import javax.swing.table.TableColumn;
  48. import java.awt.Component;
  49. import java.awt.Dimension;
  50. import java.awt.GridLayout;
  51.  
  52. /**
  53.  * TableRenderDemo is just like TableDemo, except that it
  54.  * explicitly initializes column sizes and it uses a combo box
  55.  * as an editor for the Sport column.
  56.  */
  57. public class TableRenderDemo extends JPanel {
  58.     private boolean DEBUG = false;
  59.  
  60.     public TableRenderDemo() {
  61.         super(new GridLayout(1,0));
  62.  
  63.         JTable table = new JTable(new MyTableModel());
  64.         table.setPreferredScrollableViewportSize(new Dimension(500, 70));
  65.         table.setFillsViewportHeight(true);
  66.  
  67.         //Create the scroll pane and add the table to it.
  68.         JScrollPane scrollPane = new JScrollPane(table);
  69.  
  70.         //Set up column sizes.
  71.         initColumnSizes(table);
  72.  
  73.         //Fiddle with the Sport column's cell editors/renderers.
  74.         setUpSportColumn(table, table.getColumnModel().getColumn(2));
  75.  
  76.         //Add the scroll pane to this panel.
  77.         add(scrollPane);
  78.     }
  79.  
  80.     /*
  81.      * This method picks good column sizes.
  82.      * If all column heads are wider than the column's cells'
  83.      * contents, then you can just use column.sizeWidthToFit().
  84.      */
  85.     private void initColumnSizes(JTable table) {
  86.         MyTableModel model = (MyTableModel)table.getModel();
  87.         TableColumn column = null;
  88.         Component comp = null;
  89.         int headerWidth = 0;
  90.         int cellWidth = 0;
  91.         Object[] longValues = model.longValues;
  92.         TableCellRenderer headerRenderer =
  93.             table.getTableHeader().getDefaultRenderer();
  94.  
  95.         for (int i = 0; i < 5; i++) {
  96.             column = table.getColumnModel().getColumn(i);
  97.  
  98.             comp = headerRenderer.getTableCellRendererComponent(
  99.                                  null, column.getHeaderValue(),
  100.                                  false, false, 0, 0);
  101.             headerWidth = comp.getPreferredSize().width;
  102.  
  103.             comp = table.getDefaultRenderer(model.getColumnClass(i)).
  104.                              getTableCellRendererComponent(
  105.                                  table, longValues[i],
  106.                                  false, false, 0, i);
  107.             cellWidth = comp.getPreferredSize().width;
  108.  
  109.             if (DEBUG) {
  110.                 System.out.println("Initializing width of column "
  111.                                    + i + ". "
  112.                                    + "headerWidth = " + headerWidth
  113.                                    + "; cellWidth = " + cellWidth);
  114.             }
  115.  
  116.             column.setPreferredWidth(Math.max(headerWidth, cellWidth));
  117.         }
  118.     }
  119.  
  120.     public void setUpSportColumn(JTable table,
  121.                                  TableColumn sportColumn) {
  122.         //Set up the editor for the sport cells.
  123.         JComboBox comboBox = new JComboBox();
  124.         comboBox.addItem("Snowboarding");
  125.         comboBox.addItem("Rowing");
  126.         comboBox.addItem("Knitting");
  127.         comboBox.addItem("Speed reading");
  128.         comboBox.addItem("Pool");
  129.         comboBox.addItem("None of the above");
  130.         sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
  131.  
  132.         //Set up tool tips for the sport cells.
  133.         DefaultTableCellRenderer renderer =
  134.                 new DefaultTableCellRenderer();
  135.         renderer.setToolTipText("Click for combo box");
  136.         sportColumn.setCellRenderer(renderer);
  137.     }
  138.  
  139.     class MyTableModel extends AbstractTableModel {
  140.         private String[] columnNames = {"First Name",
  141.                                         "Last Name",
  142.                                         "Sport",
  143.                                         "# of Years",
  144.                                         "Vegetarian"};
  145.         private Object[][] data = {
  146.             {"Kathy", "Smith",
  147.              "Snowboarding", new Integer(5), new Boolean(false)},
  148.             {"John", "Doe",
  149.              "Rowing", new Integer(3), new Boolean(true)},
  150.             {"Sue", "Black",
  151.              "Knitting", new Integer(2), new Boolean(false)},
  152.             {"Jane", "White",
  153.              "Speed reading", new Integer(20), new Boolean(true)},
  154.             {"Joe", "Brown",
  155.              "Pool", new Integer(10), new Boolean(false)}
  156.         };
  157.  
  158.         public final Object[] longValues = {"Jane", "Kathy",
  159.                                             "None of the above",
  160.                                             new Integer(20), Boolean.TRUE};
  161.  
  162.         public int getColumnCount() {
  163.             return columnNames.length;
  164.         }
  165.  
  166.         public int getRowCount() {
  167.             return data.length;
  168.         }
  169.  
  170.         public String getColumnName(int col) {
  171.             return columnNames[col];
  172.         }
  173.  
  174.         public Object getValueAt(int row, int col) {
  175.             return data[row][col];
  176.         }
  177.  
  178.         /*
  179.          * JTable uses this method to determine the default renderer/
  180.          * editor for each cell.  If we didn't implement this method,
  181.          * then the last column would contain text ("true"/"false"),
  182.          * rather than a check box.
  183.          */
  184.         public Class getColumnClass(int c) {
  185.             return getValueAt(0, c).getClass();
  186.         }
  187.  
  188.         /*
  189.          * Don't need to implement this method unless your table's
  190.          * editable.
  191.          */
  192.         public boolean isCellEditable(int row, int col) {
  193.             //Note that the data/cell address is constant,
  194.             //no matter where the cell appears onscreen.
  195.             if (col < 2) {
  196.                 return false;
  197.             } else {
  198.                 return true;
  199.             }
  200.         }
  201.  
  202.         /*
  203.          * Don't need to implement this method unless your table's
  204.          * data can change.
  205.          */
  206.         public void setValueAt(Object value, int row, int col) {
  207.             if (DEBUG) {
  208.                 System.out.println("Setting value at " + row + "," + col
  209.                                    + " to " + value
  210.                                    + " (an instance of "
  211.                                    + value.getClass() + ")");
  212.             }
  213.  
  214.             data[row][col] = value;
  215.             fireTableCellUpdated(row, col);
  216.  
  217.             if (DEBUG) {
  218.                 System.out.println("New value of data:");
  219.                 printDebugData();
  220.             }
  221.         }
  222.  
  223.         private void printDebugData() {
  224.             int numRows = getRowCount();
  225.             int numCols = getColumnCount();
  226.  
  227.             for (int i=0; i < numRows; i++) {
  228.                 System.out.print("    row " + i + ":");
  229.                 for (int j=0; j < numCols; j++) {
  230.                     System.out.print("  " + data[i][j]);
  231.                 }
  232.                 System.out.println();
  233.             }
  234.             System.out.println("--------------------------");
  235.         }
  236.     }
  237.  
  238.     /**
  239.      * Create the GUI and show it.  For thread safety,
  240.      * this method should be invoked from the
  241.      * event-dispatching thread.
  242.      */
  243.     private static void createAndShowGUI() {
  244.         //Create and set up the window.
  245.         JFrame frame = new JFrame("TableRenderDemo");
  246.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  247.  
  248.         //Create and set up the content pane.
  249.         TableRenderDemo newContentPane = new TableRenderDemo();
  250.         newContentPane.setOpaque(true); //content panes must be opaque
  251.         frame.setContentPane(newContentPane);
  252.  
  253.         //Display the window.
  254.         frame.pack();
  255.         frame.setVisible(true);
  256.     }
  257.  
  258.     public static void main(String[] args) {
  259.         //Schedule a job for the event-dispatching thread:
  260.         //creating and showing this application's GUI.
  261.         javax.swing.SwingUtilities.invokeLater(new Runnable() {
  262.             public void run() {
  263.                 createAndShowGUI();
  264.             }
  265.         });
  266.     }
  267. }