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,

Similar Messages

  • 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

  • Using KeyMap in Editable JComboBoxes and JTable

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

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

  • Editable JComboBox inside JTable clipping issues

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

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

  • Editable JComboBox in JTable focus issue

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

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

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

  • Editable JCombobox cell editor length limit

    Hi All,
    I have an editable JCombobox as a celleditor to one of the column in JTable, How do I limit the characters in the cell editor?
    Thanks

    A JComboBox uses a JTextField as it's cell editor. You should read up on how you would do this for a normal JTextField by using a custom Document:
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html
    Here's an example using JComboBox. I haven't tried it in a JTable but I assume it should work.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxNumericEditor extends BasicComboBoxEditor
         public ComboBoxNumericEditor(JComboBox box)
              editor.setDocument( new NumericListDocument(box.getModel()) );
         public static void main(String[] args)
              String[] items = { "one", "two", "three", "four" };
              JComboBox list = new JComboBox( items );
              list.setEditable( true );
              list.setEditor( new ComboBoxNumericEditor( list ) );
              JFrame frame = new JFrame();
              frame.getContentPane().add( list );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class NumericListDocument extends PlainDocument
              ListModel model;
              public NumericListDocument(ListModel model)
                   this.model = model;
              public void insertString(int offset, String text, AttributeSet a)
                   throws BadLocationException
                   //  Accept all entries in the ListModel
                   for (int i = 0; i < model.getSize(); i++)
                        Object item = model.getElementAt(i);
                        if (text.equals( item.toString() ))
                             super.insertString(offset, text, a);
                             return;
                   //  Build the new text string assuming the insert is successfull
                   String oldText = getText(0, getLength());
                   String newText =
                        oldText.substring(0, offset) + text + oldText.substring(offset);
                   //  Edit the length of the new string
                   if (newText.length() > 2)
                        Toolkit.getDefaultToolkit().beep();
                        return;
                   //  Only numeric characters are allowed in the new string
                   //  (appending the "0" will allow an empty string to be valid)
                   try
                        Integer.parseInt(newText + "0");
                        super.insertString(offset, text, a);
                   catch (NumberFormatException e)
                        Toolkit.getDefaultToolkit().beep();
    }

  • Multiple keystrokes selection for a JComboBox in JTable

    Has anyone used multiple keystrokes selection in a JComboBox inside JTable before? I can get it done outside JTable by using: http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html
    Looks like JTable has all kinds of problems to support JComboBox.
    Suggestions?
    Thanks,
    James

    If I read you right, you want to use a multiple keystroke combo box as an editor in a JTable?
    If you create the JComboBox as you would like it and then install it as an editor in the column(s) JTable the editor will work like the JComboBox
    Example:
    //- you would have that keyselection Manager class
    // This key selection manager will handle selections based on multiple keys.
    class MyKeySelectionManager implements JComboBox.KeySelectionManager {    ....    };
    //- Create the JComboBox with the multiple keystroke ability
    //- Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cboBox = new JComboBox(items);
    // Install the custom key selection manager
    cboBox.setKeySelectionManager(new MyKeySelectionManager());
    //- combo box editor for the JTable
    DefaultCellEditor cboBoxCellEditor = new DefaultCellEditor(cboBox);
    //- set the editor to the specified COlumn in the JTable - for example the first column (0)
    tcm.getColumn(0).setCellEditor(cboBoxCellEditor); Finally, it may be necessary to to put a KeyPressed listener for the Tab key, and if you enter the column that has the JComboBox:
    1) start the editting
    table.editCellAt(row, col);2) get the editor component and cast it into a JComboBox (in this case)
    Component comp = table.getEditorComponent();
    JComboBox cboComp = (JComboBox) comp;3) give this compent the foucus to do its deed     
    cboComp.requestFocus();Hope this helps!
    dd

  • How to put JComboBox in JTable?

    I'm trying to put JComboBox in JTable, the following is my table model. The problem is that it doesn't display a JComboBox but a string of it, something like "MyTableModel$JComboBox....". Any help would be appreciated.
    class MyModel extends AbstractTableModel {
    String[] columnNames = {"Column One", "Column One"};
    String[] boxItem = {"Item One", "Item Two"};
    String[] rows = {"Row One", "Row Two"};
    JComboBox[] boxes = {
    new JComboBox(boxItem),
    new JComboBox(boxItem)
    Object[][] data = new Object[][]{rows, boxes};
    public Object getValueAt(int row, int col) {
    return data[col][row];
    }

    Hi,
    the TableModel is the wrong place to put the combo box. A model is just a representation for the data displayed in the table.
    A combo box, on the other hand, is a certain way for the user to edit the values in the table (and in the model). To change the way a user edits in a table you have to set the TableCellEditor. You can do this for the whole table or for a certain column.
    // in the JTable's constructor or init method
    // to set JComboBox in 2nd column
    // get 2nd column
    TableColumn column = myTable.getColumnModel().getColumn(1);
    // create combo box
    JComboBox combo = new JComboBox();
    combo.add("ItemOne");
    combo.add("ItemTwo");
    // set as editor for the column
    DefaultCellEditor editor = new DefaultCellEditor(combo);
    column.setCellEditor(editor);This is just an example. Try it w/ a simple table.

  • Using Editor JComboBox is JTable CellEditors

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

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

  • Not Updating the Values in the JComboBox and JTable

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

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

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

  • 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

  • Blank values for editable JComboBox

    Hello,
    I have a editable JComboBox that the user can erase its current value and if they simple change focus (like click on a text field on the same panel) the combo box is left blank. i would like to have it so that if the user leaves focus of the box and its blank that current value goes back to what it was before they erased it.
    Many thanks,
    Jonathan

    import java.awt.FlowLayout;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    public class NonBlankCombo {
       JComboBox comboBox;
       Object previousContent;
       void makeUI() {
          Object[] data = {"One", "Two", "Three", "Four", "Five"};
          previousContent = data[0];
          comboBox = new JComboBox(data);
          comboBox.setEditable(true);
          comboBox.addItemListener(new ItemListener() {
             public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED
                      && !((String) comboBox.getSelectedItem()).trim().isEmpty()) {
                   previousContent = comboBox.getSelectedItem();
          comboBox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {
             public void focusGained(FocusEvent e) {
                previousContent = comboBox.getSelectedItem();
             public void focusLost(FocusEvent e) {
                if (((String)comboBox.getSelectedItem()).trim().isEmpty()) {
                   comboBox.setSelectedItem(previousContent);
          JFrame frame = new JFrame("Non-blank Combo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(200, 100);
          frame.setLayout(new FlowLayout());
          frame.add(comboBox);
          frame.add(new JButton("Click"));
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new NonBlankCombo().makeUI();
    }db

Maybe you are looking for

  • [solved] dhcpcd: timed out after reinstalling arch

    Hi erveryone! After reinstalling arch I can't connect to my wireless network anymore. Typed: wpa_supplicant -B -Dwext -i wlan0 -c /etc/wpa_supplicant_vienna.conf dhcpcd wlan0 Got: dhcpcd: wlan0: waiting for carrier dhcpcd: timed out wpa_supplicant_vi

  • Indent /tab position for text from INCLUDE texts in SAPscript

    Hi, ABAP colleagues! Need your help on this sapscript problem:  How to align texts taken from "INCLUDE TEXT" in SAPscript, according to tab defined in Paragraph Format? Or, how to control tab positions for texts which were extracted from “INCLUDE tex

  • Now can't send texts as usual after receiving 1st iMessage

    someone just sent me an iMessage (my first). Now I can't send a normal text. When I try to type in a message as usual, my keystrokes don't make anything happen now. What can I do?

  • How to extend material master?

    to extend storage location we can use T-code MMSC. similarly to extend material master any T-code or any other  procedure is there? please help me

  • Finder - establishing connection to server takes forever

    Hello, I already found an archived discussion (https://discussions.apple.com/message/10356039#10356039) which explains my server issue. Anyway I will write some further thoughts down here and I don't use VPN. Our company with about 40 (Lions, Mountai