Repainting JCombobox Cells???

I am working on an app, and I want to be able to use a JComboBox to get a new snapshot from one of a set of cameras.
I have a set of JPanels that show the current image from the camera (they have a refreshing loop that repaints themselves).
When I add these pannels to a frame everything looks good.
When I add them to a JComboBox as selectable elements,...
They show the correct image when I click the drop down, but do not update (IE: when I call panel.repaint() the cells in the combobox do not change).
Anyone know of a workaround?
Todd B.Musheno ;-)

Hi Todd,
I guess the main difference in displaying them is:
1) In the JFrame they act as real components
2) In the JComboBox they are rendered by a renderer.
To have the display updated in the JComboBox you probably have to subclass DefaultComboBoxModel and, when an image changes, invoke fireContentsChanged(...).
Piet

Similar Messages

  • Problem in JTable with a JComboBox cell editor

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

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

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    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)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

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

  • JTable with JComboBox cells

    Hi all,
    When I make the JComboBox(es) become the cell of the JTable, the list of JComboBox is not expanded as the way a JComboBox behaves when you click on the arrow to see the whole list. I think the JComboBox is not receiving the mouse click event. Another way to say, something keeps the JComboBox from receiving the mouse click.
    Has anybody experienced this scenario?
    Frank.

    Is the table cell editable? If it isn't, that is your problem. Enable cell editing for that cell(s).
    Stephen

  • JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4

    Hello - this is one for the experts!
    I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
    However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
    1. Editing Cells and then advancing to the next column using tab.
    Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
    2. Editable JComboBox editors and and advancing to the next column using tab.
    Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
    With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
    (i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
    package com.test;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableTest4 extends JFrame {
         private JTable table;
         private DefaultTableModel tableModel;
         public TableTest4() {
              initFrame();
          * Initialises the test frame.
         public void initFrame() {
              // initialise table
              table = new JTable(10, 5);
              tableModel = (DefaultTableModel) table.getModel();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setRowHeight(22);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
              JButton dummyBtn1 = new JButton("Dummy Button 1");
              JButton dummyBtn2 = new JButton("Dummy Button 2");
              // initialise frame
              JPanel btnPanel = new JPanel(new GridLayout(2, 1));
              btnPanel.add(dummyBtn1);
              btnPanel.add(dummyBtn2);
              getContentPane().add(btnPanel, BorderLayout.SOUTH);
              // set renderer of first table column to be an editable combobox
              JComboBox editableCombo = new JComboBox();
              editableCombo.setEditable(true);
              TableColumn firstColumn = table.getColumnModel().getColumn(0);
              firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
         public static void main(String[] args) {
              TableTest4 frame = new TableTest4();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);

    Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
    I don't believe by adding a key listener to the cell editors will have the desired effect.
    I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
    Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating !

  • JComboBox cell editor *Listener problem

    Hi all,
    I've setup a TreeTable with a JComboBox as a CellEditor for the second column.
    Everything works just fine, except for event handling on a column with a JComboBox as cell editor.
    In my case, the second column of the TreeTable represents the state of the activities. This state can be changed either programmatically or by user input. That is, my application can automatically change the state for some reason, or the user can select a new state for a particular activity with the mouse.
    What I need to achieve is to capture events generated only from the user.
    I've tried different solutions, adding ActionListener or ItemListener to the CellEditor, but they all capture events generated by the application in addition to those generated by the user of the application.
    Can someone please give me some advice in this matter?
    Xserty

    What I need to achieve is to capture events generated only from the user.If you called the JComboBox's dataModel.setSelectedItem method yourself, no event will be fired!Unfortunately, I'm not able to update the dataModel (directly) myself.
    I'm currently using the Creating TreeTables: Part 3; here's how it kinda works: my JTreeTable extends JTable. The JTreeTable has a model: TreeTableModel extends DefaultTreeModel implements InterfaceJTreeTableModel. In this model there are two methods implemented as following:
    public Object getValueAt(Object pParentNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pParentNode;
      try {
        switch (pColumn) {
          case 0 :
            return activityNode.getName();
          case 1 :
            return activityNode.getState();
          case 2 :
            return new Boolean(activityNode.isMonitored());
          default :
            // do something
      } catch (SecurityException se) {
        // do something
      return null;
    public void setValueAt(Object pValue, Object pNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pNode;
      try {
        switch (pColumn) {
          case 1 :
            activityNode.setState((String) pValue);
            break;
          case 2 :
            activityNode.setIsMonitored(((Boolean) pValue).booleanValue());
            break;
          default :
            // do something
      } catch (SecurityException se) {
        // do something
    }Once I create my JTreeTable (with a model), I set the editor of the second column of my JTreeTable to a JComboBoxCellEditor.
    As you may have noticed, all the information are stored in the node of the TreeTableModel and the information is displayed and set by the two methods above.
    Thank you anyways for the advice :))
    Have you any idea on how I could solve the problem in this case?
    Xserty

  • JComboBox Cell Render selection problem

    .......It only changes the color of the triangle for the drop down. It does not change the color of what is selected. There is just a gray selection background
    <code>
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxColor extends JFrame
         public ComboBoxColor()
              Object[] items = { Color.red, Color.green, Color.blue };
              JComboBox comboBox = new JComboBox( items );
              comboBox.setRenderer( new ColorRenderer( comboBox) );
              getContentPane().add( comboBox, BorderLayout.NORTH );
         public static void main(String[] args)
              ComboBoxColor frame = new ComboBoxColor();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class ColorRenderer extends BasicComboBoxRenderer
              JComboBox comboBox;
              Border border;
              public ColorRenderer(JComboBox comboBox)
                   this.comboBox = comboBox;
                   border = new LineBorder( Color.WHITE );
    //setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   setText("");
                   setBackground( (Color)value );
                   if (isSelected)
                        setBorder( border );
                   else
                        setBorder( null );
                   if (index == -1)
                        System.out.println((Color)value);
    comboBox.setBackground((Color)value);
    if((Color)value==Color.RED){
    System.out.println("REd");
    comboBox.setBackground(Color.RED);
    else if((Color)value==Color.GREEN){
    System.out.println("Green");
    comboBox.setBackground(Color.GREEN);
    else{
    System.out.println("Blue");
    comboBox.setBackground(Color.BLUE);
                   return this;
    </code>

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxColor extends JFrame
         public ComboBoxColor()
              Object[] items = { Color.red, Color.green, Color.blue };
              JComboBox comboBox = new JComboBox( items );
              comboBox.setRenderer( new ColorRenderer( comboBox) );
              getContentPane().add( comboBox, BorderLayout.NORTH );
         public static void main(String[] args)
              ComboBoxColor frame = new ComboBoxColor();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class ColorRenderer extends BasicComboBoxRenderer
              JComboBox comboBox;
              Border border;
              public ColorRenderer(JComboBox comboBox)
                   this.comboBox = comboBox;
                   border = new LineBorder( Color.WHITE );
                            //setOpaque(true);
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   setText("");
                   setBackground( (Color)value );
                   if (isSelected)
                        setBorder( border );
                   else
                        setBorder( null );
                   if (index == -1)
                        System.out.println((Color)value);
                                    comboBox.setBackground((Color)value);
                                    if((Color)value==Color.RED){
                                        System.out.println("REd");
                                        comboBox.setBackground(Color.RED);
                                    else if((Color)value==Color.GREEN){
                                        System.out.println("Green");
                                        comboBox.setBackground(Color.GREEN);
                                    else{
                                        System.out.println("Blue");
                                        comboBox.setBackground(Color.BLUE);
                   return this;
    }

  • How to paint a Custom Cell  while you are editing on adjacent Cell in JTabl

    Hi All,
    I have two Columns in my Custom Table . Both Two Columns are Custom Cell Editors/Renderers.
    I have made UI such that Column1 is Label , Column 2 is TextBox / Combo/ UI Input any
    My Custom Table View when i edit some value against Max Conn. it should display Blue
    =================================
    Column A | Column B
    ==================================
    Timeout | some_unchanged_value
    *{color:#0000ff}Session{color}* | some_unchanged_value
    Log File | some_unchanged_value
    ===================================
    My issue is when i start typing in my Custom Editor suppose i Type /invoke Edtir of Index 2, Column 2 font should become Blue.
    It becomes blue only when i debug this issue it perfectly works, without Debugger it doesnt changes the Font
    MyDefaultRenderer is my Custom renderer - I have set Foregroud Color as BLUE
    NOTE:_
    In run method if table.repaint() instead of single renderer:
    It turns Blue when i make call on table.repaint() methosd but i feel that repainting full table on every key Stroke should not be very good programming. Whats is more appropriate way?
    I want to repaint only that particular cell against which i change the Value
        private class MyDefaultEditor extends AbstractCellEditor implements TableCellEditor {
            private JTextField txtField = null;
            private int rowIndex;
            public MyDefaultEditor() {
                txtField = new JTextField();
                txtField.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyTyped(KeyEvent e) {
                        super.keyTyped(e);
                        System.out.println("########### Hello This is MyDefaultEditor");
                  SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                  // Call Renderer adjacentt to input to turn Blue (Is this Valid Code ??)
                                MyDefaultRenderer defRen = (MyDefaultRenderer) thisTable.getCellRenderer(activeRowIndex, 0);
                                defRen.paintMe();
              // table.repaint() works for me but i dont want to call it on evey ket type, that will be Heave rite???
            public Component getTableCellEditorComponent(JTable table,
                    Object value, boolean isSelected, int row, int column) {
                rowIndex = row;
                String valStr = "";
                if (value != null && value instanceof String) {
                    valStr = value.toString();
                txtField.repaint();
                return txtField;
            public Object getCellEditorValue() {
                return txtField.getText();
        }Edited by: Shubhadeep on Jun 27, 2009 1:58 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:01 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:06 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:12 AM

    Well, I think you need to add a custom renderer to the first column. The renderer would check if the table.isEditing(). If it is and the editing is done on the same row, then you set the font color blue, otherwise you use the default font color.
    Then the next question is how do you repaint the cell. Well you can use the table.repaint(Rectangle) method. You can get the Rectangle to repaint by using the table.getCellRect(...) method.
    Finally, you need to know when to repaint the cell. Well a PropertyChangeEvent is fired when a cell starts and stops editing. So you only need to handle these events. Don't use a KeyListener. The PropertyChangeListener you add to the table might be something like:
    public void propertyChange(PropertyChangeEvent e)
         if ("tableCellEditor".equals(e.getPropertyName()))
              if (table.isEditing())
                   processEditingStarted();
              else
                   processEditingStopped();
    }So when editing is started you need to determine the "adjacent" cell you want to repaint to the blue font is used. You would save the cell Rectangle so you can restore the font when editing is stopped.

  • JTable custom cell editor focus problem

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

  • JComboBox CellEditor and setValueAt() question

    I have created a JTable that uses a unique JComboBox cell editor for each cell in a column. This works well visually, but now those cells do not seem to use the setValueAt() method in my table model. I was using this to capture the data for the database. What is the correct way to find what the data within those combo has been changed to?? All help is greatly appreciated.

    I have created a JTable that uses a unique JComboBox cell editor for each cell in a column. This works well visually, but now those cells do not seem to use the setValueAt() method in my table model. I was using this to capture the data for the database. What is the correct way to find what the data within those combo has been changed to?? All help is greatly appreciated.

  • Cell Rendering

    Howdy,
    With Cell Rendering, I have got it working, is there anyway
    to get it to apply to specific cells on a datagrid, or is it column
    based....
    Thanks,
    Nathan

    First of all quit posting multiple question on the same topic. How are people supposed to know what has already been suggested when you keep starting new postings?
    sorry, it does not extend the abstract table model. Is there any other options pls? I'll bet you it does. Why on earth would you attempt to write your own TableModel without extending AbtractTableModel. Maybe you are extending DefaultTableModel, which in turn extends AbtractTableModel.
    Anyway, that is not the problem. Firing the event only tells the table to repaint a cell. It does not tell the table how to paint the cell. You need to have custom code in your renderer that knows what color to paint the cell. Just clicking on a button doesn't magically cause the cell to be painted a different color.
    Maybe something like this will get you started:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=606504

  • Add Divider to JComboBox

    Hello,
    I was wondering how I can add a divider after I add each symbol to this JComboBox? Is JSeparator a good idea?
    Please help out.
    import java.util.ArrayList;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JSeparator;
    public class MyComboBoxDividerTest extends JComboBox {
         private DefaultComboBoxModel myModel = new DefaultComboBoxModel();
         public MyComboBoxDividerTest()
              setModel(myModel);
              setEditable(true);
         public void generateComboBox()
              ArrayList list = new ArrayList();
              list.add("symbol1");
              list.add("symbol2");
              list.add("symbol3");
              list.add("symbol4");
              list.add("symbol5");
              JFrame frame = new JFrame("My ComboBox");
              for(int i=0;i<list.size();i++)
                   myModel.addElement(list.get(i));
                   //TODO: ADD SEPARATOR HERE (I think)
              JComboBox comboBox = new JComboBox(myModel);
              frame.getContentPane().add(comboBox);
              frame.setSize(200,55);
              frame.setVisible(true);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              MyComboBoxDividerTest test = new MyComboBoxDividerTest();
              test.generateComboBox();
    }

    You dont need to add a JSeparator at all. This is not a model level issue but a renderer level issue. In other words you'll have to modify you JComboBox cell renderer instead of its model
    From the ListCellRenderer documentation with modifications. Check Out the commented addition:
    class MyCellRenderer extends JLabel implements ListCellRenderer {
         public MyCellRenderer() {
             setOpaque(true);
         public Component getListCellRendererComponent(JList list,
                                                       Object value,
                                                       int index,
                                                       boolean isSelected,
                                                       boolean cellHasFocus) {
             setText(value.toString());
             // you can draw the line using a MatteBorder
             // you may need to implement a CompoundBorder to get add spacing around the text using an EmptyBorder
             setBorder( new MatteBorder(0,0,2,0, Color.black) ); //
             Color background;
             Color foreground;
             // check if this cell represents the current DnD drop location
             JList.DropLocation dropLocation = list.getDropLocation();
             if (dropLocation != null
                     && !dropLocation.isInsert()
                     && dropLocation.getIndex() == index) {
                 background = Color.BLUE;
                 foreground = Color.WHITE;
             // check if this cell is selected
             } else if (isSelected) {
                 background = Color.RED;
                 foreground = Color.WHITE;
             // unselected, and not the DnD drop location
             } else {
                 background = Color.WHITE;
                 foreground = Color.BLACK;
             setBackground(background);
             setForeground(foreground);
             return this;
    // once you have the Renderer, connect it to your JComboBox
    JComboBox box = new JComboBox();
       box.setRenderer( new MyCellRenderer() );Cheers, ICE

  • Cell rendering to specific cell

    Does anyone know how to render specific cells once a button is clicked. I do not want to render all the column or row but only certain cells.

    First of all quit posting multiple question on the same topic. How are people supposed to know what has already been suggested when you keep starting new postings?
    sorry, it does not extend the abstract table model. Is there any other options pls? I'll bet you it does. Why on earth would you attempt to write your own TableModel without extending AbtractTableModel. Maybe you are extending DefaultTableModel, which in turn extends AbtractTableModel.
    Anyway, that is not the problem. Firing the event only tells the table to repaint a cell. It does not tell the table how to paint the cell. You need to have custom code in your renderer that knows what color to paint the cell. Just clicking on a button doesn't magically cause the cell to be painted a different color.
    Maybe something like this will get you started:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=606504

  • Using two editor instances within JTable

    Hello,
    I'm struggling around using component editors within JTable. E.g. selectAll text on entering a JTextField cell or immediately raising the popup while entering a JComboBox cell.
    In my analysis most of these problems arises due the re-use of the cell editor.
    The event sequence is doing things in the context of the old cell while preparing the editor for the new cell has already been started.
    Because it is the same component and some things are bound deep inside the L&F it seems not easy to handle them properly.
    Just an idea from me is to avoid such problems by working with two instances for the editors in general. This should avoid all problems coming out of overlapping event processing. (To provide each cell with an own component is of course no solution)
    Any comment on such an approach?
    Thanks in advance
    Wolfgang R.

    No, it wasn't the custom JTable extension.
    By entering a cell a popup will be shown for a short moment. This is only by using Windows L&F (not Metal). Within the L&F a togglePopup() is called which may cause this problem.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableExt extends JTable {
         public static class ComboBoxEnumRenderer extends JComboBox implements
                   TableCellRenderer {
              public ComboBoxEnumRenderer() {
                   setEditable(false);
                   setBackground(Color.WHITE);
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                   this.removeAllItems();
                   this.addItem(value);
                   return this;
         public static class ComboBoxEnumEditor extends DefaultCellEditor {
              private static String[] values = null;
              public ComboBoxEnumEditor() {
                   super(new JComboBox());
                   values = new String[50000];
                   for (int i = 0; i < values.length; i++) {
                        values[i] = "row_" + i;
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   JComboBox combo = (JComboBox) getComponent();
                   combo.removeAllItems();
                   for (int i = 0; i < values.length; i++) {
                        combo.addItem(values);
                   combo.setSelectedIndex(0);
                   return super.getTableCellEditorComponent(table, value, isSelected, row,
                             column);
         public JTableExt() {
              super();
              init();
         // invoke editor on cell entry
         public void changeSelection(final int row, final int column, boolean toggle,
                   boolean extend) {
              super.changeSelection(row, column, toggle, extend);
              if (editCellAt(row, column))
                   getEditorComponent().requestFocusInWindow();
         private void init() {
              setDefaultEditor(Object.class, new ComboBoxEnumEditor());
              setDefaultRenderer(Object.class, new ComboBoxEnumRenderer());
         private static void setUI() {
              String lnfName = "";
              //lnfName = "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel";
              lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
              try {
                   UIManager.setLookAndFeel(lnfName);
              } catch (Exception exc) {
         public static void main(String args[]) {
              try {
                   setUI();
                   javax.swing.JFrame frame = new javax.swing.JFrame();
                   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                   frame.getContentPane().setLayout(new BorderLayout());
                   final JTableExt demo = new JTableExt();
                   Object[][] data = new Object[30][1];
                   demo.setModel(new DefaultTableModel(data, new String[] { "first column" }));
                   frame.getContentPane().add("Center", new JScrollPane(demo));
                   frame.setSize(600, 600);
                   frame.setVisible(true);
              } catch (Throwable t) {
                   System.exit(0);
    //end

Maybe you are looking for