DZone Forums
Go Back   DZone Forums > Community > Languages & Frameworks > Java
Reload this Page How can you use the keyboard to activate a JComboBox within a JTable without using F2
Notices
Reply
 
LinkBack Thread Tools Display Modes
  (#1 (permalink)) Old
Member
 
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default How can you use the keyboard to activate a JComboBox within a JTable without using F2 - 02-11-2008, 04:49 PM

I am brand new to Java and I can't seem to figure this out. I have a JTable with 4 columns. The first column is a jCheckBox which is working fine. The other three are JComboBoxes. They work fine when you click them and select from the list, but our end users only want to navigate with the keyboard. They want to be able to tab to the column and just start typing the first letter of the item that they want to choose from the list and have that pop up the list and scroll to the first item in the list that starts with the letter the typed. Does anyone know how to do this? I have been playing with this for a week now and I can't seem to make it work. Please help. Below is the code for my table. Any help would be appreciated greatly. Thanks,
Lisa

Code:
 
private void LoadSTCGTable(){
     //Connect to database
        try {
                connection = ConnecttoDB.connect();
                // Tell me why I couldn't connect
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }  
              
     try {
            // Get listing of Squad Types
            tblSTCG.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {new Boolean(false), null, null, null},
            },
            new String [] {
                "SELECT", "SQUAD TYPE", "SQUAD CLASS", "SQUAD GROUP"
            }
         ));
           
          //Add Checkbox column
           tblSTCG.getColumnModel().getColumn(0).setCellEditor(tblSTCG.getDefaultEditor(Boolean.class)); 
           tblSTCG.getColumnModel().getColumn(0).setCellRenderer(tblSTCG.getDefaultRenderer(Boolean.class));       
           tblSTCG.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
           
           Whichquerytoread = 1;
           GetSql();
           sql = textfileinfo;
           stmt = connection.createStatement();
           rs = stmt.executeQuery(sql);
           md = rs.getMetaData();
           typelist = new ArrayList();
           // Loop Through Results
           typelist.add(new PairedDescriptionCodeDesc("",""));
           while (rs.next())
            {
              int i = 1;
             typelist.add( new PairedDescriptionCodeDesc(rs.getString(2),rs.getString(1))); 
                     
            }
          s1 = new TreeSet(typelist);
          
          typelist = new ArrayList(s1);
          AllTypeList = new PairedDescriptionCodeDesc[typelist.size()]; 
    	
          for (int i = 0; i<typelist.size(); i++)
             AllTypeList[i]=(PairedDescriptionCodeDesc)typelist.get(i); 
             rs.close(); 
         }
           catch (SQLException ex) {
           ex.printStackTrace();
         } 
        Vector typedata = new Vector();
         for (int i=0;i<typelist.size();i++) 
         {
            typedata.addElement((PairedDescriptionCodeDesc)typelist.get(i));
         }
         cmboType = new JComboBox();
         cmboType.setModel(new DefaultComboBoxModel(typedata));
         cmboType.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
         cmboType = new JComboBox(AllTypeList);
         cmboType.setBorder(BorderFactory.createEmptyBorder()); 
         squadcol = tblSTCG.getColumnModel().getColumn(1);
         DefaultCellEditor cmboTypeEditor = new DefaultCellEditor(cmboType);
         cmboTypeEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
         squadcol.setCellEditor(cmboTypeEditor);
     
        try {
            // Get listing of Squad Class
           Whichquerytoread = 2;
           GetSql();
           sql = textfileinfo;
           stmt = connection.createStatement();
           rs = stmt.executeQuery(sql);
           md = rs.getMetaData();
           classlist = new ArrayList();
           // Loop Through Results
           classlist.add(new PairedDescriptionCodeDesc("",""));
           while (rs.next())
            {
             classlist.add(new PairedDescriptionCodeDesc(rs.getString(2),rs.getString(1)));                     
            }
          s1 = new TreeSet(classlist);
          
          classlist = new ArrayList(s1);
          AllClassList = new PairedDescriptionCodeDesc[classlist.size()]; 
    	
          for (int i = 1; i<classlist.size(); i++)
             AllClassList[i]=(PairedDescriptionCodeDesc)classlist.get(i); 
             rs.close(); 
        }
           catch (SQLException ex) {
            ex.printStackTrace();
        } 
        Vector classdata = new Vector();
         for (int i=0;i<classlist.size();i++) 
         classdata.addElement((PairedDescriptionCodeDesc)classlist.get(i));
         cmboClass = new JComboBox();
         cmboClass.setModel(new DefaultComboBoxModel(classdata));
         cmboClass = new JComboBox(AllClassList);  
         classcol = tblSTCG.getColumnModel().getColumn(2);
         DefaultCellEditor cmboClassEditor = new DefaultCellEditor(cmboClass);
         classcol.setCellEditor(new DefaultCellEditor(cmboClass)); 
         cmboClassEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
         try {
            // Get listing of Squad Group
            Whichquerytoread = 3;
           GetSql();
           sql = textfileinfo;
           stmt = connection.createStatement();
           rs = stmt.executeQuery(sql);
           md = rs.getMetaData();
           grouplist = new ArrayList();
           // Loop Through Results
           grouplist.add(new PairedDescriptionCodeDesc("",""));
           while (rs.next())
            {
              int i = 0;
             grouplist.add( new PairedDescriptionCodeDesc(rs.getString(2), rs.getString(1))); 
                     
            }
          s1 = new TreeSet(grouplist);
     
          grouplist = new ArrayList(s1);
          AllGroupList = new PairedDescriptionCodeDesc[grouplist.size()]; 
    	
          for (int i = 0; i<grouplist.size(); i++)
             AllGroupList[i]=(PairedDescriptionCodeDesc)grouplist.get(i); 
              rs.close(); 
         }
           catch (SQLException ex) {
            ex.printStackTrace();
         } 
        Vector groupdata = new Vector();
         for (int i=0;i<grouplist.size();i++) 
         groupdata.addElement((PairedDescriptionCodeDesc)grouplist.get(i));
         cmboGroup = new JComboBox();
         cmboGroup.setModel(new DefaultComboBoxModel(groupdata));
         cmboGroup = new JComboBox(AllGroupList);  
         groupcol = tblSTCG.getColumnModel().getColumn(3);
         DefaultCellEditor cmboEditor = new DefaultCellEditor(cmboGroup);
         cmboEditor.addCellEditorListener(new NewRowCellEditorListener(tblSTCG));
         groupcol.setCellEditor(cmboEditor);
    
         
         tblSTCG.setShowHorizontalLines(false);
         tblSTCG.setShowVerticalLines(false);
                  
         TableColumnModel columnModel = tblSTCG.getColumnModel();
         TableColumn column;
         tblSTCG.getColumnModel().getColumn(0).setPreferredWidth(5);
         tblSTCG.getColumnModel().getColumn(1).setPreferredWidth(100);
         tblSTCG.getColumnModel().getColumn(2).setPreferredWidth(100);
         tblSTCG.getColumnModel().getColumn(3).setPreferredWidth(100);
         scpSTCG.setViewportView(tblSTCG); 
                 
     }
 
 private class NewRowCellEditorListener implements CellEditorListener
    {
        JTable editingTable;
        public NewRowCellEditorListener(JTable table)
        {
            editingTable = table;
        }
        public void editingStopped(ChangeEvent e)
        {
            if(editingTable.getRowCount() == editingTable.getSelectedRow() + 1)
            {
                ((DefaultTableModel)editingTable.getModel()).addRow(new Object [] {null, null, null, null});                
            }
        }
        public void editingCanceled(ChangeEvent e)
        {}
    }
Reply With Quote
  (#2 (permalink)) Old
Forum Leader
 
glennji's Avatar
 
Posts: 58
Thanks: 0
Thanked 1 Time in 1 Post
Join Date: Feb 2008
Location: London
Send a message via MSN to glennji Send a message via Yahoo to glennji Send a message via Skype™ to glennji
Default 02-14-2008, 06:03 AM

Not sure if it's any help, but the following article describes how to wire-in autocompletion to a JComboBox:

Inside JComboBox: adding automatic completion

When you tab to the component, does it become active i.e. you can use the up and down arrows, or is that the problem?
Reply With Quote
  (#3 (permalink)) Old
Member
 
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-14-2008, 09:35 AM

Thanks so much for the help. I will check this out and see if this will fix my problem.
When I tab to the combobox it doesn't seem to have focus on the component unless I hit the F2 key. I can't use the arrows until I either click on the component or hit F2. This is what I would like to avoid. I would like to be able to tab to the component and then use the down arrow or type a letter to show the pop up, but I can't seem to make that happen.
Thanks Again,
Lisa
Reply With Quote
  (#4 (permalink)) Old
Member
 
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-16-2008, 07:15 AM

Hi Lisa,
I think your best bet is to add KeyListener to the table addKeyListener(KeyListener l) and listen to certain keys and next call JTable.editCellAt(int row, int column) to put the cell in edit mode.

hope this helps,
Christiaan
Reply With Quote
  (#5 (permalink)) Old
Member
 
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-18-2008, 10:32 AM

I know this question is going to sound silly, but I am new to Java and somewhat confused on how things work, but Since I have four columns, the first being a checkbox which is working fine and the next three being ComboBoxes, would I need to check which column that is selected and then somehow set the focus to the JComboBox component inside the cell? The whole focus thing seems to be an issue for the
ComboBoxes.
Thanks
Lisa
Reply With Quote
  (#6 (permalink)) Old
Member
 
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-18-2008, 02:54 PM

Hi,
I think the problem is caused in the way the JComboBox works. It is quite a complex component actually and often behaves a bit different than you would expect, which can be quite confusing for a newcomer. I think the following code should help you:
Code:
import java.awt.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableModel;

public class Main extends JFrame {

	public Main(String title) throws HeadlessException {
		super(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(new Dimension(500,500));
		setLayout(new BorderLayout());
		final JTable table = new JTable(new DefaultTableModel(5, 4));
		
		Vector<String> options = new Vector<String>();
		options.add("option 1");
		options.add("option 2");
		options.add("option 3");
		final JComboBox combobox = new JComboBox(options);
		combobox.addAncestorListener(new AncestorListener() {

			public void ancestorAdded(AncestorEvent event) {
                                                   //make sure combobox handles key events
				combobox.requestFocusInWindow();
				
			}

			public void ancestorMoved(AncestorEvent event) {

			}

			public void ancestorRemoved(AncestorEvent event) {
			}
		});

		table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(combobox));
		
		add(new JScrollPane(table));
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Main m = new Main("test");
		m.pack();
		m.setVisible(true);
	}

}
kind regards,
Christiaan
Reply With Quote
  (#7 (permalink)) Old
Member
 
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-18-2008, 04:16 PM

THANK YOU, THANK YOU, THANK YOU!!!!!!!!!!!!!!!!! It works great.
I have been trying to get this thing to work correctly for a couple of weeks and I had tried a million different things and still couldn't get it quite right.
Thanks so much for your help.
You are a lifesaver.
Lisa
Reply With Quote
  (#8 (permalink)) Old
Member
 
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Sep 2009
Default Ahoy there! - 09-29-2009, 02:50 PM

I'm a newbie from Kansas.
Really like this forum so far and am looking forward to contributing!
Reply With Quote
  (#9 (permalink)) Old
Member
 
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Sep 2009
Default Hiya.... - 09-29-2009, 03:35 PM

hello to all of you guys,
I stumbled on this great site. Am going through a dark night of the soul and it was no chance I ended up here. Look forward to reading all the info and posts.
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
ultimate challenge in JComboBox pras Java 2 06-21-2009 08:40 PM
Keyboard shortcut to Cut/Copy/Paste current line in editor? mkjackson Eclipse 0 11-07-2008 07:43 PM
Set focus to a specific cell in a JTable diasmvds Java 0 08-12-2008 08:13 AM
Keyboard shortcut on MenuItem. jayjamba Eclipse 0 05-27-2008 01:24 AM
Hashtable and JTable Problem salmanpirzada1 Java 0 05-15-2008 08:00 AM


Copyright 1997-2009, DZone, Inc.
vBulletin Skin developed by: vBStyles.com