PropertyTable : Java Beans « Development Class « 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 » Development Class » Java BeansScreenshots 
PropertyTable
PropertyTable
   
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.Comparator;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * This class is a JTable subclass that displays a table of the JavaBeans
 * properties of any specified class.
 */
public class PropertyTable extends JTable {
  /** This main method allows the class to be demonstrated standalone */
  public static void main(String[] args) {
    // Specify the name of the class as a command-line argument
    Class beanClass = null;
    try {
      // Use reflection to get the Class from the classname
      beanClass = Class.forName("javax.swing.JLabel");
    catch (Exception e) { // Report errors
      System.out.println("Can't find specified class: " + e.getMessage());
      System.out.println("Usage: java TableDemo <JavaBean class name>");
      System.exit(0);
    }

    // Create a table to display the properties of the specified class
    JTable table = new PropertyTable(beanClass);

    // Then put the table in a scrolling window, put the scrolling
    // window into a frame, and pop it all up on to the screen
    JScrollPane scrollpane = new JScrollPane(table);
    JFrame frame = new JFrame("Properties of JavaBean: ");
    frame.getContentPane().add(scrollpane);
    frame.setSize(500400);
    frame.setVisible(true);
  }

  /**
   * This constructor method specifies what data the table will display (the
   * table model) and uses the TableColumnModel to customize the way that the
   * table displays it. The hard work is done by the TableModel implementation
   * below.
   */
  public PropertyTable(Class beanClass) {
    // Set the data model for this table
    try {
      setModel(new JavaBeanPropertyTableModel(beanClass));
    catch (IntrospectionException e) {
      System.err.println("WARNING: can't introspect: " + beanClass);
    }

    // Tweak the appearance of the table by manipulating its column model
    TableColumnModel colmodel = getColumnModel();

    // Set column widths
    colmodel.getColumn(0).setPreferredWidth(125);
    colmodel.getColumn(1).setPreferredWidth(200);
    colmodel.getColumn(2).setPreferredWidth(75);
    colmodel.getColumn(3).setPreferredWidth(50);

    // Right justify the text in the first column
    TableColumn namecol = colmodel.getColumn(0);
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.RIGHT);
    namecol.setCellRenderer(renderer);
  }

  /**
   * This class implements TableModel and represents JavaBeans property data
   * in a way that the JTable component can display. If you've got some type
   * of tabular data to display, implement a TableModel class to describe that
   * data, and the JTable component will be able to display it.
   */
  static class JavaBeanPropertyTableModel extends AbstractTableModel {
    PropertyDescriptor[] properties; // The properties to display

    /**
     * The constructor: use the JavaBeans introspector mechanism to get
     * information about all the properties of a bean. Once we've got this
     * information, the other methods will interpret it for JTable.
     */
    public JavaBeanPropertyTableModel(Class beanClass)
        throws java.beans.IntrospectionException {
      // Use the introspector class to get "bean info" about the class.
      BeanInfo beaninfo = Introspector.getBeanInfo(beanClass);
      // Get the property descriptors from that BeanInfo class
      properties = beaninfo.getPropertyDescriptors();
      // Now do a case-insensitive sort by property name
      // The anonymous Comparator implementation specifies how to
      // sort PropertyDescriptor objects by name
      Arrays.sort(properties, new Comparator() {
        public int compare(Object p, Object q) {
          PropertyDescriptor a = (PropertyDescriptorp;
          PropertyDescriptor b = (PropertyDescriptorq;
          return a.getName().compareToIgnoreCase(b.getName());
        }

        public boolean equals(Object o) {
          return o == this;
        }
      });
    }

    // These are the names of the columns represented by this TableModel
    static final String[] columnNames = new String[] { "Name""Type",
        "Access""Bound" };

    // These are the types of the columns represented by this TableModel
    static final Class[] columnTypes = new Class[] { String.class,
        Class.class, String.class, Boolean.class };

    // These simple methods return basic information about the table
    public int getColumnCount() {
      return columnNames.length;
    }

    public int getRowCount() {
      return properties.length;
    }

    public String getColumnName(int column) {
      return columnNames[column];
    }

    public Class getColumnClass(int column) {
      return columnTypes[column];
    }

    /**
     * This method returns the value that appears at the specified row and
     * column of the table
     */
    public Object getValueAt(int row, int column) {
      PropertyDescriptor prop = properties[row];
      switch (column) {
      case 0:
        return prop.getName();
      case 1:
        return prop.getPropertyType();
      case 2:
        return getAccessType(prop);
      case 3:
        return new Boolean(prop.isBound());
      default:
        return null;
      }
    }

    // A helper method called from getValueAt() above
    String getAccessType(PropertyDescriptor prop) {
      java.lang.reflect.Method reader = prop.getReadMethod();
      java.lang.reflect.Method writer = prop.getWriteMethod();
      if ((reader != null&& (writer != null))
        return "Read/Write";
      else if (reader != null)
        return "Read-Only";
      else if (writer != null)
        return "Write-Only";
      else
        return "No Access"// should never happen
    }
  }
}

           
         
    
    
  
Related examples in the same category
1. JavaBean: BeanContextSupportJavaBean: BeanContextSupport
2. JavaBean: Test program that adds 100 beans to a contextJavaBean: Test program that adds 100 beans to a context
3. JavaBean: how to use the instantiateChild() convenience method to create a beanJavaBean: how to use the instantiateChild() convenience method to create a bean
4. JavaBean: illustrate delivery of the BeanContextMembershipEventJavaBean: illustrate delivery of the BeanContextMembershipEvent
5. JavaBean: creates all of the objects, a tests the service capabilitiesJavaBean: creates all of the objects, a tests the service capabilities
6. Bean ContainerBean Container
7. Property Test
8. Introspecting a BeanIntrospecting a Bean
9. Listening for Changes to the Selected File in a JFileChooser Dialog
10. Get a list of selected files
11. Listening for Changes to the Current Directory in a JFileChooser Dialog
12. Displaying the Current Directory in the Title of a JFileChooser Dialog
13. Setting an Accessory Component in a JFileChooser Dialog
14. Convert a bean to XML persistence
15. Listen for bean's property change event
16. List property names of a Bean
17. Prevent bean's property being serialized to XML
18. Create an instance a Bean
19. Convert an XML persistence to bean
20. Determine bean's property type
21. Listen for a constrained property change
22. Bean has a single property called property.
23. Implementing a Bound Property
24. Implementing a Constrained Property: fires a PropertyChangeEvent whenever its value is about to be changed.
25. Instantiating a Bean
26. Listing the Property Names of a Bean
27. Getting and Setting a Property of a Bean
28. Get and set the value of a property in a bean using Expression and Statement
29. Get and set an Object type property
30. gets and sets a primitive type property
31. gets and sets an array type property
32. Serializing a Bean to XML: XMLEncoder only persists the value of public properties.
33. Deserializing a Bean from XML
34. Preventing a Bean Property from Being Serialized to XML
35. Serializing an Immutable Bean Property to XML
36. Listening for a Property Change Event: A property change event is fired when a bound property is changed.
37. Listening for a Vetoable Property Change Event
38. Read bean's property value
39. Saving and restoring the state of a pretend CAD systemSaving and restoring the state of a pretend CAD system
40. An extension of ArrayList that provides some handy utilities for working with JavaBeans
41. An extension of Vector that provides some handy utilities for working with JavaBeans
42. extends SimpleBeanInfo
43. Get and set properties on a bean
44. Bean Utility
45. Is JavaBean Compliant Setter
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.