Table with tool tips for both cells and column headers : Table « Swing JFC « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Swing JFC » TableScreenshots 
Table with tool tips for both cells and column headers
Table with tool tips for both cells and column headers
 
/* From http://java.sun.com/docs/books/tutorial/index.html */

/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

/* 
 * TableToolTipsDemo.java is a 1.4 application that requires no other files.
 */

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;

/**
 * TableToolTipsDemo is just like TableDemo except that it sets up tool tips for
 * both cells and column headers.
 */
public class TableToolTipsDemo extends JPanel {
  private boolean DEBUG = false;

  protected String[] columnToolTips = null, null,
      "The person's favorite sport to participate in",
      "The number of years the person has played the sport",
      "If checked, the person eats no meat" };

  public TableToolTipsDemo() {
    super(new GridLayout(10));

    JTable table = new JTable(new MyTableModel()) {

      //Implement table cell tool tips.
      public String getToolTipText(MouseEvent e) {
        String tip = null;
        java.awt.Point p = e.getPoint();
        int rowIndex = rowAtPoint(p);
        int colIndex = columnAtPoint(p);
        int realColumnIndex = convertColumnIndexToModel(colIndex);

        if (realColumnIndex == 2) { //Sport column
          tip = "This person's favorite sport to "
              "participate in is: "
              + getValueAt(rowIndex, colIndex);
        else if (realColumnIndex == 4) { //Veggie column
          TableModel model = getModel();
          String firstName = (Stringmodel.getValueAt(rowIndex, 0);
          String lastName = (Stringmodel.getValueAt(rowIndex, 1);
          Boolean veggie = (Booleanmodel.getValueAt(rowIndex, 4);
          if (Boolean.TRUE.equals(veggie)) {
            tip = firstName + " " + lastName + " is a vegetarian";
          else {
            tip = firstName + " " + lastName
                " is not a vegetarian";
          }
        else {
          //You can omit this part if you know you don't
          //have any renderers that supply their own tool
          //tips.
          tip = super.getToolTipText(e);
        }
        return tip;
      }

      //Implement table header tool tips.
      protected JTableHeader createDefaultTableHeader() {
        return new JTableHeader(columnModel) {
          public String getToolTipText(MouseEvent e) {
            String tip = null;
            java.awt.Point p = e.getPoint();
            int index = columnModel.getColumnIndexAtX(p.x);
            int realIndex = columnModel.getColumn(index)
                .getModelIndex();
            return columnToolTips[realIndex];
          }
        };
      }
    };

    table.setPreferredScrollableViewportSize(new Dimension(50070));

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Add the scroll pane to this panel.
    add(scrollPane);
  }

  class MyTableModel extends AbstractTableModel {
    private String[] columnNames = "First Name""Last Name""Sport",
        "# of Years""Vegetarian" };

    private Object[][] data = {
        "Mary""Campione""Snowboarding"new Integer(5),
            new Boolean(false) },
        "Alison""Huml""Rowing"new Integer(3)new Boolean(true) },
        "Kathy""Walrath""Knitting"new Integer(2),
            new Boolean(false) },
        "Sharon""Zakhour""Speed reading"new Integer(20),
            new Boolean(true) },
        "Philip""Milne""Pool"new Integer(10),
            new Boolean(false) } };

    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];
    }

    /*
     * JTable uses this method to determine the default renderer/ editor for
     * each cell. If we didn't implement this method, then the last column
     * would contain text ("true"/"false"), rather than a check box.
     */
    public Class getColumnClass(int c) {
      return getValueAt(0, c).getClass();
    }

    /*
     * Don't need to implement this method unless your table's editable.
     */
    public boolean isCellEditable(int row, int col) {
      //Note that the data/cell address is constant,
      //no matter where the cell appears onscreen.
      if (col < 2) {
        return false;
      else {
        return true;
      }
    }

    /*
     * Don't need to implement this method unless your table's data can
     * change.
     */
    public void setValueAt(Object value, int row, int col) {
      if (DEBUG) {
        System.out.println("Setting value at " + row + "," + col
            " to " + value + " (an instance of "
            + value.getClass() ")");
      }

      data[row][col= value;
      fireTableCellUpdated(row, col);

      if (DEBUG) {
        System.out.println("New value of data:");
        printDebugData();
      }
    }

    private void printDebugData() {
      int numRows = getRowCount();
      int numCols = getColumnCount();

      for (int i = 0; i < numRows; i++) {
        System.out.print("    row " + i + ":");
        for (int j = 0; j < numCols; j++) {
          System.out.print("  " + data[i][j]);
        }
        System.out.println();
      }
      System.out.println("--------------------------");
    }
  }

  /**
   * 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);

    //Create and set up the window.
    JFrame frame = new JFrame("TableToolTipsDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JComponent newContentPane = new TableToolTipsDemo();
    newContentPane.setOpaque(true)//content panes must be opaque
    frame.setContentPane(newContentPane);

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

  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();
      }
    });
  }
}

           
         
  
Related examples in the same category
1. Creating a JTable Component
2. Creates tables that allow rows and columns to be added or deleted
3. Build a table from list data and column names
4. Getting the Number of Rows and Columns in a JTable Component
5. Appending a Row to a JTable Component
6. Add columns to a table through DefaultTableModel
7. Insert a row to a table through DefaultTableModel
8. Insert a row to a table through DefaultTableModel at specified row
9. Scroll Table SampleScroll Table Sample
10. Simple demonstration of JTableSimple demonstration of JTable
11. Create a table with two dimensional arrayCreate a table with two dimensional array
12. Create table with Unicode dataCreate table with Unicode data
13. Use Table to display type data(Integer, Boolean, Color)Use Table to display type data(Integer, Boolean, Color)
14. Resize TableResize Table
15. Expense TableExpense Table
16. StockTable 6: Action and Dynamic DisplayStockTable 6: Action and Dynamic Display
17. JTable selection eventsJTable selection events
18. A table with the ability to play with row and column selectionsA table with the ability to play with row and column selections
19. Table Selection modeTable Selection mode
20. Use code to change Table Selection Use code to change Table Selection
21. Display ResultSet in Table (JTable)
22. JTable(Table) with JDBC and ResultSetJTable(Table) with JDBC and ResultSet
23. ResultSet Table: extends AbstractTable and combine the ResultSet
24. List UI Properties in a JTable and sortableList UI Properties in a JTable and sortable
25. Property Table: Use JTable to display and edit propertiesProperty Table: Use JTable to display and edit properties
26. StockTable 4: Table SorterStockTable 4: Table Sorter
27. Table Sort Test
28. JTable sorter:click the table header to sort a column and a tableJTable sorter:click the table header to sort a column and a table
29. Creating image out of a JTable
30. JTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
31. JTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
32. JTable.setColumnSelectionAllowed(boolean b);
33. JTable.setRowSelectionAllowed(boolean b);
34. JTable.setCellSelectionEnabled(boolean b);
35. Handle selection and model change events for a JTable.
36. ListSelectionModel rowSelMod = JTable.getSelectionModel();
37. ListSelectionModel colSelMod = JTable.getColumnModel().getSelectionModel();
38. JTree.getModel().addTreeModelListener(new TreeModelListener())
39. Move the last visible column so it becomes the first visible column
40. the last column is moved to the first position
41. Allowing the User to Resize a Column in a JTable Component
42. Retrieve the value in the visible cell (1,2) in a JTable
43. Retrieve the value in cell (1,2) from the model
44. Change a cell in the 2nd visible column
45. Change a cell in the 3rd column in the model
46. Showing the Table Header in a Non-Scrollable JTable Component
47. Changing the Name of a Column in a JTable Component
48. Displaying an Icon in a Column Head of a JTable Component
49. Implementing Variable-Height Column Headers in a JTable Component
50. Removing the Column Headers from a Scrollable in a JTable Component
51. Creating a Custom Column Header Renderer in a JTable Component
52. Setting Column Header Tool Tips in a JTable Components
53. Setting Tool Tips on Cells in a JTable Component
54. Enable row selection (default) in a JTable
55. Enable column selection in a JTable
56. Enable cell selection in a JTable
57. Get default selection mode:MULTIPLE_INTERVAL_SELECTION
58. Allow only single a selection
59. Allow selection to span one contiguous set of rows, visible columns, or block of cells
60. Allow multiple selections of rows, visible columns, or cell blocks (default)
61. Select a column - column 0 in a JTable
62. Select an additional range of columns - columns 1 to 2
63. Deselect a range of columns - columns 0 to 1
64. Select a row - row 0
65. Select an additional range of rows - rows 1 to 2
66. Deselect a range of rows - rows 0 to 1
67. Select a cell: cell (2,1)
68. Extend the selection to include all cells (5,3)
69. Deselect a cell: cell (3,2), All cells in the row and column containing (3,2) are deselected.
70. Toggles the selection state, if it were called again, it exactly reverses the first call.
71. Select all cells
72. Deselect all cells
73. Column selection is enabled, get the indices of the selected columns
74. Row selection is enabled, Get the indices of the selected rows
75. Get selected row and selected index
76. Get the min and max ranges of selected cells
77. Check each cell in the min and max ranges of selected cells
78. Disabling Selections in a JTable Component
79. Getting the Anchor Cell in a JTable Component
80. Creating a Scrollable JTable Component
81. Disable auto resizing to make the table horizontal scrollable
82. Determining If a Cell Is Visible in a JTable Component
83. Making a Cell Visible in a JTable Component
84. Scrolling a Cell to the Center of a JTable Component
85. Show both horizontal and vertical grid lines (the default)
86. Don't show any grid lines
87. Show only vertical grid lines
88. Show only horizontal grid lines
89. Set the grid color
90. Getting the Gap Size Between Cells in a JTable Component
91. Add 5 spaces to the left and right sides of a cell.
92. Increase the row height
93. Programmatically Starting Cell Editing in a JTable Component
94. Save the current value in the cell being edited and stops the editing process
95. Discard any changes made by the user and stops the editing process
96. Disabling User Edits in a JTable
97. Disabling User Edits in a JTable with DefaultTableModel
98. Sorting the Rows in a JTable Component Based on a Column
99. Sorting a Column in a JTable Component
100. Listening for Selection Events in a JTable Component
101. Listening for Changes to the Rows and Columns of a JTable Component
102. Listening for Column-Related Changes in a JTable Component
103. Listening for Clicks on a Column Header in a JTable Component
104. Sorting and Filtering Tables
105. Use a regexFilter to filter table content
106. Creating a JTable with rows of variable height
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.