Displaying a JComboBox in JTable

I have a JComboBox in a JTable. The JComboBox contains JCheckBox's.
To enable the user to select multiple checkbox items in the combobox, my class which extends JComboBox also implements ComboBoxEditor. In getItem I use showPopup inside a thread to enable multiple selections.
public Object getItem()
SwingUtilities.invokeLater(new Runnable()
public void run()
showPopup();
return getSelectedItem();
The code that I have written works when the combobox is dsplayed in a panel. However, when it is placed in a JTable it fails with a:
Exception occurred during event dispatching:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
     at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
     at java.awt.Component.getLocationOnScreen(Component.java:1481)
     at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
     at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
     at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
     at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
     at javax.swing.JComboBox.showPopup(JComboBox.java:775)
     at com.clarologic.pm.backoffice.usermanagement.accounts.usertabs.branchdetails.rolecombobox.RoleComboBox$1.run(RoleComboBox.java:155)
The last line corresponds to the showPopup(); in the getItem() function.
Anyone seen this and resolved it before ??
Chris

ICE,
public Object getItem()
SwingUtilities.invokeLater(new Runnable()
public void run()
if (isShowing())
showPopup();
return getSelectedItem();
This certainly stops the exception, however, it also wrecks the desired functionality.
I wonder if the table renderer is getting in the way, which is causing the problem to occur.
Chris

Similar Messages

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

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

  • 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

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

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

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

  • JComboBox within JTable

    Hi,
    I've got the following problem with my JComboBox:
    The JComboBox zcb is filled out of a database (this works!). This JComboBox is a column of the JTable jtbDauerlaeufe (this works, too!).
    Now the strange behaviour:
    1.) In the application I open for the first time the JDialog which the JTable is part of.
    2.) Then the correct value in the JTable column is displayed.
    3.) I click with the mouse in the column with my JComboBox => the ComboBox opens, but not with the selected (or displayed) value of my column, but with the first value of available JComboBox-values :-(
    4.) When I leave the JComboBox and open it again, then the selected/displayed value of my column is also selected within my JComboBox.
    Now my question:
    Why is this behaviour not available when I open my JComboBox the first time? And what have I to do for getting the selected value of my jtable-column when I open the JComboBox the first time???
    JComboBox zcb = new JComboBox();
    // gets the JTable-column for the JComboBox
    tc = jtbDauerlaeufe.getColumn(model.getZETColName());
    // fill the values in the JComboBox
    broker.getZaehlereinheitenBroker().fillComboBox(zcb);
    tc.setCellEditor(new DefaultCellEditor(zcb));
    Any help & hint is very welcome,
    Fe

    Hi
    The problem is not with ur JComboBox.. It lies where u set the datavector of the JTable..
    1. What type of objects does the ComboBox hold. Simple String or other Objects??
    2. How do u set the JTable data the first time??
    First time I think u wuld be explicitly setting the table data with different kind of objects , say string value for the column holding the combobox. Thats y the first time while loading it works properly.
    Try changing the combobox values with strings instead of other Objects.. tell me if it works :)
    Nisha

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

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    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 < 1) {
    return false;
    } else {
    return true;
    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("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • How to display images in a Jtable cell-Urgent

    Hay all,
    Can anybody tell me that can we display images to JTable' cell,If yes the how do we do that(with some code snippet)? Its very urgent .Plz reply as soon as possible.

    Here is an example
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class SimpleTableExample extends JFrame
         private     JPanel  topPanel;
         private     JTable  table;
         private     JScrollPane scrollPane;
         public SimpleTableExample()
              setTitle( "Table With Image" );
              setSize( 300, 200 );
              setBackground( Color.gray );
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              getContentPane().add( topPanel );
              // Create columns names
              String columnNames[] = { "Col1", "Col2", "Col3" };
              // Create some data
              Object data[][] =
                   { (ImageIcon) new ImageIcon("User.Gif"), (String) "100", (String)"101" },
                   { (String)"102", (String)"103", (String)"104" },
                   { (String)"105", (String)"106", (String)"107" },
                   { (String)"108", (String)"109", (String)"110" },
              // Create a new table instance
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              };          // Add the table to a scrolling pane
              scrollPane = new JScrollPane( table );
              topPanel.add( scrollPane, BorderLayout.CENTER );
         public static void main( String args[] )
              SimpleTableExample mainFrame     = new SimpleTableExample();
              mainFrame.setVisible( true );
    }

  • How To Display Table Header in JTable

    Hi,
    I have a tree node that is a JTable. It displays the cells, but not the header or the left hand side of the table.
    Here is my code ...
    Anyone got any ideas?
    public SimpleTree() {
    super("Creating a Simple JTree");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    JTable table;
         String columnNames[] = { "OrderID", "CustomerID", "EmployeeID", "Order Date", "Shipped Date" };
         String dataValues[][] =
              { "34", "234", "67","12/02/2002", "16/04/2002" },
              { "-123", "43", "853","12/02/2002", "16/04/2002" },
              { "93", "89.2", "109","12/02/2002", "16/04/2002" },
              { "279", "9033", "3092","12/02/2002", "16/04/2002" }
         table = new JTable( dataValues, columnNames );
         table.setEnabled(true);
         table.isCellEditable(4,4);
         table.setShowHorizontalLines(true);
         table.setShowVerticalLines(true);     
         table.getTableHeader().setForeground(Color.black);
         table.getTableHeader().setBackground(Color.lightGray);
         table.getTableHeader().setReorderingAllowed(true);
         table.getTableHeader().resizeAndRepaint();
         JTableHeader header = table.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.setReorderingAllowed(true);
         Object[] hierarchy =
    { "Orders",
    new Object[] { "Orders",
                                  table},
    new Object[] { "Prodcuts",
    new Object[] { "",
    table },
    "Employees",
    "Suppliers" };
         DefaultMutableTreeNode root = processHierarchy(hierarchy);
         JTree tree = new JTree(root);
         tree.putClientProperty("JTree.lineStyle", "Angled");
         tree.setCellRenderer(new MyTreeCellRenderer(table));
         tree.setCellEditor(new SimpleTreeCellEditor(table));
         tree.repaint();
         table.repaint();
         tree.setRowHeight(-2);      
         tree.setEditable(true);
         content.add(new JScrollPane(tree), BorderLayout.CENTER);
         setSize(275, 300);
    setVisible(true);

    The column header is a different component of the table component. You can get this component directly and place it wherever you want in a container, just get them from the JTable:JPanel aPanel = new JPanel( new BorderLayout() );
    JTable myTable = xxx;
    aPanel.add( myTable.getTableHeader() , BorderLayout.NORTH );
    aPanel.add( myTable, BorderLayout.CENTER );

Maybe you are looking for