Cell editor removed when table resized

I'm using Java 1.5.0_06 in my application. I have a JFrame which contains a JTable. I use FormLayout (which is like GridBagLayout). When the frame resizes, the table resizes too.
When I enter edit mode in a cell of the table and resize the frame (and the table), the cell exits edit mode. The editor of the cell is removed when the table is resized which causes the value that I had entered in the cell to be lost.
Is there a way to stop cell editing when the frame is resized instead of the cell just exiting edit mode.
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
public class ResizableTableTest extends JFrame {
     final JScrollPane _scrollPane;
     public static void main(String[] args) {
          ResizableTableTest frame = new ResizableTableTest();          
            frame.addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
            frame.setSize(451, 340);
            frame.setVisible(true);
     public ResizableTableTest() {
          super();
          getContentPane().setLayout(new FormLayout(
               new ColumnSpec[] {
                    new ColumnSpec("default:grow(1.0)"),
                    FormFactory.RELATED_GAP_COLSPEC,
                    FormFactory.DEFAULT_COLSPEC},
               new RowSpec[] {
                    new RowSpec("default:grow(1.0)"),
                    FormFactory.RELATED_GAP_ROWSPEC,
                    FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.RELATED_GAP_ROWSPEC,
                    FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.RELATED_GAP_ROWSPEC,
                    FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.RELATED_GAP_ROWSPEC,
                    FormFactory.DEFAULT_ROWSPEC}));
          _scrollPane = new JScrollPane();
          getContentPane().add(_scrollPane, new CellConstraints(1, 1, CellConstraints.FILL, CellConstraints.FILL));
          addTableToScrollPane();
     private void addTableToScrollPane() {
           JTable table = new JTable();
         DefaultTableModel model = (DefaultTableModel)table.getModel();
         table.setRowSelectionAllowed(false);
         table.setCellSelectionEnabled(true);
         //Add some columns
         model.addColumn("column A");
         model.addColumn("column B");
         model.addRow(new Object[]{"item1", "apple"});
         model.addRow(new Object[]{"item2", "banana"});
         model.addRow(new Object[]{"item3", "carrot"});
         model.addRow(new Object[]{"item1", "grape"});        
         _scrollPane.setViewportView(table);          
}thanks,

I would assume that on the resize of the table the
editing cancelled event is being fired...
You could try overriding the method in the JTable and
when it gets fired, fire the editing stopped method
instead... not sure whether that will work thoughI tried that, but it didn't help. On searching for this problem, I saw a bug report on this very problem.
Here's info on a related bug in java:
Cell editing does not complete when JTable loses focus
Lost newly entered data in the cell when resizing column width
And here's an interesting article:
Why Editable Table Cells Are Evil
Message was edited by:
petes1234

Similar Messages

  • How can I get right data in a cell of JTable when table  enter editing

    how can I get right data in a cell of JTable when table enter editing

    how can I get right data in a cell of JTable when table enter editing

  • Small issue with custom table cell editor and unwanted table row selection

    I'm using a custom table cell editor to display a JTree. Thing i notice is that when i select a value in the tree pop-up, the pop-up closes (as it should) but then every table row, from the editing row to the row behind the pop-up when i selected the value becomes highlighted. I'm thinking this is a focus issue, but it thought i took care of that. To clairfy, look at this: Before . Notice how the "Straightening" tree item is roughly above the "Stock Thickness" table row? When i select Straightening, this is what happens to my table: After .
    My TreeComboBox component:
    public class TreeComboBox extends JPanel implements MouseListener {
        private JTextField itemField;
        private TreeModel treeModel;
        private ArrayList<ActionListener> actionListeners = new ArrayList<ActionListener>();
        private Object selectedItem;
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
        public TreeComboBox(TreeModel treeModel) {
            this(treeModel, null);
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public TreeComboBox(TreeModel treeModel, Object selectedItem) {
            this.treeModel = treeModel;
            this.selectedItem = selectedItem;
            initComponents();
         * Returns the current drop-down tree model.
         * @return the current <code>TreeModel</code> instance.
        public TreeModel getTreeModel() {
            return treeModel;
         * Sets the tree model.
         * @param treeModel a <code>TreeModel</code> instance.
        public void setTreeModel(TreeModel treeModel) {
            this.treeModel = treeModel;
         * Returns the selected item from the drop-down selector.
         * @return the selected tree object.
        public Object getSelectedItem() {
            return selectedItem;
         * Sets the selected item in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public void setSelectedItem(Object selectedItem) {
            this.selectedItem = selectedItem;
            String text = selectedItem != null ? selectedItem.toString() : "";
            itemField.setText(text);
            setToolTipText(text);
         * Overridden to enable/disable all child components.
         * @param enabled flat to enable or disable this component.
        public void setEnabled(boolean enabled) {
            itemField.setEnabled(enabled);
            super.setEnabled(enabled);
        public void addActionListener(ActionListener listener) {
            actionListeners.add(listener);
        public void removeActionListener(ActionListener listener) {
            actionListeners.remove(listener);
        // MouseListener implementation
        public void mouseClicked(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
            showPopup();
        private void initComponents() {
            setLayout(new GridBagLayout());
            itemField = new JTextField();
            itemField.setEditable(false);
            itemField.setText(selectedItem != null ? selectedItem.toString() : "");
            itemField.addMouseListener(this);
            add(itemField, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        private void showPopup() {
            final TreePopup popup = new TreePopup();
            final TreeComboBox tcb = this;
            final int x = itemField.getX();
            final int y = itemField.getY() + itemField.getHeight();
            int width = itemField.getWidth() + popupButton.getWidth();
            Dimension prefSize = popup.getPreferredSize();
            prefSize.width = width;
            popup.setPreferredSize(prefSize);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popup.show(tcb, x, y);
                    popup.requestFocusInWindow();
        private void fireActionPerformed() {
            ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "TreeComboBoxSelection");
            for (ActionListener listener : actionListeners) {
                listener.actionPerformed(e);
        private class TreePopup extends JPopupMenu {
            private JTree tree;
            private JScrollPane scrollPane;
            public TreePopup() {
                initComponents();
                initData();
            private void initData() {
                if (treeModel != null) {
                    tree.setModel(treeModel);
            private void initComponents() {
                setFocusable(true);
                setFocusCycleRoot(true);
                tree = new JTree();
                tree.setRootVisible(false);
                tree.setShowsRootHandles(true);
                tree.setFocusable(true);
                tree.setFocusCycleRoot(true);
                tree.addTreeSelectionListener(new TreeSelectionListener() {
                    public void valueChanged(TreeSelectionEvent e) {
                        tree_valueChanged(e);
                scrollPane = new JScrollPane(tree);
                add(scrollPane);
            private void tree_valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                setSelectedItem(node.getUserObject());
                fireActionPerformed();
                this.setVisible(false);
    }My TreeComboBoxTableCellEditor:
    public class TreeComboBoxTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
        protected TreeComboBox treeComboBox;
        protected ArrayList<CellEditorListener> cellEditorListeners = new ArrayList<CellEditorListener>();
        public TreeComboBoxTableCellEditor(TreeComboBox treeComboBox) {
            this.treeComboBox = treeComboBox;
            treeComboBox.addActionListener(this);
        public Object getCellEditorValue() {
            return treeComboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            treeComboBox.setSelectedItem(value);
            return treeComboBox;
        public void actionPerformed(ActionEvent e) {
            stopCellEditing();
    }Any thoughts?
    Edited by: MiseryMachine on Apr 3, 2008 1:21 PM
    Edited by: MiseryMachine on Apr 3, 2008 1:27 PM

    As I said, you have to have empty context elements before additional rows will be open for input.
    For instance if you want to start with 5 rows available for input do the following to your internal table that you will bind:
    data itab type standard table of sflight.
    do 5 times.
      append initial line to itab.
    enddo.
    context_node->bind_table( itab ).
    The other option if you need n number of rows is to add a button to the table toolbar for adding more rows. When this button is pressed, you add a new context element to the node - thereby creating a new empty row in the table.

  • Dynamically change the cell editor in the table control

    Hi..
         I have 3 columns in a table . of which in one column we need to change the cell editor dynamically at runtime.
    i.e for example i have  columns as carrid, connid and fldate.
    For the first 2 rows the cell editor for the carrid  clomn shud be a dropdown and from there on in the next rows for the same  carrid column it shud be a input field.
    Can experts plz help me how to achieve this as this is very high priority issue....
    Regards,
    Madhu...

    This is actaully fairly simple to do.  You will need to add a cellVariant to your table column. You can then dataBind a context attribute to the selectedCellVariant property of the column to control which cellVariant will be used. This allows you to control row-by-row which cell editor you want to output.
    http://help.sap.com/saphelp_nw70/helpdata/EN/bd/5d9041d3c72e7be10000000a1550b0/frameset.htm
    http://help.sap.com/saphelp_nw70/helpdata/EN/56/5e9041d3c72e7be10000000a1550b0/frameset.htm
    Also here is an example that I did the other day that uses Cell Variants within ALV.  This process is actually a little more complicated because you have to go through the ALV APIs.  To do this in a normal table is actually easier because you can create the cellVariant in the layout designer.
    Re: Freely-programmed value help for a single ALV cell

  • Saving table cell editor value when switch to other cell

    Hello,
    I have the code below to allow user entering integer values in a table cell. What I want is that if the user switch to an other cell than I want to save the editor value. It works fine if the user press the Enter button, but how can I do this when user clicks or press tab, arrow to switch to an other cell?
    public class IntegerEditor extends AbstractCellEditor implements TableCellEditor, ActionListener{
         JFormattedTextField component = new JFormattedTextField(NumberFormat.getIntegerInstance());
         public IntegerEditor(){
              component.addActionListener(this);
                                              component.setBorder(null);             
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                          if (value != null)  component.setValue(value);
                          return component;
         public Object getCellEditorValue() {
              return Integer.valueOf(component.getValue().toString());
         public void actionPerformed(ActionEvent e) {
              fireEditingStopped();
    }

    Hello camickr,
    I add a column to the table with the function see below.
    With this sollution I the cell value saving is working fine, but it accept string vales for me :(
    If I use the JFormattedTextField than it accepts only integers but I have the original problem. I'm using fireEditingStopped(); in the focusLost method but it has no effect.
    What do I wrong?
    public TableColumn addNewIntegerColumn(java.lang.String caption, int width, boolean fix) {
          //Switch off AutoCreate
          this.setAutoCreateColumnsFromModel(false);
          //Create a new Column
          TableColumn col = new TableColumn(dataSheet.getColumnCount(),width,new LabelRenderer(),this.getDefaultEditor(Integer.class) );
          //Set column header
          col.setHeaderRenderer(new HeaderRenderer());
          col.setHeaderValue(caption);
         if (fix) col.setResizable(false);
          col.setPreferredWidth(width);
          //Add column to the table
          this.addColumn(col);
          //Add column to the model
          dataSheet.addColumn(caption);
          return col;
    }

  • Stopcellediting removes my custom cell editor

    Hi Gurus,
    Please look at the following where I am using stopcellediting with my custom editor. Problem is when I use stopcellediting, it removes the cell editor from the table, so in result any function I want to do in the cell editor doesnt get executed anymore. I tried setcelleditor right after stopcellediting but did not fix.
    For example if user types anything else than number I want to check and when it reaches 10 characters I want to add new blank record, but stopCellEditing does not let me do it, and I have to stopCellEditing in certain conditions (I did not include those conditions here) eg if user clicks tab or delete or etc.
    Pleas HELP
    Thanks,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class TableEdit extends JFrame
         TableEdit()
              JTable table = new JTable(5,5);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollpane = new JScrollPane(table);
              getContentPane().add(scrollpane);
              //  Use a custom editor
              TableCellEditor fce = new FiveCharacterEditor();
              table.setDefaultEditor(Object.class, fce);
        // Editor class
        class MyNumberEditor extends javax.swing.AbstractCellEditor implements TableCellEditor
            private JTextField editor;
            public MyNumberEditor()
                super();
                editor = new JTextField();
                try
                    editor.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(KeyEvent e)
                            super.keyTyped(e);
                            editorKeyTyped(e, 0);
                        public void keyReleased(KeyEvent e)
                            super.keyReleased(e);
                            editorKeyTyped(e, 1);
                } catch (Exception e){}
            public Object getCellEditorValue()
                return editor.getText();
            public Component getTableCellEditorComponent(JTable table,
                    Object value, boolean isSelected, int row, int column)
                if(value instanceof String)
                    editor.setText((String)value);
                return editor;
            private void editorKeyTyped(KeyEvent e, int event)
    System.out.println("editorKeyTyped.................: "+e.getKeyCode()+" - "+e.getKeyChar());
                if(event == 1)
                    if(jTable.isEditing())
                        stopCellEditing();
    //                    tableColumn.setCellEditor(this);
                    int numbers = 0;
                    int rows = jTable.getRowCount();
                    for(int i = 0; i < rows; i++)
                        String number = ((String)jTable.getValueAt(i, 0)).trim();
                        if(number.length() > 0)
                            numbers++;
                if(event == 0 && editor.getText().trim().length() == 9 && e.getKeyChar() != 8)
                    addBlankRecord();
         public static void main(String [] args)
              JFrame frame = new TableEdit();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

    hi camikr
    Thanks again for your help.
    here is the sample program, i tried setClickCountToStart. it still doesnt show the cursor, if i dont click.
    Also when I type the value in the first cell eg, i have to press tab TWICE to get to the next cell. or if it has error eg not 10 digits and then I fix it then again i have press TAB twice to get to next field
    How can display the cursor when I click or use tab to next field, and how to use one tab only to get to the next field.
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.text.*;
    public class MyTable2 extends JFrame
        JTable jTable;
        DefaultTableModel tm;
        MyTable2()
            jTable = null;
            tm = null;
            JButton dumy = new JButton("dummy button");
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            tm = new DefaultTableModel(1, 1);
            jTable = new JTable(tm);
            jTable.setPreferredScrollableViewportSize(jTable.getPreferredSize());
            JScrollPane scrollpane = new JScrollPane(jTable);
            scrollpane.setPreferredSize(new Dimension(100,200));
            panel.add(dumy, "North");
            panel.add(scrollpane, "South");
            JTextField field = new JTextField();
            TableCellEditor fce = new MyNumberEditor(field);
            TableColumn col = null;
            col = jTable.getColumn(jTable.getColumnName(0));
            col.setCellEditor(fce);
            getContentPane().add(panel);
        class MyNumberEditor extends DefaultCellEditor
            String allowedValues = "0123456789";
            int allowedLength = 10;
            public MyNumberEditor(JTextField field)
                super(field);
                setClickCountToStart(0);
            public boolean stopCellEditing()
                try
                    String editingValue = (String)getCellEditorValue();
                    if(editingValue.length() > 0 && editingValue.length() != allowedLength)
                        setErrorMessage("Please enter 10 digits.");
                        return false;
                    if(editingValue.length() == allowedLength)
                        for(int i = 0; i < allowedLength; i++)
                            String val = editingValue.substring(i,i+1);
                            if(allowedValues.indexOf(val) == -1)
                                setErrorMessage("Please enter digits only.");
                                return false;
                } catch(ClassCastException exception)
                    return false;
                boolean stopped = super.stopCellEditing();
                tm.addRow(new Object[]{""});
                return stopped;
            public void setErrorMessage(String message)
                JTextField textField = (JTextField)getComponent();
                textField.setBorder(new LineBorder(Color.red));
                textField.selectAll();
                textField.requestFocus();
                JOptionPane.showMessageDialog(null,
                                              message, "Error",JOptionPane.ERROR_MESSAGE);
            public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column) {
                Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                ((JComponent)c).setBorder(new LineBorder(Color.black,1));
                return c;
        public static void main(String args[])
            JFrame frame = new MyTable2();
            frame.setDefaultCloseOperation(3);
            frame.pack();
            frame.setVisible(true);
    }

  • Focus cell editor component of JTable when starting editing by typing

    Hello, everybody.
    We all know that the JTable component doesn't actually focus the actual cell editor component when editing is started by typing. But I need this functionality in an application of mine. So, I ask: is there a way to transfer focus to the editor component when editing is started by typing?
    Thank you.
    Marcos

    Well, I think that I've found it: JTable#setSurrendersFocusOnKeystroke.
    Marcos

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

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

  • How to use cell editors in JTree?

    Hi,
    I have a component where I am placing JTable in JTree node.The table cells should be editable.
    I was unable to do that.
    I am giving code for 2 classes below,which I used.
    To test this compile the classes seperately.
    /**************************TableInTree.java(main class)**************/
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class TableInTree extends JFrame
    public TableInTree()
    super("TableInTree");
    JTree tree = new JTree(this.createTreeModel());
    tree.setCellRenderer(new ResultTreeCellRenderer());
    tree.setEditable(true);
    this.getContentPane().add(new JScrollPane(tree));
    public static void main(String[] args)
    TableInTree frame = new TableInTree();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.show();
    // * Method createRootNodes.
    private TreeModel createTreeModel()
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("test1");
    node1.add(new DefaultMutableTreeNode(new TableRenderDemo)));
    root.add(node1);
    root.add(new DefaultMutableTreeNode("test2"));
    return new DefaultTreeModel(root, true);
    public static class ResultTreeCellRenderer extends DefaultTreeCellRenderer
    public Component getTreeCellRendererComponent(JTree t, Object value,boolean s, boolean o,boolean l, int r, boolean h)
    if (value instanceof DefaultMutableTreeNode)
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    if (node.getUserObject() instanceof TableRenderDemo)
    return new JScrollPane((TableRenderDemo) node.getUserObject());
    return super.getTreeCellRendererComponent(t, value, s, o, l, r, h);
    /*******************TreeRenderDemo.java**************************/
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.table.*;
    import java.awt.*;
    * 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 TableRenderDemo extends JPanel {
    private boolean DEBUG = false;
    public TableRenderDemo() {
    super(new GridLayout(1,0));
    JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //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.
    setUpSportColumn(table, table.getColumnModel().getColumn(2));
    //Add the scroll pane to this panel.
    add(scrollPane);
    * 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 =
    ((JTableHeader)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");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Knitting", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", "Milne",
    "Pool", new Integer(10), new Boolean(false)}
    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[j]);
    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() {
    //Make sure we have nice window decorations.
    //JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo newContentPane = new TableRenderDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    Please give me a solution.
    thanks in advance

    rebounce

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

  • Updating a sorted table when a cell editor is open

    In Sun's table sorter demo, if you are in the middle of editing a cell and you toggle the sort on any column, the editor automatically cancels the edit, closes the editor and the table sorts appropriately. I am guessing that the cancelEditing method on the editor is called somehow by the table when the table data changes.
    For some reason, in my application, when the sort is toggled, the editor remains open and does not cancel. As a result, when the table sorts, the value you are editing is not for the correct row anymore.
    The custom cell editors I am using are not the problem because I removed them and I still have this problem.
    Unfortunately, it would be extremely difficult for me to provide a sample application to demonstrate my problem because there is so much proprietary stuff mixed into my tables. I am hoping someone else is familiar with the problem I am having and can offer some solution.
    Thanks in advance for any assistance.

    Actually I do have this setup on the table and when sorting is toggled, the focus remains in the editor so it does not terminate.
    Any other possibilities?

  • How can one resize a cell editor when in use in a JTree?

    It is possible to resize, for example, a JTextArea cell editor while it is being used in a JTable by having a document listener check the preferred height and then changing the rowHeight of the table to fit that. This gives the nice effect of the table expanding and contracting in size as required while it is being edited.
    I would also like to this this for a Jtree. But one cannot reset the height of an individual JTree row, and although it can be set up to get the correct height when the editor or renderer is installed (via setRowHeight(0)), there does not seem to be a way to dynamically adjust this height while editing.
    This would be very nice to be able to do. (I would say it should be required of a good tree component that it allow this).
    Is there some way I am missing? It seems like there is no difficult constraint on the design of Jtree which should make this difficult in principle.

    You cannot download apps from another country's store unless you have an account in that country which means having a credit card that is tied to a physical address in that country.
    AFAIK, you cannot add more dictionaries to the collection that. Apple has provided. There is no way to add any plug ins, or enhancements to any of the built to in apps or iOS functions.

  • When I open an old pages doc in new pages 5.0 objects in table cells are removed. how can I stop this?

    When I open an old pages doc with new pages 5.0 - objects, specifically pictures, in table cells are removed. Is there a way I can stop this?

    nigel32,
    Gavin is right.  You are bound to lose images in tables of docs made in previous versions.  If you wish to continue using Pages 5.0 to edit docs from previous versions, you can try re-inserting your images using the following method:
    1.  Click on the cell you want to insert to.
    2.  Select CELL on the right contextual menu.
    4.  Click on FILL and select IMAGE FILL.
    5.  Click CHOOSE then select the image you need from Finder.
    6.  Tweak the appearance using the SCALE slider or drop down menu.

  • How to create a context menu in ALV table cell editor(Webdynpro abap )

    Hello Experts,
    I am having a problem in creating a context menu in a table cell editor in the ALV table output.I have assigned a 'lta' as the cell editor.But befor assigning the lta as cell editor I have assigned the menu to the lta.But when the view is rendered I can see the lta with the actioned assigned to it.But I cannot see the context menu.
    The code snippet below:
      "Create menu for each coloumn
      create OBJECT lo_menu_actions type CL_SALV_WD_VE_MENU EXPORTING
          id = 'MITM_ACTIONS'.
      lo_menu_actions->set_visible( value = abap_true ). 
      lo_menu_actions->set_visible_fieldname( value = 'ACTIONS' ).
      "ADd menu items
      CREATE OBJECT lo_menu_item_create type CL_SALV_WD_VE_MENU
      exporting
        id = 'MITM_CREATE_EXPRESSION'.
      lo_menu_item_create->set_visible( value = abap_true ).
      lo_menu_item_create->set_visible_fieldname( value = 'Create' ).
      "Add item 1
      lo_menu_actions->ADD_ITEM( VALUE = lo_menu_item_create ). 
      "  Set the cell editor for each column cell(link to an action)
      LOOP AT lt_node_dec_tab_cols INTO ls_node_dec_tab_cols .
        lv_column_name = ls_node_dec_tab_cols-object_name.
        lr_column = lr_column_settings->get_column( lv_column_name ).
       "Create 'lta' Ui item
        CREATE OBJECT lo_lta TYPE cl_salv_wd_uie_link_to_action.
        lo_lta->set_menu( value = lo_menu_actions ).
        lo_lta->set_text_fieldname( lv_column_name ).
        lr_column->set_cell_editor( lo_lta ).
        IF ls_node_dec_tab_cols-is_result EQ abap_true.
          lr_column->set_cell_design( value =
                      cl_wd_table_column=>e_cell_design-key_medium ).
        ENDIF.
      ENDLOOP.

    Hi Prakash,
    I have not come across this requirement till now to have context menu in a cell editor of alv.
    Unfortunately  the implementation of method SET_MENU of alv ui elements ( ex: cl_salv_wd_uie_text_view ) is not updating alv configurable table, instead it just stores in a global attribute as string. Hence has no effect on context menu.
    If your user is very particular about this requirement of having context menu in cell editor, you can go for a normal table. Because, normal table's cell editor has the property to set the menuID as we do it for other ui elements.
    Regards,
    Rama

Maybe you are looking for

  • Publishing Ical in weekly view with start time I want

    I have my Ical set up to start at 11am and end at 9pm. When I publish my calendar it still shows start time at 7am on weekly view. How do I publish my Ical with the start and end times I want? Thanks

  • How to get rid of: Would You Like To See Your Photos on a Map?

    Every single time I edit a photo in Aperture I get this annoying question: "Would you like to see your photos on a map?" Enable GPS tracking - yes or no. How can I get this pop-up screen permanently off of Aperture? Sometimes this causes Aperture to

  • How can i create an auto increment column

    Hello Everyone We are working on an EAM package which has an auto number facility but that is not meeting our requirement because some 10s and 100s of numbers keep on jumping based on the number of records the child table has.Means every record in my

  • Can't Build a PDF Portfolio

    The HELP function suggests building a PDF Portfolio, which would be helpful for me when doing serches on PDF documents.  But when I go to the File drop-down menu, no option appears for PDF portfolio, as the HELP instructions says there should occur. 

  • CONTAINS and CATSEARCH

    If I understand it correctly, to use contains(text_col, ...) or catsearch(text_col, ...) in a WHERE clause, the "text_col" column must first carry an index on it. Is this correct? Another thing, this source:"http://www.dba-oracle.com/oracle_tips_like