Adding JComboBox in JTable?

Hi,
How can i add a JComboBox inside the cell of a JTable. sothat i can select options from the cell of JTable.?
or any other idea for that?
Thank you ;
Ganesh.

Swing related questions should be posted in the Swing forum.
"Using a Combo Box as an Editor"
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox

Similar Messages

  • Problem in adding JComboBox in JTable

    Hi,
    I was trying to put some comboxes in a jtable. The problem is I am not able to add combo boxes in the 1st and 2nd column. But its adding from the 3rd column. What can be wrong in the following code?
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.*;
    * TableRenderDemo is just like TableDemo, except that it
    * explicitly initializes column sizes and it uses a combo box
    * as an editor for the Sport column.
    public class TableRenderDemo1 extends JPanel {
        private boolean DEBUG = true;
            DefaultTableCellRenderer renderer =  new DefaultTableCellRenderer();
        public TableRenderDemo1() {
            //super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 250));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Set up column sizes.
            initColumnSizes(table);
            //Fiddle with the Sport column's cell editors/renderers.
            setUpNameColumn(table, table.getColumnModel().getColumn(3));
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table, table.getColumnModel().getColumn(4));
            //Add the scroll pane to this panel.
            add(scrollPane);
            String strPlaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            try {
                    UIManager.setLookAndFeel(strPlaf);
                    SwingUtilities.updateComponentTreeUI(scrollPane);
            } catch(Exception e) {
                    e.printStackTrace();
         * This method picks good column sizes.
         * If all column heads are wider than the column's cells'
         * contents, then you can just use column.sizeWidthToFit().
        private void initColumnSizes(JTable table) {
            MyTableModel model = (MyTableModel)table.getModel();
            TableColumn column = null;
            Component comp = null;
            int headerWidth = 0;
            int cellWidth = 0;
            Object[] longValues = model.longValues;
            TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
            for (int i = 0; i < 5; i++) {
                column = table.getColumnModel().getColumn(i);
                comp = headerRenderer.getTableCellRendererComponent(
                                     null, column.getHeaderValue(),
                                     false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
                comp = table.getDefaultRenderer(model.getColumnClass(i)).
                                 getTableCellRendererComponent(
                                     table, longValues,
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    comboBox.setVisible(true);
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    public void setUpNameColumn(JTable table, TableColumn nameColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("One");
    comboBox.addItem("Two");
    comboBox.addItem("Three");
    comboBox.addItem("Four");
    comboBox.addItem("Five");
    comboBox.setVisible(true);
    nameColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    nameColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Saikat", "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Srinath", "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Sheela", "Knitting", new Integer(2), new Boolean(false)},
    {"John", "Yashwant", "Something", new Integer(5), new Boolean(true)},
    {"Harry", "Jay", "Playing", new Integer(1), new Boolean(true)},
    public final Object[] longValues = {"Sharon", "Campione",
    "None of the above",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo1 newContentPane = new TableRenderDemo1();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Thanks in advance.

    First, I don't see where you are tying to set the combo box on the first two columns. I only see it for the 3 and 4.
    Also why are you putting combo boxes in columns that are not editable:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
            }

  • Placing JComboBox in JTable ColumnHeader

    Can any one help me on how to place a JComboBox in JTable ColumnHeader....?

    try this:
    package ComponentDisplayer;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class JComponentCellRenderer implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
            return (JComponent)value;
    }and
    package ComponentDisplayer;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Pable
         public static void main(String[] args)
              JFrame frame = new JFrame("Table");
              frame.addWindowListener( new WindowAdapter() {
                   public void windowClosing(WindowEvent e)
                        Window win = e.getWindow();
                        win.setVisible(false);
                        win.dispose();
                        System.exit(0);
              JTable table = new JTable(3,2);
                 TableCellRenderer renderer = new JComponentCellRenderer();
                  TableColumnModel columnModel = table.getColumnModel();
                  TableColumn column0 = columnModel.getColumn(0);
                  TableColumn column1 = columnModel.getColumn(1);
                  column0.setHeaderRenderer(renderer);
                  JComboBox jb=new JComboBox();
                  jb.insertItemAt("well", 0);
                  jb.insertItemAt("done", 1);
                  column0.setHeaderValue(jb);
                  column1.setHeaderRenderer(renderer);
                  column1.setHeaderValue(new JComboBox());
              table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
              table.setSize(900, 1200);
              JScrollPane sp = new JScrollPane(table);
              table.setColumnSelectionAllowed(false);
             table.setRowSelectionAllowed(true);
              frame.getContentPane().add( sp );
              frame.pack();
              frame.setVisible(true);
              //frame.show();
    }as you can see adding it is not that hard but you cannot interact with them because if my memory serves well, tableheaders cannot have focus by default. So you gotta write your own implementation of header (may be using sth like: )public class MyTableHeaderRenderer extends JComponent implements
              TableCellRenderer {
         public MyTableHeaderRenderer() {
              // TODO Auto-generated constructor stub
         public Component getTableCellRendererComponent(JTable arg0, Object arg1,
                   boolean arg2, boolean arg3, int arg4, int arg5) {
              // TODO Auto-generated method stub
              return (JComponent)arg1;
         }and then use this as default renderer in your implementation.)
    E,ther you have to handle setfocus thing or keep track of mouse events
    I hope this helps

  • 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

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

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

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

  • Jcombobox inside jtable

    I have a jcombobox inside jtable.now i want to access its items by keys only..without using F2 key.for example if i press 's' key..the whole combobox shud popup and value 'string' is selected.please help me regarding this.

    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.

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • Adding JCheckBox into JTable

    Hi all,
    I added a JCheckBox into a JTable, while clicking the check box the selection will not replicate into the JTable. Please help me to resolve this issue.
    * TableDemo.java
    * Created on September 5, 2006, 11:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package simPackage;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    * @author aathirai
    public class TableDemo extends JPanel{
       // public JRadioButton[] dataButton;
        /** Creates a new instance of TableDemo */
        public TableDemo() {
            JCheckBox firstCheck = new JCheckBox("");
            Object[][] data={{firstCheck,"2","4","5","2"}};
                    String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
                    JTable searchResultTable = new JTable(data,columnNames);
                    searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
                    searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
            JScrollPane scrollPane = new JScrollPane(searchResultTable);
            //Add the scroll pane to this panel.
            add(scrollPane);
    public static void main(String args[])   {
         JFrame jFrame  = new JFrame("testing");
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableDemo newContentPane = new TableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            jFrame.setContentPane(newContentPane);
            //Display the window.
            jFrame.pack();
            jFrame.setVisible(true);
    class RadioButtonRenderer implements TableCellRenderer {
        public JCheckBox check1 = new JCheckBox("");
      public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int row, int column) {
          check1.setBackground(Color.WHITE);
         return check1;
    class RadioButtonEditor extends DefaultCellEditor{
        public JCheckBox check1 = new JCheckBox("");
      boolean state;
      int r, c;
      JTable t;
      class RbListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          if (e.getSource() == check1){
            state = true;
          else{
            state = false;
          RadioButtonEditor.this.fireEditingStopped();
      public RadioButtonEditor(JCheckBox checkBox) {
        super(checkBox);
      public Component getTableCellEditorComponent(JTable table, Object value,
       boolean isSelected, int row, int column) {
        RbListener rb = new RbListener();
        t = table;
        r = row;
        c = column;
        if (value == null){
          return null;
        check1.addActionListener(rb);
         //check1.setSelected(((Boolean)value).booleanValue());
        /*if (((Boolean)value).booleanValue() == true){
          check1.setSelected(true);
        return check1;
      public Object getCellEditorValue() {
        if (check1.isSelected() == true){
          return Boolean.valueOf(true);
        else{
          return Boolean.valueOf(false);
    }Thanks in advance.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class TableDemo extends JPanel
      public TableDemo()
        //JCheckBox firstCheck = new JCheckBox("");
        //Object[][] data={{firstCheck,"2","4","5","2"}};
        Object[][] data={{new Boolean(false),"2","4","5","2"}};
        String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
        JTable searchResultTable = new JTable(data,columnNames);
        //searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
        //searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
        TableColumn tc = searchResultTable.getColumnModel().getColumn(0);
        tc.setCellEditor(searchResultTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(searchResultTable.getDefaultRenderer(Boolean.class));
        JScrollPane scrollPane = new JScrollPane(searchResultTable);
        add(scrollPane);
      public static void main(String args[])
        JFrame jFrame  = new JFrame("testing");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        jFrame.setContentPane(newContentPane);
        jFrame.pack();
        jFrame.setVisible(true);
    }

  • How can I surrend the focus of Jcombobox in Jtable?

    There are a jcombobox for each row of a jtable. I can click each cell to choose some value from the item list of jcombobox.
    The problem is, when I import data into the table by changing the values of tablemodel, if some cell still hold the focus, the table won't show the new imported data for this specific cell, but keep the old one. Others cells without focus work well.
    For example, originally I choose a "Monday" from the combobox with focus. When I import new data (by clicking some button), for instance "Tuesday", the new data doesn't show in the focused cell.
    So, how can I surrend the focus of this specific cell to other components, for instance, some button?

    In your action for your button, before you update your table with the imported information do the following:
    if (myTable.isEditing())
        myTable.getCellEditor().stopCellEditing();
    }

  • 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

  • Problem adding JTextFeild on JTable

    Hi,
    I have a JTable and I added then added a JTextFeild to a particular column.For that i used the following code.
    public class PackageCellEditor extends DefaultCellEditor {
         public PackageCellEditor(JTextField jTextFeild) {
              super(jTextFeild);          
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
         if (value==null) return null;
    //     ((JTextField)getComponent()).setPreferredSize(new Dimension(2,2));
    //     ((JTextField)getComponent()).setMaximumSize(new Dimension(3,3));
    //     ((JTextField)getComponent()).setMinimumSize(new Dimension(2,2));
    //     ((JTextField)getComponent()).setOpaque(true);
    //     ((JTextField)getComponent()).set
         return (JTextField)getComponent();
    //     public Object getCellEditorValue(){
    }problem is while editing the text that i am typing is not visible completely since the size of the JTextFeild is more than the cell.Once the editing is complete the typed data is shown properly inside the cell.
    How to adjust the size of the JTextFeild inside the cell to fit it to the size of the cell itself.???
    Thnx
    Neel

    Try using getTableCellEditorComponent() instead of getComponent().

  • Bug when using JComboBox as JTable CellEditor

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

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

Maybe you are looking for