Editing JComboBox with keyboard

One of my JTable columns has JComboBox. When I select the entries with the mouse it works fine. But when I use the keyboard and select the entries it is not getting updated in the display. Can somebody provide me pointers to fix this problem.
Thanks
Mahesh

See here the complete class.
just check for the combo_keyPressed method. There will be some other methods you will need in order to make it work.
Check it out and see what you need.
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
* <p>Title: KComboBox Class</p>
* <p>Description: This class provides the functionality for selecting the closest value
* in the combobox compared to the keystrokes which are made. There are two additional
* parameters added to this class which provides the option of the casesensitivity comparision
* between the element in the list and the keystrokes made. Also the interval for reseting
* the keystroke string is an additional parameter. These can be set through the 2 methods
* setCasesensitivity and the setStrokeInterval. If those two parameters are not set
* by the user. The default values will be use in that case.</p>
* @author Stefaan Delanghe
* @version 1.0
public class KComboBox extends JComboBox
* the default value for the keystroke interval
private final static long const_DEFAULT_STROKEINTERVAL = 900;
* the default value for the casesentive option
private final static boolean const_DEFAULT_CASESENITIVE = false;
* holds the time which may not be bypassed to reset the current keystrokes
private long m_strokeinterval = const_DEFAULT_STROKEINTERVAL;
* holds if the comparison of the keystrokes must be case sensitive or not
private boolean m_casensitive = const_DEFAULT_CASESENITIVE;
* holds the time of the first keystroke initiated
private long m_beginkeypress = System.currentTimeMillis();
* holds the time when the next key was pressed
private long m_nextkeypress;
* holds the current pressed key
private char m_keychar;
* holds the keystrokes pressed within the interval
private String m_keystring;
* default constructor with addition of adding the listener for the keystrokes.
public KComboBox() { super(); setListeners(); }
* constructor with setting a combobox model and adding the listener for the keystrokes.
* @param _model ComboBoxModel The model definition for the combobox
public KComboBox(ComboBoxModel _model) { super(_model); setListeners(); }
* constructor with setting of the elements as an object array and as addition the listener
* for the keystrokes.
* @param _items Object[] List of the elements which should be included in the combobox
public KComboBox(Object[] _items) { super(_items); setListeners(); }
* constructor with setting of the elements as a vector and as addition the listener
* for the keystrokes.
* @param _items Vector List of the elements which should be included in the combobox
public KComboBox(Vector _items) { super(_items); setListeners(); }
* sets the listeners needed for the implementation of the keystroke. This method
* only defines the keypressed method for handling the keystrokes.
private void setListeners()
addKeyListener(new KeyAdapter()
public void keyPressed(KeyEvent e)
combo_keyPressed(e);
* method for interpretation of the keystrokes and select the closest element in the combobox.
* @param e KeyEvent object holding the values and method in association with the keystroke
private void combo_keyPressed(KeyEvent e)
boolean reset = false;
boolean found = false;
String listvalue = "";
m_nextkeypress = System.currentTimeMillis();
if(m_nextkeypress - m_beginkeypress > m_strokeinterval)
reset = true;
if(reset)
m_keychar = e.getKeyChar();
m_keystring = String.valueOf(m_keychar);
m_beginkeypress = System.currentTimeMillis();
m_nextkeypress = m_beginkeypress;
else
m_keystring += e.getKeyChar();
m_nextkeypress = System.currentTimeMillis();
int cntlist = 0;
for(cntlist = 0; cntlist < getItemCount() && !found; cntlist++)
listvalue = getItemAt(cntlist).toString();
if(m_keystring.length() > listvalue.length())
found = true;
else
if(listvalue.length() >= m_keystring.length())
if(m_casensitive)
if(listvalue.substring(0,m_keystring.length()).compareTo(m_keystring) >= 0)
found = true;
else
if(listvalue.substring(0,m_keystring.length()).compareToIgnoreCase(m_keystring) >= 0)
found = true;
cntlist--;
if(found)
setSelectedIndex(cntlist);
* sets the interval between keystrokes that are concatenated for comparison to the
* element in the combobox. Each time that interval has been passed the keystroke string
* will be reset.<br>
* A default value is specified to 900.
* @param _interval long The new interval value
public void setStrokeInterval(long _interval)
m_strokeinterval = _interval;
* set the if the comparison of the keystrokes should be case sensitive or not. A default
* value is specified with a contact which is false.
* @param _set boolean use true in case you want to set the casesentivity otherwise use false
public void setCasensitive(boolean _set)
m_casensitive = _set;
}

Similar Messages

  • 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 -
    }

  • 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?

  • JCalendar and JcomboBox access with keyboard

    Hello guys, What can i do?, ive implemented a JComboBox (this have autocompletion, downloaded of http://www.orbital-computer.de/JComboBox/), and Jcalendar inside a JTable but the problem appear when i try access to typing/input with keyboard in a JComboBox (i cant), this only activate with a mouse, the same ocurr with the next cell (JCalendar), this only activate with a mouse.
    What i need to change in the source code??
    Thanks...

    i'm not sure what you mean by "HTML Access Keys/Keyboard Shortcuts", but your browser's shortcut keys should continue to work.

  • Search Editable JComboBox

    I would like to Search in Editable JComboBox. (Just like Google.com search window).
    I have populated the List for the JComboBox. I already have following code in my Program.
    jComboBox1.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jComboBox1KeyTyped(evt);
    I would like to do showPopup() in jComboBox1KeyTyped() as I start typing keys on the keyboard. But it should start at the KeyTyped and also String Typed.
    For example.
    If my list contains {"Henry","Google", "Gould", "Goulwy", "Gpater"}
    and If I start typing "Goul", popup menu should start with "Google" and then keep moving to "Goulwy" and so on? (Just like Google.com search as I mentioned above)

    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=5124613

  • 870A Fuzion Power has problem with keyboard and mouse movement only in games.

    Hey guys,
    recently built a new system and chose to go with the 870A Fuzion Power mainboard, everything has gone very smoothly execpt for one problem, only when I play games like Crysis 2 ect the mouse seems to jolt around now and again and the keyboard decides to stop responding if I hold down the movement keys, and this is only in game not surfing the web for example. Now, I am using a wireless mouse and keyboard but I plugged in a PS/2 keyboard and the exact same thing happened. I've installed all of the drivers that came with this board and the drivers for the mouse and keyboard. Any of you guys ever had this sort of problem or know how to fix this?
    Thanks.

    I bought a new Macbook pro in june 2010, I didn't have any keyboard or mouse issues prior to upgrading to 10.6.4 supposedly this update was made to fix some issues with keyboard and mouse becoming unresponsive. For me the opposite happened. after the upgrade, my keyboard and mouse (trackpad) becomes sometimes partially unresponsive or totally unresponsive. the only way to solve the problem is by completely turning of the computer and turning back on.. granted it doesn't happen very often.. generally once every about 2-3 weeks but it is still annoying though..
    I didn't have a chance to use the computer too much on the previous version (10.6.3) so I don't know if it is software related or hardware related.. any thoughts?
    Message was edited by: msoued

  • My MacBook Pro Retina's Bluetooth chipset unknown/odd login message on the login screen states Login Window Authentication Login window Name edit text has keyboard focus. In addition, the login screen is not remembering me

    I have been experiencing several issues with my MacBook Pro Retina mid 2012. My MBPR is scheduled to go into the depot. However, I am wondering if anyone may be able to shed light on a few issues as this is the third "official" time my MBPR is going back for service ("one depot" trip; "one authorized" dealer; several in-store visits).
    My Bluetooth is stating that the Bluetooth Chipset is Unknown (0). I also have had Bluetooth Preferences mysteriously change on me. In addition, while Bluetooth is off there are two serial modems turning on. I have turned them off, but they continue to pop up.
    In addition, when I log in, my MBPR is not remembering me and my login name is not appearing on the slate-gray screen. The name and password are blank and the following message appears in the lower left hand corner. "login window authentication login window Name edit text has keyboard focus."  As a side note, I am the only user. The login issue is a recent occurrence as we just totally wiped it again via a Command + R, and I don't believe I have an accessibility setting set to anything that would cause this, but wanted to check.
    Should I be concerned here? Has anyone else had issues like this? I don't want to worry if I don't have to. I have had so many issues over the course of nine months. 5-6 wipes. Airport card replaced and I am about to pull my hair out if my MBPR doesn't come back worldly like clock work this time. I just can't send my days trying to get a $2300 product to work for me any longer. No idea what is wrong with it, but it is driving me insane. Cross your fingers for me and any guidance you have or thoughts would be welcomed. Thank you. EMM

    A few more issues...
    In Console, the following is greyed out:
    User and Diagnostic reports
    Com.apple.launchd.peruser.0
    Com.apple.launchd.peruser.88
    Com.apple.launchd.peruser.89
    Com.apple.launchd.peruser.92
    Com.apple.launchd.peruser.97
    Com.apple.launchd.peruser.200
    Com.apple.launchd.peruser.201
    Com.apple.launchd.peruser.202
    Com.apple.launchd.peruser.212
    *[user logs are accessible]
    Krb5kdc
    Radius
    My guest files are locked, but again I am the administrator of MBPR.
    I am worried about a keystroke logged or at least, trying to rule it out.
    Also:
    Mdworker32(225) [and other mdworker numbers] are sandboxing; stating deny Mach-lookup
    Com.apple.Powermanagement.control, etc. long attachment with those files with version: ??? (???).
    Postinstall: removing applications/Microsoft Office 2011/Microsoft Outlook.app
    WARNINGS in Console include:
    [NSImage compositeToPoint:fromRect:operation:fraction:] is deprecated in MacOSX 19.8 and later. Please use -[NSImage drawAtPoint:fromRect:operation:fraction] instead.
    There are a ton of other warnings. Before I go through this again, can someone tell me if this is normal (all of it -- above too); or if these are symptoms is a keystroke logger or hardware issues? 
    I ask because originally, when my computer went in for diagnostics (more than once), Apple stated the hardware was fine (other than Airport Card -- finally). However, if I've done 5-6 total wipes; created new users; do not have sharing set-up; have not played around in Terminal; and am up-to-date with versions -- and various issues KEEP COMING BACK -- I am left wondering if a keystroke logger would be possible here?!? I thought maybe a faulty logic board, but why would diagnostics be okay, then? Not trying to be hyperbole, just desperate.
    Please help me rule keystroke logger out or at least, tell me so I know, so I can take appropriate action. If you think it could be the logic board with symptoms above, that would be a great too.
    All I want to do is use the computer as intended, but I can't seem to get a real answer, so after nine months -- I am turning to the communities to see if anyone -- anyone at all -- can help. The last thing I can do is have the MBPR come back from the depot and the same thing occur. Any guidance or advice would be so gratefully appreciated.

  • How can I use a FocusEvent to distinguish among editable JComboBoxes?

    Hi,
    I have a Frame with multiple editable JComboBoxes, but I am at a loss as to how to sort them out in the focusGained() method.
    It is easy when they are not editable, because the FocusEvent getSource() Method returns the box that fired the event. That lets me read an instance variable that is set differently for each box.
    But with editable boxes, the FocusEvent is not fired by the box. It is fired by a Component object returned by getEditor().getEditorComponent(). So far I cannot find a way to query that object to find the box it it tied to. (I hope this isn't going to be painfully embarassing.).
    Anyway, the code below produces a frame with four vertical components: a JTextField (textField), a NON-Editable JComboBox (comboBox1) and two Editable JComboBoxes (comboBox2 & comboBox3).
    This is the command screen produced by :
    - Running the class
    - Then tabbing through all the components to return to the text field.
    I am not sure why, but it gives the last component added the foucus on startup.Focus Gained - Begin: *****
       This is the comboBox that Is Not Editable
    Focus Gained - End: *******
    Focus Gained - Begin: *****
       This Is The TextField
    Focus Gained - End: *******
    Focus Gained - Begin: *****
       Class: class javax.swing.plaf.metal.MetalComboBoxEditor$1
       Name: javax.swing.plaf.metal.MetalComboBoxEditor$1
    Focus Gained - End: *******
    Focus Gained - Begin: *****
       Class: class javax.swing.plaf.metal.MetalComboBoxEditor$1
       Name: javax.swing.plaf.metal.MetalComboBoxEditor$1
    Focus Gained - End: *******
    Focus Gained - Begin: *****
       This is the comboBox that Is Not Editable
    Focus Gained - End: *******
    Focus Gained - Begin: *****
       This Is The TextField
    Focus Gained - End: *******As you can see, the FocusEvent source for both editable boxes is a MetalComboBoxEditor. Both have identical names.
    Can anyone help me get from there back to the actual combo box so I can read the instance variable to see which one fired the event?
    The (painfully tedious and inelegant ) code that produced the above output is:import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TestListeners extends JFrame
      implements ActionListener, DocumentListener,
                             FocusListener,  ItemListener {
      // Constructor
       TestListeners () {
          super ();
          panel.setLayout (new GridLayout (4, 1));
          textField.addActionListener (this);
          textField.getDocument ().addDocumentListener (this);
          textField.addFocusListener (this);
          panel.add(textField);
          comboBox2.addActionListener (this);
          comboBox2.getEditor().getEditorComponent ().addFocusListener (this);
          comboBox2.addItemListener (this);
          comboBox2.setEditable (true);
          panel.add (comboBox2);
          comboBox3.addActionListener (this);
          comboBox3.getEditor().getEditorComponent ().addFocusListener (this);
          comboBox3.addItemListener (this);
          comboBox3.setEditable (true);
          panel.add (comboBox3);
          comboBox1.addActionListener (this);
          comboBox1.addFocusListener (this);
          comboBox1.addItemListener (this);
          comboBox1.setEditable (false);
          panel.add (comboBox1);
          this.getContentPane ().add(panel);
          this.setVisible (true);
          pack ();
       // Nested class
        public class CB extends JComboBox {
           // Nested Constructor
          public CB  (Vector items, String str) {
             super (items);
             this.type = str;
          public String type;
       // Instance Members
       JTextField     textField = new JTextField ("Test Listener TextField");
       JPanel panel  = new JPanel ();
       String[] str = {"one", "two", "three"};
       Vector items = new Vector (Arrays.asList (str));
       CB comboBox1 = new CB (items, "Is Not Editable");
       CB comboBox2 = new CB (items, "Is Editable 2");
       CB comboBox3 = new CB (items, "Is Editable 3");
       // Methods
       public static void main(String args[]) {
          TestListeners frame = new TestListeners ();
       public void actionPerformed (ActionEvent ae) {
          System.out.print ("ActionEvent: This is ");
           if (ae.getSource ().getClass () == CB.class) {
             System.out.print ( ((CB) ae.getSource ()).type + " ");
          System.out.println (" "+ae.getActionCommand() + "\n" );
       public void focusGained (FocusEvent fge) {
          System.out.println ("Focus Gained - Begin: ***** ");
          if (fge.getSource ().getClass () == CB.class) {
          System.out.println ( "   This is the comboBox that "+((CB) fge.getSource ()).type);
          } else if (fge.getSource ().getClass () == JTextField.class) {
             System.out.println ( "   This Is The TextField");
         } else {
             System.out.println ("   Class: "+fge.getSource ().getClass());
             System.out.println ("   Name: "+fge.getSource ().getClass ().getName ());
         System.out.println ("Focus Gained - End: *******\n*\n");
       public void focusLost (FocusEvent fle) { }
       public void changedUpdate (DocumentEvent de) { }
       public void insertUpdate (DocumentEvent de) { }
       public void removeUpdate (DocumentEvent de) { }
       public void itemStateChanged (ItemEvent ie) { }
    }

    I added the following in your focusGained() method and it seemed to work:
    Component c = ((Component)fge.getSource ()).getParent();
    if (c instanceof JComboBox)
         JComboBox cb = (JComboBox)c;
         System.out.println("Selected: " + cb.getSelectedItem());
    }

  • 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

  • JComboBox with checkboxes - how to ?

    How can I implement a JComboBox with JChecBoxes as elements ?

    my first guess:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import javax.swing.JCheckBox;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    public class CheckListCellRenderer extends JCheckBox implements
            ListCellRenderer {
        public CheckListCellRenderer() {
            setLayout(new BorderLayout());
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            return (Component) value;
    }The problem is the checkboxes are not editable....

  • Editable JComboBox -Saving itz new value in the database.

    Hi,
    I have a Combobox say Product , in which some fields (like -> tv , hand blender etc) comes from Database and i have added one more field say others ,
    in others field user can enter new product name and it shd be saved in the same database, i have used editable jcombobox but dnt no how to proceed further.
    Thanks & Regards
    Komal

    And make a provision to delete wrong entries, or you'll end up with all the typos stored separately.
    I speak from experience. I actually have such a combo in several of my VFP applications (not in Java though)
    db

  • Can JOptionPane produce an editable JComboBox?

    Can I use JOptionPane for an input dialog component with a data input area represented by an editable JComboBox ?
    For example :
    JOptionPane.showInputDialog( parent,
    � How Much?�,
    �This is the title�,
    JOptionPane.QUESTION_MESSAGE,
    null,
    new Object[]
    { � �, �un peu�,�beaucoup�,�passionnement�},
    �passionnement�);
    This one statement produces the input dialog I want, except that it does not allow an input such as �pas du tout� which is not in the list of selections.
    Does any one knows if somehow I could get to this JComboxBox and make it editable? (still using JOptionPane of course)?
    Thank you to any one who can answer me.

    Hi,
    You could use the JOptionPane.showMessageDialog() in the following way:
    JComboBox comboBox = //Make your own JComboBox here
    Object[] message = new Object[] {
    "Make your choice:",
    comboBox
    JOptionPane.showMessageDialog(parent, message);
    In this way you are able to add every Component to your message dialog you want to.
    Hope that helps, Mathias

  • JComboBox with Horizontal ScrollBar

    Hi all,
    I created this custom ComboBox:
    import com.sun.java.swing.*;
    import com.sun.java.swing.plaf.basic.*;
    public class myCombo extends JComboBox{
        public myCombo(){
            super();
            setUI(new myComboUI());
        public class myComboUI extends BasicComboBoxUI{
            protected ComboPopup createPopup(){
                BasicComboPopup popup = new BasicComboPopup(comboBox){
                    protected JScrollPane createScroller() {
                            return new JScrollPane( list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
                return popup;
      {code}
    When i add this ComboBox to a Frame, it has a look and feel diffrent from the others component !
    How to resolve that ?
    Regards
    Jack                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    [removed]
    Just another cross poster.
    [http://www.coderanch.com/t/432788/Swing-AWT-SWT-JFace/java/JComboBox-with-horizontall-scroll-bar]
    Edited by: Darryl.Burke

  • Update the testfield when setSelectedItem() for editable JComboBox

    Hi,
    I am having problem with setSelectedItem() and setSelectedIndex() methods of editable JComboBox.
    I extended JComboBox with default dataModel. When I enter some string in the textfield of the combobox, I call insertItemAt() method to dynamically grow the list. The application requires to clear the textfield everytime I enter something and press "return" key. To make it work, I insert an empty string to the list at the very beginning and call the setSelectedItem("") method in the actionPerformed().
    Now the problem is that I know the setSelectedItem("") is called since the getActionCommand() returns "comboBoxChanged" everytime I enter something in the textfield, but the testfield is not cleared. And if I select one item from the list and press "enter" key, the textfield is cleared. To make things more interesting, after I enter the first string and press "enter", the textfield really get cleared, but not for all other later input. Is this a bug? Can anyone please help me? Thanks a lot. Below is my code snippet.
    public class MyComboBox extends JComboBox implements ActionListener
    public GsISCommComboBox()
    jbInit();
    private void jbInit() throws Exception
    this.setEditable(true);
    this.addActionListener(this);
    insertItemAt("",0);
    public void actionPerformed(ActionEvent e)
    String str=null;
    String strrr=e.getActionCommand();
    System.out.println("getActionCommand: "+strrr);
    if(strrr.equalsIgnoreCase("comboBoxChanged"))
    str=(String)this.getSelectedItem();
    return;
    else
    str=strrr;
    // other stuff to process the string and do things
    setSelectedItem("");
    repaint();
    hidePopup();
    insertItemAt(str,0);

    Try inserting your string first and then, try clearing the combobox's textfield.
    insertItemAt(str,0);
    setSelectedItem("");
    hidePopup();
    repaint();
    Since you add the "" string at the begining, it will have the index 0. Perhaps, you want to insert your string this way:
    // insert string at the end
    insertItemAt(str, this.getItemCount());
    //Then use the
    setSelectedIndex(0);
    But you need to remember that if you add an item at the begining, index 0 may not be your '' '' string after that.
    I hope that it helps.

  • Editable JComboBox [URGENT]

    Hi All,
    I have an editable JComboBox.It is having some values in the model.By using getSelectedItem() ,i can get the value that was selected.But suppose if the user types a new value which is not there in its model, how to get that value.If i use getSelectedItem(), i am getting a null pointer exception.Can somebody help me?
    Thanks in advance
    Ashok

    Thanx for ur advise.I am getting the value with the method you said and with getSelectedItem() also but it is still throwing NullPointerException.The stack is as follows.
    java.lang.NullPointerException
    at javax.swing.JComboBox.getSelectedIndex(JComboBox.java:479)
    at javax.swing.plaf.basic.BasicComboPopup.syncListSelectionWithComboBoxSelection(BasicComboPopup.java:810)
    at javax.swing.plaf.basic.BasicComboPopup$ItemHandler.itemStateChanged(BasicComboPopup.java:613)
    at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:846)
    at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:891)
    at javax.swing.JComboBox.contentsChanged(JComboBox.java:946)
    at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:79)
    at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:86)
    at javax.swing.JComboBox.actionPerformed(JComboBox.java:925)
    at javax.swing.plaf.basic.BasicComboBoxUI$EditorFocusListener.focusLost(BasicComboBoxUI.java:1402)
    at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:171)
    at java.awt.Component.processFocusEvent(Component.java:3644)
    at javax.swing.JComponent.processFocusEvent(JComponent.java:2058)
    at java.awt.Component.processEvent(Component.java:3537)
    at java.awt.Container.processEvent(Container.java:1164)
    at java.awt.Component.dispatchEventImpl(Component.java:2595)
    at java.awt.Container.dispatchEventImpl(Container.java:1213)
    at java.awt.Component.dispatchEvent(Component.java:2499)
    at java.awt.LightweightDispatcher.setFocusRequest(Container.java:2076)
    at java.awt.Container.proxyRequestFocus(Container.java:1335)
    at java.awt.Container.proxyRequestFocus(Container.java:1330)
    at java.awt.Container.proxyRequestFocus(Container.java:1330)
    at java.awt.Container.proxyRequestFocus(Container.java:1330)
    at java.awt.Component.requestFocus(Component.java:4192)
    at javax.swing.JComponent.grabFocus(JComponent.java:967)
    Any idea why so?

Maybe you are looking for