Customized JComboBox Editor for JTable

Hi,
I am new to swing development and have gotten my self stuck on an issue. Basically I have a JTable that is dynamically populated from the database, in which one of the columns has a customized JComboBox Renderer and Editor. The default values load up fine when the page loads up but when I selected a new value in the combo box and select a new row in the JTable, the combo box defaults back to the original value. How can I make sure that the new selection is maintain.
Thanks, Anthony
Here are my Driver, Renderer and Editor:
excerpts from the Driver
contract.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
keys = contractSelectedEvent.getKeys();
String sql = contractSelectedEvent.getSchdSql(keys);
table = contractSelectedEvent.getStatusTable(sql);
table.setDefaultRenderer(CashFlow.class, new CashFlowRenderer());
table.setDefaultEditor(CashFlow.class, new CashFlowEditor());
public class CashFlowRenderer extends JComboBox implements TableCellRenderer {
protected QueryComboBoxModel comboModel;
/** Creates a new instance of CashFlowRenderer */
public CashFlowRenderer() {
super();
comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where
Ref_Typ_ID = 910 order by Ref_ID ");
super.setModel(comboModel);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if(value == null) {
return this;
if(value instanceof CashFlow) {
//set the cashflow equal to the value
CashFlow cashFlow = new CashFlow(((CashFlow) value).getCashFlow());
setSelectedItem(cashFlow);
else {
//default the cashflow
CashFlow cashFlow = new CashFlow();
setSelectedItem(cashFlow.getCashFlow());
return this;
public boolean isCellEditable() {
return true;
public class CashFlowEditor extends JComboBox implements TableCellEditor {
protected transient Vector listeners;
protected transient String originalValue;
protected QueryComboBoxModel comboModel;
/** Creates new CashFlowEditor */
public CashFlowEditor() {
super();
comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where Ref_Typ_ID = 910 order by Ref_ID ");
super.setModel(comboModel);
listeners = new Vector();
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(value == null) {
return this;
if (value instanceof CashFlow) {
setSelectedItem(((CashFlow)value).getCashFlow());
else {
CashFlow cashFlow = new CashFlow();
setSelectedItem(cashFlow.getCashFlow());
table.setRowSelectionInterval(row, row);
table.setColumnSelectionInterval(column, column);
originalValue = (String) getSelectedItem();
return this;
public void cancelCellEditing() {
fireEditingCanceled();
public Object getCellEditorValue() {
return (String)getSelectedItem();
public boolean isCellEditable(EventObject eo) {
return true;
public boolean shouldSelectCell(EventObject eo) {
return true;
public boolean stopCellEditing() {
CashFlow cashflow = new CashFlow((String)getSelectedItem());
setSelectedItem(cashflow.getCashFlow());
fireEditingStopped();
return true;
public void addCellEditorListener(CellEditorListener cel) {
listeners.addElement(cel);
public void removeCellEditorListener(CellEditorListener cel) {
listeners.removeElement(cel);
protected void fireEditingCanceled() {
setSelectedItem(originalValue);
ChangeEvent ce = new ChangeEvent(this);
for(int i = listeners.size(); i >= 0; i--) {
((CellEditorListener)listeners.elementAt(i)).editingCanceled(ce);
protected void fireEditingStopped() {
ChangeEvent ce = new ChangeEvent(this);
for(int i = listeners.size() - 1; i >= 0; i--) {
((CellEditorListener)listeners.elementAt(i)).editingStopped(ce);

First off, I wouldn't subclass JComboBox to create a custom renderer/editor. I would have a renderer/editor component that makes use of a JComboBox. But that is just me.
In order for setSelectedItem to work, the items in your combo box have to compare against each other correctly with equals(). Since you are creating new instances, your objects (even though they contain the same data) are going to be different instances and aren't going to be considered equal. Write your own equals() method in your CashFlow object that tests for equality based on the actual values in the objects and you should be fine.

Similar Messages

  • How do I set up Premiere Elements 13 as the custom external editor for Lightroom 5?

    Situation
    I own Lightroom 5.6 and I'm experienced. I've just bought Premiere Elements 13 and I'm a video-editing virgin (be gentle with me). I've spent a day experimenting, reading, watching videos and I'm still stuck (I've tried reasonably hard to solve my own problem).
    Problem
    I've tried to set up the custom external editor in Lightroom 5 to send photos to Premiere Elements, so that I can incorporate images into movies. Having set it up, when I use it by selecting Photo/Edit In/Premiere Elements 13/, there is an exciting lull as a copy of the image is created and appears in LR, then Premiere Elements launches, then what??? There is no clue as to what has happened to the image regarding its import into Premiere Elements 13. It doesn't appear on the screen, it doesn't appear in the Organizer, it's no-where to be seen, other than in LR!
    Resolution sought:
    Can anyone tell me
    1. Is it possible to use Premiere Elements as an external editor in LR5 ?
    2. What are the precise settings should be for each field?
    3. If I configure it correctly, what does good look like: what should I expect to see happen in Premiere Elements?
    I don't know if this is relevant: MacBook Pro 16GB 2.8Ghz i7, 750GB SSD (i.e. plenty of space, plenty of horsepower), OS X 10.9.5
    I also don't know if I this is the right place for my question (Adobe directed me here) so please don't shout at me if I've come to the wrong place (I expect if I get no joy here, when I post it to an LR forum, they'll shout at me too :-)
    Thanks
    Phil

    Phil
    You wrote
    1. Is it possible to use Premiere Elements as an external editor in LR5 ?
    I do not have Lightroom 5 or other version of it. I did do some work on an earlier version tryout of it.
    And, I believe now as then, that the answer to your question is No. Bottom line, if there is integration
    to be found between Lightroom, it is between Photoshop Elements and the Elements Organizer, not the Premiere Elements Editor.
    The following is the extent of my travels through Lightroom with focus the Slideshow Module.
    Lightroom 4.1 Slideshow Module Visited - Elements Village
    Good suggestion to get the Lightroom view point at the Adobe Lightroom Forum.
    Best wishes
    ATR

  • Setting JcomboBox editor for a table cell

    Hi,
    I have a ComboBox editor for a cell in my table. I want to set this editor depending on the value of another column
    qualifierTable.addMouseListener(new MouseAdapter(){
       public void mouseClicked(MouseEvent e){
        int selRow = qualifierTable.getSelectedRow();
        int selCol = qualifierTable.getSelectedColumn();
       if (someCondition)
                JComboBox comboBoxEditor = new JComboBox();
                comboBoxEditor.addItem("Private");
                 comboBoxEditor.addItem("Protected");
                 comboBoxEditor.addItem("Public");
                 qualDataValueCol.setCellEditor(new DefaultCellEditor(comboBoxEditor));
                 Object dataValue = comboBoxEditor.getSelectedItem();
                                          if (dataValue!= null)
                 {                              qualifierTablemodel.setValueAt(dataValue, selRow, selCol);
    }The problem is this sets the editor for all cells in the column. However I want the editor to revert to JTextField if this condition is not met. Where should I set it back. It does not work if I set it in the else part

    Override the getCellEditor(...) method to return the appropriate editor. Something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=637581

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

  • Custom column headers for JTable in JScrollPane

    I want a heirachical header structure on a scrolled JTable. I've successfully generated a second JTableHeader which moves it's tabs with the normal header. If I add the secondary JTableHeader into the container above the whole scroll pane it's does almost what I want, but it's not quite correctly aligned.
    What I want to do is to put both the automaticaly generated JTableHeader and my extra one into the JScrollPane's column header area.
    I wrapped the two headers together into a vertical Box and tried calling the setColumnHeaderView() on the scrollpane, and then creating a JViewport and using setColumnHeader(). Niether seems to have any effect. The basic table header obstinately remains unaltered.
    There seems to be some special processing going on when JTable and JScrollPane get together, but I can't understand how replacing the column header viewport can be ineffective.

    Thanks. I think I've just cracked it more thoroughly, though. [I found this bug report|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5032464]. This has guided me to a work-around that seems stable so far. I'm using an extended JTable class anyway (mostly to do with table header width behaviour). I've added a field to my own table class and the following override:
    The trick is to work out where the dirty deed is done, having search all the scroll pane related classes for special casing JTable.
    public class STable extends JTable {
        @Override
        protected void configureEnclosingScrollPane() {
            if (secondaryHeader == null) {
                super.configureEnclosingScrollPane();
            } else {
                Container p = getParent();
                if (p instanceof JViewport) {
                    Container gp = p.getParent();
                    if (gp instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane) gp;
                        // Make certain we are the viewPort's view and not, for
                        // example, the rowHeaderView of the scrollPane -
                        // an implementor of fixed columns might do this.
                        JViewport viewport = scrollPane.getViewport();
                        if (viewport == null || viewport.getView() != this) {
                            return;
                        JPanel hdrs = new JPanel();
                        hdrs.setLayout(new BorderLayout());
                        hdrs.add(secondaryHeader.getHeader(), BorderLayout.NORTH);
                        hdrs.add(getTableHeader(), BorderLayout.SOUTH);
                        scrollPane.setColumnHeaderView(hdrs);
                        //  scrollPane.getViewport().setBackingStoreEnabled(true);
                        Border border = scrollPane.getBorder();
                        if (border == null || border instanceof UIResource) {
                            Border scrollPaneBorder =
                                    UIManager.getBorder("Table.scrollPaneBorder");
                            if (scrollPaneBorder != null) {
                                scrollPane.setBorder(scrollPaneBorder);
        }I'm hopeful that will prevent the column header view from being overwritten by later layout operations.

  • JTable & custom cell editor

    Hello everyone,
    what is the correct way of writing a custom cell editor for a JTable? I followed the example in the Java tutorial ([How to use tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editor]), but the result is a bit weird. The code I have is the following:
        private class NumericCellEditor extends AbstractCellEditor implements TableCellEditor {
            NumericFTField field = new NumericFTField(threeDecimalsFormat, 3, null, 1);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int col) {
                field.setValue(value);
                return field;
            public Object getCellEditorValue() {
                return field.getValue();
            @Override
            public boolean stopCellEditing() {
                if (((NumericFTField)field).verifyDouble()) {
                    field.setBorder(new EmptyBorder(0, 0, 0, 0));
                    fireEditingStopped();
                    return true;
                } else {
                    field.setBorder(BorderFactory.createLineBorder(Color.red));
                    return false;
        }where the NumericFTField is a class derived from JFormattedTextField that only allows digits, decimal separator, minus and 'E' to be inserted, and it monitors clipboard operations. verifyDouble() is a method of the NumericFTField class that verifies whether the current input can be parsed to a double and whether it satisfies everything it should. This is then used in
    ((TableColumn)jTblSpecs.getColumnModel().getColumn(1)).setCellEditor(new NumericCellEditor());The NumericFTField class works great, I use it also in place of a JTextFields, so I'd say there is nothing wrong with it.
    After I click in a cell (single click), it behaves a little different that the default cell editor: the cell is not highlighted, but it immediately jumps to the editing state (why???). I, indeed, can insert the allowed characters only. When I click in a cell, do some editing and press Enter, the cell's content gets validated. If it is invalid, stopCellEditing() method does its magic; if it is valid, the caret disappears and everything SEEMS okay. However, if I started typing at this point, the cell reverts to the editing state, but now I am able to enter any character I want. It truly looks like the cell editor is now some other component, not the original NumericFTField one. What is going on here?
    It would be great is someone could provide a short schematic source of a custom cell editor class that would work exactly as the JTable's default one except it would only permit digits and so on. It doesn't have to be anything fancy, just a "skeleton" of the class with comments like "input verification here" etc.
    I am sorry for any lack of clarity, but I am still a Java newbie.
    Any help would be much appreciated.
    Best regards,
    vt

    Hi,
    I am also facing the same problem. In addition to what you have specified, my requirement is to be able to select multiple rows for deletion. But, the very first row selected using mouse is not visible as selected though its selected. The other rows are visible as selected.
    If you can use any JDK version, start using JDK1.6. You will not be facing this problem. There were so many changes done for swings from JDK 1.4 to 1.6. But, I have to strictly use JDK1.4, but could not find any workaround for this problem.
    It would be great if anyone can help me out in this issue to get workaround for this problem.

  • Custom UI or editor for input-parameter

    I think I need to implement a custom UI editor for an input-paramenter.  My input parameter is really a HashTable. I'd like to present a dialog that allows the user to enter any number of key value pairs.  The optional "editor" element  looks promising because it allows you to specify a ui-component.  I have searched and searched for sample code, but haven't found any.  Would some kind soul please point me to a resource that shows how to implement such as custom UI (whether it involves the "editor" element or not)?
    Here's a link to the ui-component element in the reference:
    http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/help/wwhelp/wwhimpl/js/html/w whelp.htm?href=000959.html#1548965&accessible=true
    Thanks,
    Halynn

    I appreciate the reply.
    I was actually trying to point to another page, although that page may be applicable.  Apparently the URL in my browser window was not sufficient to recreate my state in livedocs.  I was looking at the reference for component.xml, specifically where it describes an optional <editor> element of <input-parameter>.  This <editor> component also has a child called <ui-component>.  I haven't found any sample code that uses these two elements.
    I need to call my component with a Map or Hashtable (an arbitrary set of Key/Value String pairs).  This Map needs to be easily configurable in LiveCycle Workbench.  I've seen numerous operations that popup dialogs for input-parameters and serialize their data.  I was thinking that I will have to implement my own dialog.
    It sounds like you are suggesting I can achieve this with a variable and the set value service.  I don't quite understand.  How would I insert the string pairs?
    Thanks,
    Halynn

  • Using ComboBox as an editor for treenodes

    I have a customized combobox editor for editing treenodes. The treenodes may or may not editable based on a particular condition in the userobject at each node.
    The node and the combobox are rendered fine but as soon as I select an item from the combobox, i see the following error messages in the stack trace and the code goes into an infinite loop :
    Exception occurred during event dispatching:
    java.lang.StackOverflowError
         at java.lang.ref.Reference.<init>(Reference.java:198)
         at java.lang.ref.FinalReference.<init>(FinalReference.java:19)
         at java.lang.ref.Finalizer.<init>(Finalizer.java:69)
         at java.lang.ref.Finalizer.register(Finalizer.java:75)
         at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:883)
         at javax.swing.JComboBox.contentsChanged(JComboBox.java:950)
         at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:79)
         at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:86)

    Here's the code for the custom combobox editor:
    public class ScmComboBoxEditor extends DefaultCellEditor
    private JTree m_tree;
    /* private JComboBox m_comboBox;
    protected EventListenerList _treeNodeListeners = new EventListenerList();
    protected ChangeEvent changeEvent = null;
    public ScmComboBoxEditor(JTree tree, JComboBox combo)
    super(combo);
    m_tree = tree;
    setClickCountToStart(3);
    public Component getTreeCellEditorComponent(JTree tree, Object value,
                                  boolean isSelected,
                                  boolean expanded,
                                  boolean leaf, int row)
    Component comp = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
    if(comp instanceof JComboBox)
    JComboBox combo = (JComboBox)comp;
    ScmTreeNode thisNode = (ScmTreeNode)value;
    /* if(thisNode.getUserObject() instanceof ScmObject)
    ScmObject thisObj = (ScmObject)thisNode.getUserObject();
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    ScmObject obj = new ScmObject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    if(thisNode.getUserObject() instanceof MappableProject)
    MappableProject thisObj = (MappableProject)thisNode.getUserObject();
    if(thisObj.hasBranches())
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    MappableProject obj = new MappableProject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    else if(thisNode.getUserObject() instanceof MappableFolder)
    MappableFolder thisObj = (MappableFolder)thisNode.getUserObject();
    if(thisObj.hasBranches())
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    MappableProject obj = new MappableProject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    return comp;
    public boolean isCellEditable(EventObject ev)
    boolean rv = false;
    if(ev instanceof MouseEvent)
    MouseEvent me = (MouseEvent)ev;
    System.out.println("Clicks = " + me.getClickCount());
    if(me.getClickCount() == this.getClickCountToStart())
    TreePath path = m_tree.getPathForLocation(me.getX(), me.getY());
    ScmTreeNode node = (ScmTreeNode)path.getLastPathComponent();
    if(((ScmObject)node.getUserObject()).hasBranches())
    rv = true;
    return rv;
    public boolean stopCellEditing()
    this.fireEditingStopped();
    return false;
    public void cancelCellEditing()
    this.fireEditingCanceled();
    /* public void addCellEditorListener(CellEditorListener l)
    _treeNodeListeners.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l)
    _treeNodeListeners.remove(CellEditorListener.class, l);
    protected void fireEditingStopped()
    Object[] listeners = _treeNodeListeners.getListenerList();
    for(int i = listeners.length-2; i >= 0; i-=2)
    if(changeEvent == null)
    changeEvent = new ChangeEvent(this);
    ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
    protected void fireEditingCanceled()
    Object[] listeners = _treeNodeListeners.getListenerList();
    for(int i = listeners.length-2; i >= 0; i-=2)
    if(changeEvent == null)
    changeEvent = new ChangeEvent(this);
    ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    public void setCellEditorValue(Object value)
    m_comboBox = (JComboBox)this.editorComponent;
    m_comboBox.setSelectedItem(value);
    }

  • Custom Property Editors in jDev

    Hello,
    I have a custom property editor for a component in the viewer window. How do I access the component from my custom property editor? The propety editor does not have any reference of the component, since it is used to set the value of the property in the property inspector. Does anyone have a way to this?? Please help.
    Another problem I faced is that a Combobox does not show the items as it normally does when used in the UI of a custom property editor. Why is it so??
    Thankyou.

    already done that....
    apparently it's something to do with the inner properties of the editor being 'hidden' and the IDE doesn't notice that the bean has changed when its inner properties have changed.
    tried setting the property to 'hidden' as recommended elsewhere, but still no luck

  • Setting value in a cell in JTable where editor for cell is a JComboBox

    Hi,
    I have a column in a JTable where it holds a comboBox . As the comboBox has different
    values depending on the row I've a cell editor for each row. That's fine. My problem is that one of the
    values on the comboBox launches a dialog where the user selects a new value to add to the comboBox.
    The comboBox gets updated with this new value and I call setValueAt on the table. Both get updated
    but the cell doesn't display the new value added in the JTable. I click it and the comboBox has the
    value and I've to select it to get it displayed in the cell.
    Here's the code for updating the tableModel -
    public void updateCellDetails(String value, int row)
    JComboBox combo = (JComboBox) rowEditor.getTableCellEditorComponent(
                        this,
                        value,
                        true,
                        row,
                        4);
    if (combo != null)
    combo.insertItemAt(value, combo.getItemCount() - 1);
    combo.setSelectedItem(value);
    rowEditor.setEditorAt(row, new DefaultCellEditor(combo));
    MyTableModel tableModel = (MyTableModel) getModel();
    tableModel.setValueAt(value, row, 4);
    Thanks

    Not sure if this'll help, but did you ever fire an editing-stopped event? If such an event is never fired, then editing-cancelled will be fired when you lose focus from the editor and the original value will be restored.

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

  • JTable - Custom cell editor lossing commit

    Hello,
    I have a custom cell editor and a default renderer assigned to a specific cell in my table...
    I have the following problem :
    If i change the value of cell 'c1' from value 'v1' to 'v2' and press enter and go to another cell the value in 'c1' is rendered correctly as 'v2'
    Hoever if i change the value of cell 'c1' from 'v1' to 'v2' and simply click over to another cell the value in 'c1' stays rendered as 'v1'
    Question : Is there ANY way to mimic the behavior of the user pressing enter in my custom cell editor when a user simply selects another cell, i guess on loss of focus or something..
    This is the last problem i have on the current project i am on and its very annoying.
    Thanks in advance, any help appreciated..
    -Alan

    I have the same problem using a custom Date/Time Picker Object (which extends JComboBox) as an editor within a table cell. For simplicity sake, I am posting code using only the base editable JComboBox, but it exhibits the same symptoms. If you enter a value in the TextField portion of the ComboBox and Tab, your value remains the same. If you enter a value in the TextField portion of the ComboBox and click in another cell, the value returns to the previous value (before editing began).
    import java.awt.*;                                                  // BorderLayout
    import javax.swing.*;                                               // JTable, JFrame
    import javax.swing.table.*;                                         // DefaultTableModel
    public class Tester extends JFrame
      public static void main(String[] args)
        Tester test = new Tester();
      public Tester()
        String[] values = {"Test", "Values"};
        JComboBox combo = new JComboBox(values);
        combo.setEditable(true);
        DefaultCellEditor editor = new DefaultCellEditor(combo);
        JTable table = new JTable(2, 3);
        table.getColumn(table.getColumnName(0)).setCellEditor(editor);
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

  • Setting cell editor for individual cell in JTable

    Hi there,
    I want to provide individual cell editor for my JTable. Basically, my JTable shows property names and values. I want to show different cell editors for different properties.
    I followed the advice in this post:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=423318
    but I have a question:
    I looked at the code of DefaultCellEditor. It just has a single editor component (the one provided in the constructor), so all the methods use the same component and certain aspects are customized for the type of component. Again, there can be only one type of component at a time.The problem that I am facing is that I will have different components for different row/column of the same table. So how do I implement some of the methods (for example, getCellEditorValue()), when I have multiple editor components?
    Also, how do I commit changes made by the user?
    I am extremely confused.
    Someone please help!
    Thanks.

    Actually, that's what I am currently doing.
    Here is my cell editor class:
    public class ObjectPropertyEditor extends DefaultCellEditor
           public ObjectPropertyEditor()
              super(new JTextField());
              Vector list = new Vector();
              list.add("Yes");
              list.add("No");
             myCombo = new JComboBox(list);
          public Component getTableCellEditorComponent(JTable table, Object value,
              boolean isSelected, int row, int column)
             String colName = (String)table.getValueAt(row,0);
             if(colName.equalsIgnoreCase("Leaf-Node?")) //if it is the "Leaf" property, return the combo box as the editor
                 return myCombo;
            else  //for all other properties, use JTextField of the super class
                return super.getTableCellEditorComponent(table,value,isSelected,row,column);
        private JComboBox myCombo;
    }The problem I have is that when I select a new item from the combo box, the new selection is not reflected in the tableModel. I don't know how I can achive that. I think I need the functionalities that DefaultCellEditor gives to its delegate when its constructor arguments is a combo box. But how can I get two different sets of functionalities (JTextField and JComboBox) ?
    Please help!
    Thanks.

  • Problem sorting JTable with custom cell editor

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

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

  • Set Maximum size for combobox editor in JTable

    Hi guys.
    I have a JTable with a custom JTextArea as editor for string datatypes.
    On the other hand, I have a combo editor too for some other columns of the table.
    My question is to know whether I can force the combox editor not to grow along with the text area.
    When I have a multiline text in a cell, I don 't want the combo box editor to fill the entire height of the row (the row height is continuously adjusted as user enter text into the text area cell editor), but to remain as big as just to render one line.
    Thanks.

    you know there's a swing forum, why not use it :-)
    As to your problem: the basicUI simply forces all editors to fit the cell size, returning more reasonable max-sizes for the combo wouldn't help. Way out might be to wrap into a panel with an appropriate layoutManager. Not entirely trivial, would expect some work ...
    Cheers
    Jeanette

Maybe you are looking for

  • Calculation of basic salary

    dear all experts i have one issue as in a month there are 30 days & 26 days are working days now employee takes two unpaid leaves & two paid leaves(1PL&1CL) of the 4 wt in it 0008 ,two r to be calculted on the basis of 24 days & remaining two wagetyp

  • In Abap Class, Rage declaration

    Hi, How to declare field range in Abap Class and select statement of inner join Thanks and Regards, Prabhakar Dharmala

  • Does FCS 2 utilize all 8 cores

    Hello, I am jumping between two Mac Pros. a 2.66 4-core or a 2.66 8-core. I've been researching quite a bit and it seems that those two configurations seem to be the best options. I have FCS 2 and plan on getting CS5. I don't plan on upgrading to FCS

  • Tomcat Manager Portal in BlazeDS Turnkey Server

    Hi all, Im pretty new to blazeds, and liking what i have experienced thus far. Could anyone please tell me how to access the Tomcat Manager Portal within the BlazeDS Turnkey Server Installation. Like in know it runs on port 8400 by default. So runnin

  • Why is the first page printed fine and subsequent pages are huge type with missed information?

    When printing from a website the first page that gets printed is normal: regular size print and it fits on the page. All subsequent pages are large print do not fit on the page and information is missing between printed pages. This is a recent proble