Using KeyMap in Editable JComboBoxes and JTable

I am using Keymapping for JTextFields. It works fine ! I am interested in extending the keymap feature to JComboBoxes and JTable.

if you want to do the keymapping inside the editable component of the combobox or the table, make sure you apply it on the editor component.e.g. comboBox.getEditor().getEditorComponent() and table.getCellEditor().getTableCellEditorComponent().

Similar Messages

  • Editable JComboBox in JTable

    There is a bug in Jdk1.5 (bug#4684090) - When TAB out from Editable Jcombobox in JTable, the focus is moved to outside JTable instead of next cell.
    What is the best workaround for thsi bug.
    Thanks,
    VJ

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • HT2506 I use Preview to edit photos, and would like to know if there are any Preview updates in the works. I find there is a problem with Preview crashing, or taking a very long time to "catch up" (spinning beachball of death) while I'm editing.

    I use Preview to edit photos, and would like to know if there are any updates to this program in the works. It seems Apple is constantly updating its software, except for Preview. I find it crashes all too often, and also takes forever to "catch up" with me (as in spinning beachball of death) when I'm editing a lrge amount of photos. Yes, I know I should be using Photoshop or somesuch, but it's just too **** confusing, and I don't have the time to figure it out. Thanks!!

    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
    Step 1
    Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left. If you don't see that menu, select
    View ▹ Show Log List
    from the menu bar.
    Enter the name of the crashed application or process in the Filter text field. Select the messages from the time of the last crash, if any. Copy them to the Clipboard (command-C). Paste into a reply to this message (command-V).
    When posting a log extract, be selective. In most cases, a few dozen lines are more than enough.
    Please do not indiscriminately dump thousands of lines from the log into this discussion.
    Important: Some private information, such as your name, may appear in the log. Anonymize before posting.
    Step 2
    In the Console window, look under User Diagnostic Reports for crash reports related to the crashed process. The report name starts with the name of the process, and ends with ".crash". Select the most recent report and post the entire contents — again, the text, not a screenshot. In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.) Please don’t post shutdownStall, spin, or hang logs — they're very long and not helpful.

  • I used to be able to use the tools, edit image and highlight certain items in the pdf photos. why can I not now?

    I used to be able to use the tools, edit image and highlight certain items in the pdf photos. why can I not now?

    Usually Acrobat has linked to PhotoShop to do the photo editing. You might check the updates for Acrobat and PhotoShop.

  • Problem using an editable JComboBox as JTable cell editor

    Hi,
    i have a problem using an editable JComboBox as cell editor in a JTable.
    When i edit the combo and then I press the TAB or ENTER key then all works fine and the value in the TableModel is updated with the edited one, but if i leave the cell with the mouse then the value is not passed to the TableModel. Why ? Is there a way to solve this problem ?
    Regards
    sergio sette

    if (v1.4) [url
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTa
    le.html#setSurrendersFocusOnKeystroke(boolean)]go
    hereelse [url
    http://forum.java.sun.com/thread.jsp?forum=57&thread=43
    440]go here
    Thank you. I've also found this one (the first reply): http://forum.java.sun.com/thread.jsp?forum=57&thread=124361 Works fine for me.
    Regards
    sergio sette

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • Editable JComboBox inside JTable clipping issues

    Here is an example of what I am talking about
    http://img95.imageshack.us/img95/9514/clipping4fw.png
    As you can see, the bottom of the editable JComboBox is being clipped. Is there any way to remove what looks like the invisible border there?
    Thanks
    Daniel

    I am not sure if I understand your question exactly. Your table's row height is not high enough so you may need to add a line of code like:
            table.setRowHeight(table.getRowHeight() + 4);to solve your problem.

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • Editable JComboBox and left display

    My JComboBox is editable and when a selection is made the selection is shown. When the value (String) is to large for the field, only the final part of the String is shown.
    I tried to set or move the caret position to 0 for the related JTextField obtained by
    ((JTextField) (TransferComboBox.getEditor()).getEditorComponent();).
    I tried as well to left align by doing
    JLabel jl = (JLabel) TransferComboBox.getRenderer();
    jl.setHorizontalAlignment(SwingConstants.LEFT);
    Nothing worked.

    Where did you set the caret position? You will need to do it every time you select something from the list. I tried the following and it worked:
    JComboBox cb=new JComboBox();
    cb.setEditable(true);
    cb.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent e)
        JComboBox cb=(JComboBox)e.getSource();
        JTextField editor=(JTextField)cb.getEditor().getEditorComponent();
       editor.setCaretPosition(0);
    getContentPane().add(cb, BorderLayout.NORTH);
    cb.addItem(longString1);
    cb.addItem(longString2);

  • Updating resultsets using vectors in editable JTables

    Ok i am currently retrieveing my result from a vector of vectors from a query:
    public void presentResultSet (ResultSet rs)throws SQLException {
    Vector dataVector=new Vector();
    try
    {if (!rs.next())
        JOptionPane.showMessageDialog(null, " No records for student" );
      else {
        do{
         Vector rowVector=new Vector();
         rowVector.addElement(rs.getString("studentID"));
         rowVector.addElement(rs.getString("moduleID"));
         rowVector.addElement(rs.getString("examMark"));
         dataVector.addElement (rowVector);
        }while(rs.next());
    } tab.setData(dataVector);
    dataTableScrollPane.setViewportView(dataTable);}
    catch (Exception f){ System.out.println (f.getMessage());
    This method is fine actually as it displays the results onto my GUI. But problem is, i want to add another feature of the system where users can click on any cells in the JTable, edit it and JTable will be able to help me update it onto my tables in mysql.
    I have set the public boolean iseditable into true.
    but can anyone tell me how to write the public void setValueAt method ? how to retrieve that information that the user type into the particular cell and update it onto the database ? Please help !

    Ok I assume because your using a JTable that you are using your own TableModel because the DefaultTableModel usually won't do everything you want. So if your not extending DefaultTableModel you need to start there.
    In your Table model you need a method called setValueAt which will overide the DefaultTableMode.setValueAt().
    Your TableModel's setValueAt() will get called by the table Cell Renderer when ever a cell is edited.
    So to break down setValueAt(Object aValue,int aRow,int aColumn)
    Object aValue = is whatever the user has entered in the Cell. Now its an Object and not a String because you can have all sort of things in a JTable Cell such as checkboxes,buttons, etc.
    The int Row and int Column are pretty self explanitory.
    I don't know what your table looks like but lets say you have have 3 columns
    StudentID,ModuleID,ExamMark you could do something like this
    public void setValueAt(Object aValue,int aRow,int aColumn)
            // In your table model there should be some Vector that contains your other 
            // Vectors. In this example "rows" is that Vector
           // this assigns rowVector the Vector of Columns at the row
           // that was edited by the user in the JTable. It should contain the 3 columns
           Vector rowVector = (Vector)rows.elementAt(aRow);
            // this will overwrite the current value at that column
            rowVector.setElementAt(aValue,aColumn );
            // you may need to cast aValue into whatever Object you plan on storing probably a string
            // ie. rowVector.setElementAt((String)aValue,aColumn );
    } Your Table Model should now contain the new value in its rows Vector all you have do is add someway to save that new Vector back into the Database.
    Hope this helps I didn't compile it but I think it will work or at least give you a better understanding....
    Or maybe I confused you more.
    Good Luck
    Justin

  • Escape key "dies" in combobox and JTable

    I have set in my JDialog the default key ESCAPE as this standard code:
              KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
              int param = JComponent.WHEN_IN_FOCUSED_WINDOW;
              root.getInputMap(param).put(escKey, "close");
              root.getActionMap().put("close", actionCancel);
         this.btCancel.setAction(actionCancel);
    The problem is when I have JComboBoxs and JTables. All key events seem to be consumed
    In this components (and maybe more components). So, if I press ESCAPE and my focus
    in a combobox, the dialog won't close.
    How could I work around this?
    thank you

    I've got the solution!
    I have a javaBean (JPanel) that has only one JComboBox. I trigger key pressed (don't know
    if should be key released in this case) on comboBox. Then I check if...
    this.comboBox.isPopupVisible().
    Simple. If popup is not visible and dispatch the event to this.
    I just wonder how the event goes to my javaBean, my javabean is in a dialog and this
    dialog of mine ends up to catch the event. ???
    Ok, this stays has a solution for future developers to found - in case they guess that
    right keywords :)

  • Bug when using JComboBox as JTable CellEditor

    Hello! I have a JTable that displays database information, and one of the columns is editable using a JComboBox. When the user selects an item from the JComboBox, the database (and consequently the JTable) is updated with the new value.
    Everything works fine except for a serious and subtle bug. To explain what happens, here is an example. If Row 1 has the value "ABC" and the user selects the editable column on that row, the JComboBox drops down with the existing value "ABC" already selected (this is the default behavior, not something I implemented). Now, if the user does not select a new value from the JComboBox, and instead selects the editable column on Row 2 that contains "XYZ", Row 1 gets updated to contain "XYZ"!
    The reason that is happening is because I'm updating the database by responding to the ActionListener.actionPerformed event in the JComboBox, and when a new row is selected, the actionPerformed event gets fired BEFORE the JTable's selected row index gets updated. So the old row gets updated with the new row's information, even though the user never actually selected a new item in the JComboBox.
    If I use ItemListener.itemStateChanged instead, I get the same results. If I use MouseListener.mousePressed/Released I get no events at all for the JComboBox list selection. If anyone else has encountered this problem and found a workaround, I would very much appreciate knowing what you did. Here are the relavent code snippets:
    // In the dialog containing JTable:
    JComboBox cboRouteType = new JComboBox(new String[]{"ABC", "XYZ"));
    cboRouteType.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ev) {
              doCboRouteTypeSelect((String)cboRouteType.getSelectedItem());
    private void doCboRouteTypeSelect(String selItem) {
         final RouteEntry selRoute = tblRoutes.getSelectedRoute();
         if (selRoute == null) { return; }
         RouteType newType = RouteType.fromString(selItem);
         // Only update the database if the value was actually changed.
         if (selRoute.getRouteType() == newType) { return; }
         RouteType oldType = selRoute.getRouteType();
         selRoute.setRouteType(newType);
         // (update the db below)
    // In the JTable:
    public RouteEntry getSelectedRoute() {
         int selIndx = getSelectedRow();
         if (selIndx < 0) return null;
         return model.getRouteAt(selIndx);
    // In the TableModel:
    private Vector<RouteEntry> vRoutes = new Vector<RouteEntry>();
    public RouteEntry getRouteAt(int indx) { return vRoutes.get(indx); }

    Update: I was able to resolve this issue. In case anyone is curious, the problem was caused by using the actionPerformed method in the first place. Apparently when the JComboBox is used as a table cell editor, it calls setValueAt on my table model and that's where I'm supposed to respond to the selection.
    Obviously the table itself shouldn't be responsible for database updates, so I had to create a CellEditListener interface and implement it from the class that actually does the DB update in a thread and is capable of reporting SQL exceptions to the user. All that work just to let the user update the table/database with a dropdown. Sheesh!

  • JTable with editable JComboBoxes

    For some reason once I added editable JComboBoxes to a JTable I can no longer tab among the fields in the table. If I just select a cell, I can tab to the other cells in that row, and then to proceeding rows as I reach the end of each. However if I double click the cell and enter data or select from the combobox. I no longer can tab to the next cell. At that point once I do hit tab, I am taken to the next table. Not the next cell in the row, or the next row in the current table.
    I have tried messing with a bunch of listeners, but I am not using the right listener on the right object? What listerner and object should the listener belong to? Table, model, cell editor, combobox, jpanel, jframe ? I hope this is not to vague.

    Well I am starting to think it's an implementation issue. Like I am not doing it how I should. I am basically doing
    JComboBox jcb = new JComboBox();
    jcb.setEditable(true);
    column.setCellEditor(new DefaultCellEditor(jcb));
    When I think I should be inheriting, and creating my own editor and/or renderer? Now my combobox vars are globally available in the class, so I can set and clear their contents. It does not matter that each row in the table has the same content in the combo boxes, that's basically what I want. User to be able to select an existing entry or make a new one.
    What I am trying to do is on tables have a drop down box that shows up when a user types a matching entry. If no entry matches, no popup box. If entry matches, box pops up and shows possible entries starting with what they are typing. Like code completion in IDE's like Netbeans. However I am doing this in a table. I thought a JComboBox would be a good widget to start with?

  • Editable JComboBox in a JTable

    I posted my problem into the "Java Essentials/Java programming" forum but it would be much better if I'd posted it here into the swing theme :).
    Here it is what I posted:
    Funky_1321
    Posts:8
    Registered: 2/22/06
    editable JComboBox in a JTable
    Oct 21, 2006 1:32 PM
    Click to email this message
    Hello!
    Yesterday I posted a problem, solved it and there's another one, referring the same theme.
    So it's about a editable JComboBox with autocomplete function. The combo is a JTables cellEditors component. So it's in a table. So when the user presses the enter key to select an item from the JComboBox drop down menu, I can't get which item is it, not even which index has the item in the list. If for exemple the JComboBox isn't in a table but is added on a JPanel, it works fine. So I want to get the selectedItem in the actionPerformed method implemented in the combo box. I always get null instead of the item.
    Oh... if user picks up some item in the JComboBox-s list with the mouse, it's working fine but I want that it could be picked up with the enter key.
    Any solutions appreciated!
    Thanks, Tilen
    YAT_Archivist
    Posts:1,321
    Registered: 13/08/05
    Re: editable JComboBox in a JTable
    Oct 21, 2006 1:55 PM (reply 1 of 2)
    Click to email this message
    I suggest that you distill your current code into a simple class which has the following attributes:
    1. It can be copied and pasted and will compile straight out.
    2. It has a main method which brings up a simple example frame.
    3. It's no more than 50 lines long.
    4. It demonstrates accurately what you've currently got working.
    Without that it's hard to know exactly what you're currently doing, and requires a significant investment of time for someone who hasn't already solved this problem before to attempt to help. I'm not saying that you won't get help if you don't post a simple demo class, but it will significantly improve your chances.
    Funky_1321
    Posts:8
    Registered: 2/22/06
    Re: editable JComboBox in a JTable
    Oct 21, 2006 2:11 PM (reply 2 of 2)
    Click to email this message
    Okay ... I'll write the code in short format:
    class acJComboBox extends JComboBox {
      public acJComboBox() {
        this.setEditable(true);
        this.setSelectedItem("");
        this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
         // ... code code code
         // that's tricky ... the method getSelectedItem() always returns null - remember; the acJComboBox is in a JTable!
         if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getEditor().setItem(getSelectedItem()); }
    }And something more ... adding the acJComboBox into the JTable:
    TableColumn column = someTable.getColumn(0);
    column.setCellEditor(new DefaultCellEditor(new acJComboBox());
    So if the user presses the enter key to pick up an item in the combo box drop down menu, it should set the editors item to the selected item from the drop down menu (
    getEditor().setItem(getSelectedItem());
    When the acJComboBox is on a usual JPanel, it does fine, but if it's in the JTable, it doesn't (getSelectedItem() always returns null).
    Hope I described the problem well now ;).

    Okay look ... I couldn't write a shorter code just for an example. I thought that my problem could be understoodable just in mind. However ... type in the first combo box the letter "i" and then select some item from the list with pressing the enter key. Do the same in the 2nd combo box who's in the JTable ... the user just can't select that way if the same combo is in the JTable. Why? Thanks alot for future help!
    the code:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    class Example extends JFrame {
        private String[] columns = { "1", "2", "3" };
        private String[][] rows = {};
        private DefaultTableModel model = new DefaultTableModel(rows, columns);
        private JTable table = new JTable(model);
        private JScrollPane jsp = new JScrollPane(table);
        private acJComboBox jcb1 = new acJComboBox();
        private acJComboBox jcb2 = new acJComboBox();
        public Example() {
            // initialize JFrame
            this.setLayout(null);
            this.setLocation(150, 30);
            this.setSize(300, 300);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            // initialize JFrame
            // initialize components
            Vector<String> v1 = new Vector<String>();
            v1.add("item1");
            v1.add("item2");
            v1.add("item3");
            jcb1.setData(v1);
            jcb2.setData(v1);
            jcb1.setBounds(30, 30, 120, 20);
            jsp.setBounds(30, 70, 250, 100);
            add(jcb1);
            add(jsp);
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setCellEditor(new DefaultCellEditor(jcb2));
            Object[] data = { "", "", "" };
            model.addRow(data);
            // initialize components
            this.setVisible(true);
        public static void main(String[] args) {
            Example comboIssue = new Example();
    class acJComboBox extends JComboBox {
        private Vector<String> data = new Vector<String>();
        private void init() {
            this.setEditable(true);
            this.setSelectedItem("");
            this.setData(this.data);
            this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
                        if (e.getKeyCode() != 38 && e.getKeyCode() != 40) {
                            String a = getEditor().getItem().toString();
                            setModel(new DefaultComboBoxModel());
                            int st = 0;
                            for (int i = 0; i < getData().size(); i++) {
                                String str1 = a.toUpperCase();
                                String tmp = (String)getData().get(i).toUpperCase();
                                if (str1.length() <= tmp.length()) {
                                    String str2 = tmp.substring(0, str1.length());
                                    if (str1.equals(str2)) {
                                        DefaultComboBoxModel model = (DefaultComboBoxModel)getModel();
                                        model.insertElementAt(getData().get(i), getItemCount());
                                        st++;
                            getEditor().setItem(new String(a));
                            JTextField jtf = (JTextField)e.getSource();
                            jtf.setCaretPosition(jtf.getDocument().getLength());
                            hidePopup();
                            if (st != 0 && e.getKeyCode() != 10 && new String((String)getEditor().getItem()).length() != 0) { showPopup(); }
                            if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getSelectedItem(); }
                            if (new String((String)getEditor().getItem()).length() == 0) { whenEmpty(); }
            this.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) {
                hidePopup();
        // - constructors -
        public acJComboBox() {
            init();
        public acJComboBox(Vector<String> data) {
            this.data = data;
            init();
        // - constructors -
        // - interface -
        public void whenEmpty() { } // implement if needed
        public void setData(Vector<String> data) {
            this.data = data;
            for (int i = 0; i < data.size(); i++) {
                this.addItem(data.get(i));
        public Vector<String> getData() {
            return this.data;
        // - interface -
    }

  • Using Editor JComboBox is JTable CellEditors

    Hello all.
    I have a JTable with an editable JComboBox as a cell editor, but when it is activated the text inside the edit area is cut off.
    Example: http://www.rightstep.org/Image.jpg
    What can I do with the JComboBox settings to make more of the text visible? If some of it is cut off, that is not a huge issue -- but I'd like as much visible as possible for when people need to enter text that is not already in the drop down box.
    Thanks for any help!

    A combo box has an associated editor which in turn has an associated textfield.... get the textfield and set a null or empty border on it.
    ;o)
    V.V.

Maybe you are looking for