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?

Similar Messages

  • Problem in JTable with a JComboBox cell editor

    Hi gurus,
    Please help! I am having a problem with a JTable that has a JComboBox cell editor. When the table is first loaded, the combo box column displays correct data. But whenever I click the combo box, the selection will be set to the first item in the combo box list once the popup menu pops up even before I make any new selection. It is very annoying.
    Here is how I set the cell editor:
    populateComboBoxModel(); // populate the combo box model.
    DefaultCellEditor cell_editor = new DefaultCellEditor(new JComboBox(
    combo_model));
    contrib_table.getColumnModel().getColumn(1).setCellEditor(
    cell_editor);
    I didn't set the cell renderer so I assume it is using the default cell renderer.
    Thanks !

    Not quite. The example doesn't have a different cell editor for each row of the table. I'm sure I must be missing something, bc I've found many references to the fact that this is possible to do. And I have most of it working. However, when I click on any given combobox, it automatically switches to the first value in the list, not the selected item. I've tried setting the selected item all over the code, but it has no effect on this behavior. Also, it only happens the first time I select a given cell. For example, suppose the first row has items A, B, and C, with B being the selected value. The table initially displays with B in this cell, but when I click on B, it switches to A when it brings up the list. If I select B, and move on to some other cell, and then go back and click on B again, it doesn't switch to A.
    There seems to be a disconnect between the values that I display initially, and the values that I set as selected in the comboboxes. Either that, or it behaves as though I never set the selected item for the combobox at all.
    Any help would be greatly appreciated.

  • KeyListener is not working with editable JComboBox??!!!

    When I make the JComboBox editable property to true, the keylistener of the jcombobox is not working why?
    How can I solve this problem?
    Please help
    Haroon

    When editable, focus is placed on the editor component of the combo box. So you need to add the KeyListener to the editior component.
    comboBox.getEditor().getEditerComponent().addKeyListener(...);

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • 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

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

  • Stopping cell editing in a JTable using a JComboBox editor w/ AutoComplete

    Hi there! Me again with more questions!
    I'm trying to figure out the finer parts of JTable navigation and editing controls. It's getting a bit confusing. The main problem I'm trying to solve is how to make a JTable using a combo box editor stop editing by hitting the 'enter' key in the same fashion as a JTextField editor. This is no regular DefaultCellEditor though -- it's one that uses the SwingX AutoCompleteDecorator. I have an SSCCE that demonstrates the issue:
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableModel;
    import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
    public class AutoCompleteCellEditorTest extends JFrame {
      public AutoCompleteCellEditorTest() {
        JTable table = new JTable();
        Object[] items = {"A", "B", "C", "D"};
        TableModel tableModel = new DefaultTableModel(2, 2);
        table.setModel(tableModel);
        table.getColumnModel().getColumn(0).setCellEditor(new ComboCellEditor(items));
        getContentPane().add(table);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
      private class ComboCellEditor extends AbstractCellEditor implements TableCellEditor {
        private JComboBox comboBox;
        public ComboCellEditor(Object[] items) {
          this.comboBox = new JComboBox(items);
          AutoCompleteDecorator.decorate(this.comboBox);
        public Object getCellEditorValue() {
          return this.comboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
          comboBox.setSelectedItem(value);
          return comboBox;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new AutoCompleteCellEditorTest().setVisible(true);
    }Problem 1: Starting to 'type' into the AutoCompleteDecorate combo box doesn't cause it to start editing. You have to hit F2, it would appear. I've also noticed this behaviour with other JComboBox editors. Ideally that would be fixed too. Not sure how to do this one.
    Problem 2: After editing has started (say, with the F2 key), you may start typing. If you type one of A, B, C, or D, the item appears. That's all good. Then you try to 'complete' the edit by hitting the 'enter' key... and nothing happens. The 'tab' key works, but it puts you to the next cell. I would like to make the 'enter' key stop editing, and stay in the current cell.
    I found some stuff online suggesting you take the input map of the table and set the Enter key so that it does the same thing as tab. Even though that's not exactly what I desired (I wanted the same cell to be active), it didn't work anyway.
    I also tried setting a property on the JComboBox that says that it's a table cell editor combo box (just like the DefaultCellEditor), but that didn't work either. I think the reason that fails is because the AutoCompleteDecorator sets isEditable to true, and that seems to stop the enter key from doing anything.
    After tracing endless paths through processKeyBindings calls, I'm not sure I'm any closer to a solution. I feel like this should be a fairly straightforward thing but I'm having a fair amount of difficulty with it.
    Thanks for any direction you can provide!

    Hi Jeanette,
    Thanks for your advice. I looked again at the DefaultCellEditor. You are correct that I am not firing messages for fireEditingStopped() and fireEditingCancelled(). Initially I had copied the behaviour from DefaultCellEditor but had trimmed it out. I assumed that since I was extending AbstractCellEditor and it has them implemented correctly that I was OK. But I guess that's not the case! The problem I'm having with implementing the Enter key stopping the editing is that:
    1) The DefaultCellEditor stops cell editing on any actionPerformed. Based on my tests, actionPerformed gets called whenever a single key gets pressed. I don't want to end the editing on the AutoCompleteDecorated box immediately -- I'd like to wait until the user is happy with his or her selection and has hit 'Enter' before ending cell editing. Thus, ending cell editing within the actionPerformed listener on the JComboBox (or JXComboBox, as I've made it now) will not work. As soon as you type a single key, if it is valid, the editing ends immediately.
    2) I tried to add a key listener to the combo box to pick up on the 'Enter' key and end the editing there. However, it appears that the combo box does not receive the key strokes. I guess they're going to the AutoCompleteDecorator and being consumed there so the combo box does not receive them. If I could pick up on the 'Enter' key there, then that would work too.
    I did more reading about input maps and action maps last night. Although informative, I'm not sure how far it got me with this problem because if the text field in the AutoCompleteDecorator takes the keystroke, I'm not sure how I'm going to find out about it in the combo box.
    By the way, when you said 'They are fixed... in a recent version of SwingX', does that mean 1.6.2? That's what I'm using.
    Thanks!
    P.S. - Maybe I should create a new question for this? I wanted to mark your answer as helpful but I already closed the thread by marking the answer to the first part as correct. Sorry!
    Edited by: aardvarkk on Jan 27, 2011 7:41 AM - Added SwingX versioning question.

  • Setting color of an item in a Jcombobox in a JTable when editing

    Hello,
    I have a situation where I have a JCombobox in a JTable . The JCombobox is non-editable. The items within the combobox are colored in pink or blue in order to help the user differentiate between the two categories that are in the list.
    But the problem is that when the user is on that cell and is just typing the first letter(s) in the combobox, he does see the item starting with that letter(s) but that item is not shown as colored. However, if the user clicks on the combobox with a mouse, the list pops-up and the items are shown as colored. I want the first part to work where the user can just use keyboard and see the items as colored in that cell itself. By default, currently when the row is selected the foreground is white and background is black. I want that particularly when this combobox has focus and an item is selected, the foreground should be of the same color as the color of the item.
    Can someone help?
    Thanks a lot in advance.

    Additional information on above:
    I associate a customized renderer with the column of my table for which i want to set the colors.
    TableColumn tc6 = jTableDRS.getColumnModel().getColumn(myDRSModel.FINANCECODE_COLUMN);
    tc6.setCellRenderer(new ColorRenderer());
    here is the renderer that I am using...
    public class ColorRenderer extends JLabel implements TableCellRenderer {
    protected Border noFocusBorder;
    public ColorRenderer() {
    noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    Color foreground = null;
    Color background = null;
    Font font = null;
    if(column == myDRSModel.FINANCECODE_COLUMN)
    setFont((font != null) ? font : table.getFont());
    String str = (String)value.toString();
    if (!str.equalsIgnoreCase("SELECT ONE")) {
    int y = financedesc.indexOf(str);
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    if(isSelected)
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    setBackground(table.getSelectionBackground());
    else{
    setBackground(table.getBackground());
    else
    if(isSelected)
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    setValue(value);
    return this;
    protected void setValue(Object value) {
    setText((value == null) ? "" : value.toString());
    }

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

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

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

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

  • JTable with custom combobox

    Hi
    I been trying to create a JTable with a custom combobox, that is in a column the lists contained within each combobox is unique. I tried using a renderer, even though the combo appears I cannot select the combo for editing. Any suggestions on how to get the combo working properly would be appreciated thanks.

    It's been a few years since I did something like this, but my recollection is that you should implement the TableCellEditor interface and have the getTableCellEditor method return your custom combo box. Then, either override getCellEditor in your JTable to return your custom TableCellEditor or (better) call tableColumn.setCellEditor for the column you're interested in, passing an instance of your TableCellEditor. I suggest you return the same JComboBox from your implementation of getTableCellEditor every time, and either replace the underlying model or have a custom model in which you can easily switch the contents on-the-fly.
    Having done this in the past, I remember that it's quite easy to leak stuff - I wouldn't advise making a new JComboBox every time.
    Regards,
    Huw

  • 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());
    }

Maybe you are looking for

  • Is there something wrong with my battery?

    Hi everyone! I have an Iphone 5 that was newly "remodeled" for tmobile. I was wondering if there was something wrong with my battery after a recent decline in performance. I am updated to the latest iOS and I recently restored all of my settings on m

  • How do I add buttons/links in video

    Hello, I am new to editing video. I am looking to add a replay link and a go to url link once my movie plays through. I am using Flash CS3 pro. If someone could give me specific directions or direct me to a tutorial instructing me how to do this I wo

  • Why is my iPad asking for a passcode at startup?

    Just updated iPad to ios 7 and its now asking for a passcode. It didn't have one before and I'm now locked out. Is there a default passcode? How the **** do I get back into it?

  • To calculate age in terms of Months

    Hi All, How do I calculate the age of the person in terms of "Months"? Regards, sps

  • FCE can't launch AGP Graphics Card?

    I've been using FCE 4.x for years. The other day, I installed Soundtrack and all of a sudden my Final cut won't open or launch. I'm getting a "Configuration Error" "This software requires certain hardware or software which is missing." "AGP graphics