Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTable with Editable JComboBox

843806Oct 15 2007 — edited Mar 4 2008
Hello,

I am trying to allow the user to select an item from an editable jcombobox when it is a cell editor in a jtable. Selecting the item with the mouse works fine, but I can't get it to work when you try to select an item by pressing enter.

Please see the following example code. Run the application and click on a table cell to expand the popup list. Then (instead of clicking on an item with mouse), highlight an item with the up/down arrows and hit enter. The popup will close, but the value will not change. Any help is greatly appreciated.

I've tried adding action listeners to the jcombobox, the jcombobox editor, and I can't seem to find the new value anywhere.

Thanks
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;


public class TableTest extends JFrame
{
   public static void main( String[] args )
   {
      TableTest table_test = new TableTest();

      table_test.setSize( 400, 400 );
      table_test.setLocation( 200, 200 );
      table_test.setVisible( true );
   }

   private TableTest()
   {
      super( "Table Test" );
      super.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      DefaultTableModel model = new DefaultTableModel();
      model.addColumn( "Value" );
      model.addRow( new Object[] { "5" } );
      model.addRow( new Object[] { "10" } );
      model.addRow( new Object[] { "" } );

      final JComboBox combo_box = new JComboBox();
      combo_box.setEditable( true );
      for( int i = 0; i < 20; i++ )
         combo_box.addItem( Integer.toString( i ) );

      TableCellEditor editor = new DefaultCellEditor( combo_box );
      DefaultTableColumnModel column_model = new DefaultTableColumnModel();
      column_model.addColumn( new TableColumn( 0, 10, null, editor ) );

      JTable table = new JTable( model, column_model );
      table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

      JPanel content = new JPanel( new BorderLayout() );
      content.add( table, BorderLayout.CENTER );
      super.setContentPane( content );

      table.getSelectionModel().setSelectionInterval( 0, 0 );
   }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 1 2008
Added on Oct 15 2007
6 comments
438 views