Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Creating Your Own Editors

In addition to letting you customize the rendering of cells, the table component allows you to attach custom cell editors to columns of cells. As a result, you can edit cell values in different ways. To see what a cell editor looks like, take a look at Figure 12.

Figure 12 Because a table component supports custom column editing, you can edit true/false values using a more natural editor, such as a check box.

As with TableDemo10, the TableDemo12 program that generated Figure 12 was not hard to write because it relies on one of a table component's default editors. To see what TableDemo12's source code looks like, examine Listing 12.

Listing 12: TableDemo12.java

// TableDemo12.java

import java.awt.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

class TableDemo12 extends JFrame
{
  TableDemo12 (String title)
  {
   // Pass the title to the JFrame superclass so that it appears in
   // the title bar.

   super (title);

   // Tell the program to exit when the user either selects Close
   // from the System menu or presses an appropriate X button on the
   // title bar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a my table model consisting of 4 rows by 3 columns.

   MyTableModel mtm = new MyTableModel (4, 3);

   // Assign column identifiers (headers) to the columns.

   String [] columnTitles =
   {
     "Name",
     "Address",
     "Unemployed",
   };

   mtm.setColumnIdentifiers (columnTitles);

   // Populate all cells in the my table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   Boolean [] employmentStatus =
   {
     new Boolean (false),
     new Boolean (true),
     new Boolean (false),
     new Boolean (true)
   };

   int nrows = mtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      mtm.setValueAt (names [i], i, 0);
      mtm.setValueAt (addresses [i], i, 1);
      mtm.setValueAt (employmentStatus [i], i, 2);
   }

   // Create a table using the previously created my table model.

   JTable jt = new JTable (mtm);

   // Place the table in a JScrollPane object (to allow the table to
   // be vertically scrolled and display scrollbars, as necessary).

   JScrollPane jsp = new JScrollPane (jt);

   // Add the JScrollPane object to the frame window's content pane.
   // That allows the table to be displayed within a displayed
   // scroll pane.

   getContentPane ().add (jsp);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 110 vertical pixels.

   setSize (400, 110);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public static void main (String [] args)
  {
   // Create a TableDemo12 object, which creates the GUI.

   new TableDemo12 ("Table Demo #12");
  }
}

class MyTableModel extends DefaultTableModel
{
  MyTableModel (int rows, int cols)
  {
   super (rows, cols);
  }

  public Class getColumnClass (int columnIndex)
  {
   // If column is the Unemployed column, return Boolean.class so
   // that the Boolean renderer and editor will be used.

   if (columnIndex == 2)
     return Boolean.class;
   else
     return Object.class;
  }
}

Because TableDemo12 is so similar to TableDemo10 in structure, there really isn't much to say about the code. However, you might find it interesting to note that the table component chooses both a Boolean renderer and a Boolean editor when getColumnClass(int columnIndex) returns Boolean.class for the third column. In fact, each default renderer has its own corresponding default editor. Apart from the Boolean default editor, the other default editors don't look much different from the Object.class default editor.

Editors in Depth

Although it's nice to be able to use a default editor, there are times when you want to add your own custom editor. For example, you might want to modify TableDemo10 so that it allows you to pick colors from a color chooser, instead of forcing you to modify a cell's string text. As you might have guessed, you will be given an opportunity to see a TableDemo13 program that extends TableDemo10 with such an editor. However, before you can see that program, you need to understand how a table component deals with the editing task.

A table component's UI delegate (such as BasicTableUI) initiates editing in one of two ways. First, if you press any key other than F2 (and some special keys, such as the arrow keys), JTable's processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) method automatically starts the editor for the focused cell. Second, if you press F2 or double-click the left mouse button while the mouse pointer is positioned over some cell, an action named startEditing is invoked. Specifically, its actionPerformed(ActionEvent e) method gets called and starts the editor for the focused cell. Regardless, JTable's editCellAt(int rowIndex, int columnIndex) method is called with the row and column indexes of the focused cell.

The editCellAt(int rowIndex, int columnIndex) method calls JTable's editCellAt(int rowIndex, int columnIndex, EventObject e) method with null assigned to e. That latter method first determines whether the cell at (rowIndex, columnIndex) is read-only by calling JTable's isCellEditable(int rowIndex, int columnIndex) convenience method. If that cell is read-only, editCellAt(int rowIndex, int columnIndex, EventObject e) returns and the cell is not edited.

Assuming that the cell is editable, editCellAt(int rowIndex, int columnIndex, EventObject e) calls JTable's getCellEditor(int rowIndex, int columnIndex) method to return a reference to an object whose class implements the TableCellEditor interface. That object serves as the cell's editor. The following source code (taken from the JTable class) shows how getCellEditor(int rowIndex, int columnIndex) works:

public TableCellEditor getCellEditor(int row, int column)
{
  // Acquire a reference to the TableColumn object associated with
  // column.

  TableColumn tableColumn = getColumnModel ().getColumn (column);

  // Fetch the editor associated with the TableColumn object.

  TableCellEditor editor = tableColumn.getCellEditor ();

  // If the developer has not specified an editor for that column,
  // obtain a reference to the default editor.

  if (editor == null)
    editor = getDefaultEditor (getColumnClass (column));

  return editor;
}

If getCellEditor(rowIndex, columnIndex) returns a non-null reference to an editor, and if editing can start on that cell, editCellAt(int rowIndex, int columnIndex, EventObject e) calls JTable's prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex) method to prepare the editor for editing. The following code fragment (taken from JTable's prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex) method) shows what happens:

Object value = getValueAt (rowIndex, columnIndex);

boolean isSelected = isCellSelected (rowIndex, columnIndex);

Component comp = editor.getTableCellEditorComponent (this, value, 
                           isSelected, 
                           row, column);

First, JTable's getValueAt(int rowIndex, int columnIndex) convenience method is called to retrieve the value located at (rowIndex, columnIndex) in the data model. Then JTable's isCellSelected(rowIndex, columnIndex) method is called to determine whether that cell has been selected so that an appropriate selection rectangle can be drawn. Finally, the editor's getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int columnIndex) method is called to configure the editor and return a Component object that carries out the editing. That object's reference returns from prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex).

Assuming that a non-null Component reference returns, editCellAt(int rowIndex, int columnIndex, EventObject e) calls several methods to initialize the editor. One of those methods attaches a CellEditorListener to the editor. The listener responds to various events, such as editing canceled and editing stopped. If an editing stopped event occurs, the value is read from the editor (via the editor's getCellEditorValue() method) and stored in the model (via the model's setValueAt(Object value, int rowIndex, int columnIndex) method.

You can create your own editor either by subclassing the AbstractCellEditor class and implementing the TableCellEditor interface or by subclassing the DefaultCellEditor class. Listing 13's TableDemo13 source code demonstrates the former approach.

Listing 13: TableDemo13.java

// TableDemo13.java

import java.awt.*;

import javax.swing.*;
import javax.swing.table.*;

class TableDemo13 extends JFrame
{
  TableDemo13 (String title)
  {
   // Pass the title to the JFrame superclass so that it appears in
   // the title bar.

   super (title);

   // Tell the program to exit when the user either selects Close
   // from the System menu or presses an appropriate X button on the 
   // title bar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a my table model consisting of 4 rows by 3 columns.

   MyTableModel mtm = new MyTableModel (4, 3);

   // Assign column identifiers (headers) to the columns.

   String [] columnTitles =
   {
     "Name",
     "Address",
     "Favorite Color",
   };

   mtm.setColumnIdentifiers (columnTitles);

   // Populate all cells in the my table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   Color [] favoriteColors =
   {
     Color.red,
     Color.blue,
     Color.green,
     Color.red
   };

   int nrows = mtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      mtm.setValueAt (names [i], i, 0);
      mtm.setValueAt (addresses [i], i, 1);
      mtm.setValueAt (favoriteColors [i], i, 2);
   }

   // Create a table using the previously created default table
   // model.

   JTable jt = new JTable (mtm);

   // Establish a color renderer for the third column.

   jt.getColumnModel ().getColumn (2).
              setCellRenderer (new ColorRenderer());

   // Establish a color editor for the third column.

   jt.getColumnModel ().getColumn (2).
              setCellEditor (new ColorEditor ());

   // Place the table in a JScrollPane object (to allow the table to
   // be vertically scrolled and display scrollbars, as necessary).

   JScrollPane jsp = new JScrollPane (jt);

   // Add the JScrollPane object to the frame window's content pane.
   // That allows the table to be displayed within a displayed
   // scroll pane.

   getContentPane ().add (jsp);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 110 vertical pixels.

   setSize (400, 110);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public static void main (String [] args)
  {
   // Create a TableDemo13 object, which creates the GUI.

   new TableDemo13 ("Table Demo #13");
  }
}

class ColorEditor extends AbstractCellEditor implements TableCellEditor
{
  private JLabel l = new JLabel ("");

  public Object getCellEditorValue ()
  {
   // Return the label's background color so that it can be stored
   // in the table component's model.

   return l.getBackground ();
  }

  public Component getTableCellEditorComponent (JTable table,
                         Object value,
                         boolean isSelected,
                         int row,
                         int column)
  {
   if (value instanceof Color)
   {
     // Display a JColorChooser dialog box that allows the user to
     // choose a color from a visual color picker.

     Color c = JColorChooser.showDialog (null, "Choose color",
                       (Color) value);

     // If user didn't Cancel the Color Chooser, set the label's
     // background to the chosen color, as expressed via a Color
     // object. Otherwise, assign the Color object, as expressed
     // by value, to the label's background. If that is not done,
     // a future return l.getBackground (); in 
     // getCellEditorValue() will return the most recently set 
     // background color, which will then be assigned to the table
     // component's model. That color will most likely not be the
     // same as the color passed in value. As a result, a cell's 
     // original background color will disappear.

     if (c != null)
       l.setBackground (c);
     else
       l.setBackground ((Color) value);
   }

   // Return a reference to the component that does the editing.
   // Because a JLabel reference is being returned, there won't be
   // any editing. The reason editing isn't needed is that the color
   // chooser is being used to obtain the color.

   return l;
  }
}

class ColorRenderer extends DefaultTableCellRenderer
{
  public Component getTableCellRendererComponent (JTable table,
                          Object value,
                          boolean isSelected,
                          boolean isFocus,
                          int row,
                          int column)
  {
   if (value instanceof Color)
     setBackground ((Color) value);

   // Prevent value.toString ()'s returned String from being
   // rendered.

   value = ""; 

   // Allow the superclass to complete configuring the renderer.

   return super.getTableCellRendererComponent (table, value,
                         isSelected, isFocus,
                         row, column);
  }
}

class MyTableModel extends DefaultTableModel
{
  MyTableModel (int rows, int cols)
  {
   super (rows, cols);
  }

  public Class getColumnClass (int columnIndex)
  {
   // If column is the Favorite color column, return Color.class so
   // that the Color renderer and editor will be used.

   if (columnIndex == 2)
     return Color.class;
   else
     return Object.class;
  }
}

When you run TableDemo13, you see a table component consisting of three columns. The rightmost column displays colored cells, thanks to the ColorRenderer. If you double-click (or even single-click) on one of those colored cells—or if you press F2 when one of those cells is focused, a color chooser dialog box appears as an editor and allows you to select a replacement color. Assuming that you click the color chooser's OK button after selecting a color, you will not see the new color until you select a different row. However, if you cancel the color chooser, the cell's original color will remain.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020