January 21, 2005

Java tip #1

Working with Swing JTables can be tricky. Working with custom cell editors is even trickier. Here's a tip that may save you some time and frustration.

This is a custom cell editor (based on a text field) that will automatically highlight its contents as soon as it is becomes active and save the user from having to select the text with the mouse or with the all-too-common "home - shift+end" key sequence.

The trick is to select the text after the editor gets focus. Otherwise, the JTextField object will ignore the request.

Here's the code:

private class CustomTableCellEditor
    extends DefaultCellEditor
{
  public CustomTableCellEditor()
  {
     // use a JTextField as the actual editor
     super(new JTextField());
     final JTextField editor = (JTextField) getComponent();

     editor.setName("Table.editor");
     editor.setBorder(new LineBorder(Color.black));

     // listen for focusing events
     editor.addFocusListener(new FocusListener()
     {
       public void focusGained(FocusEvent e)
       {
         // now is the time to select the text in the JTextField
         editor.selectAll();
       }

       public void focusLost(FocusEvent e) { }
     });
   }

   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
   {
     final JTextField textField = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);

     Runnable task = new Runnable() {
       public void run()
       {
         // set the focus on the JTextField
         textField.requestFocusInWindow();
       }
     };
     SwingUtilities.invokeLater(task);

     return textField;
   }
}

1 Comments:

Blogger Unknown said...

This is awesome! THNX!

December 17, 2006 1:13 PM  

Post a Comment

<< Home