Differrent CELL Editors and Renderers in a Column

Is it possible to have different cell editors and renderers within a single column? I would like to have text, CheckBox and ComboBox on different rows and within the same column.
If yes, pls point me to somthing that describes this process.

One thing that is often overlooked,due to a poor naming choice by Sun, is that a Renderer is not forced to return this as the component that will ultimately paint the cell: the only job of a cell renderer (as per the interface TableCellRenderer ) is to provide a component to do the painting. It is free to re-used the same component as much as possible (as a memory optimization), but it can also return either JComponent out of a set of 3.
For example:
public class MyRenderer implements TableCellRenderer {
    private JLabel componentThatRendersFoos;
    private JLabel componentThatRendersBars;
    public void getTableCellRendererComponent(...) {
        if (whatever criterion that identifies the cell as a foo) {
            componentThatRendersFoos.setBackground(...);
            return componentThatRendersFoos;
        else if (whatever criterion that identifies the cell as a bar) {
            componentThatRendersBars.setBackground(...);
            return componentThatRendersBars;
    }And similarly for editors.
This has the advantage to enable to configure the renderer without havingto subclass JTable.
Edited by: jduprez on Jan 20, 2011 10:51 PM
Here is a reference to a discussion about the mixed concepts in renderers: {message:id=9161690}

Similar Messages

  • Cell editors  and renderers confusion

    HI i went thru some code recently but cud not understand why he is doin that , here is the step
    creates editor e1
    creates renderer r1
    editor e1 has renderer r1 as member var ie we can refer it as e1.r1
    in the getTableCellEditorComponent()of e1 method he is returning renderer r1.
    table.setCellRenderer(e1)
    i am just confused , is ther any advantage of this approach?
    am i clear, 7

    I can't see any advantage and find this approach rather confusing.
    In my opinion, renderer and editor should be separated from each other.
    G.

  • Is it OK to re-use 1 instance of editors and renderers?

    Hi,
    The simple version of the question, is can I make 1 instance of my custom cell editor and cell renderer classes and safely use it in all my JTable instances?
    For example, I have a DateRenderer class, and instantiate it in a static member, and use it in all Date columns and tables, many of which will be instatiated at one time. If a column needs a non-default format, then I guess I'd create a special instance for it, other wise it would use the default instance.
    It seems to be OK so far, but but my program hasn't received any serious usage yet.
    As to why, I'm thinking this way, I've been messing around with CellEditors and renderers and despite wanting to use default functionality whenver possible, I find that I'm using custom versions for every situation... so if possible, I'd like to keep the number of instances to a minimum.
    Regards
    Iain

    OK, I see what you mean.
    Stop cell editing on focus lost isn't the default behaviour, but I've had to use it anyway (it seems to make sense).
    The reason I asked is that, to get the behaviour that I want, it looks like I'll have to have my custom renderers and editors on every column of every table so I'd like to avoid unneccessary instantiation.
    I'm aiming for a system where:
    - 1 click selects the row (default behaviour),
    - 2 clicks starts editing the cell (also default),
    - but tabbing or pressing enter after editing a cell keeps you in editing mode.
    I don't suppose that many people here have had experience with this, but entering Japanese (and presumably other non ascii type character sets) using MS's IME doesn't work very well with the standard JTable behaviour. If you don't double click, the entered japanese text appears in a little IME window somewhere on the screen (no neccessarily near the editing cell) and just gets lost when you press enter. You have to double click every time, and I can't see the users accepting that.
    I'll be investigating this over tme, and hopefully will be able to get it working smoothly.
    Thanks,
    Iain

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

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • How to use Radiobutton Cell Editor in Table using Master Column

    Hi Guys,
    I have a Table that uses a Master Column.  I need to have a field that uses a Radio Button type cell editor.  A user should only be ably to select ONE row via the Radio Button at a time.
    I have done all this but I only seem to be able to select multiple radio buttons instead of only one.  It is like the radio buttons do not get "regognised" as a group.  Could you please advise as I probably set the "keyToSelect" and "selectedKey" properties incorrectly.
    tks
    Christiaan

    I think the following should work:
    Context:
    Rows (node,c=0:n)
    --- rowIndex (integer)
    selectedRowIndex (integer)
    Bind the "selectedKey" property of the radio button (cell editor) to attribute "selectedRowIndex" (outside table data source node) and bind "keyToSelect" to attribute "Rows.rowIndex". Make sure that the "rowIndex" attribute will contain the index of the node element in node "Rows".
    Armin

  • JTable cell editor and row selection

    I have a JTable with 8 columns and the last column is editable and has a custom table cell editor. The user can edit cells in that column or select a row and use buttons above the table to do such things as delete the row. So far so good. However if the user selects a row by clicking on a cell in the editable column and tries to delete the last row(for example) the row disappears except for the cell in the last column which is left hanging with the cursor in it.
    I do a table.clearSelection(). Do I need to set the focus elsewhere in the table?
    Help! and thanks.

    Before you delete the row, cancel the in-process editing:
    if( _table.isEditing() ) {
        _table.getCellEditor().cancelCellEditing();
    // Delete the row in the model

  • Cell Editor and Structures

    Hi,
    I have a requirement to use a field in a previous row of a query result in a calculation in the current row.
    My first question is, is this possible ? or does anybosy have any suggestions for a workaround
    In trying to determine if it is possible I was going to investigate the use of the Cell Editor. However this requires that I have 2 structures in my query. I have therefore created a reuseable structure for the key figures, but the structure for the characteristics does not display the characteristics selected in either the query definition or the query results. Because of this I cannot proceed with the Cell editor.
    Can any one help with defining characteristic structures ?
    Can anybody recommend a good book for BW query definition/tips/tricks ?

    Hi Bhanu.
    I am creating the structure as you say by right clicking
    on the 'rows' heading and creating a new structure.
    Then I am right clicking on the new structure and dragging and dropping the required characteristics into the structure. eg Plant and Material. I am changing the description eg 'MM Data'  Then after closing the dialog I do 'save as' to save the structure as reusable. All appears to work fine. BUT I was expecting the rows of the query to then contain Plant and Material, instead they have a heading of  'MM data' with no values for either Plant or Material showing.
    I am therefore not sure that I have grasped the point of reusable structures. Having said that, if I create one in exactly the same way for key figures then it does work  in the way I was expecting. ie The key figures contained in the structure are visible in the report.
    The actual rqmt I have is to be able to multiply 2 key figures together from separate rows in the query results. i don't think its possible, but was trying to exhaust all avenues of thought before going back to the users with alternatives. 
    Rgds
    Simon

  • Good Explanations for Editors and Renderers

    Hi
    I need to write some custom renderers and editors for both trees and tables for a project I'm working on. I've looked at the Java Swing Tutorial, but it doesn't really explain how they are coded or how they work etc.
    I've search the web and all the examples I've found don't explain how they work etc (lack of comments etc).
    My needs are to use both panels with lots of objects and thing like Check boxes.
    from the stuff I've tried doing, I've been getting some very strange results and bits disappearing etc. I'll try to put together a simple example and post it.
    Thanks for your help.
    Nick.

    Hi
    Apologies for the late response.
    That link was most useful.
    I tried searching for one relating to trees as opposed to tables, but couldn't find one.
    Is there any major differences between renderers for trees and tables or are they fundamentally the same.
    Thanks.
    Nick.

  • Tree Editors and Renderers

    What I am currently trying to implement is a tree editor renderer that displays label and a text field next to a tree node.
    The label contains text describing the contents of the text field to the right.
    The requirement is that the user can click in the textfield area and type a new value, which when they press return is accepted.
    My problem is that in order to detect single clicks in the textfield area to enable the editor for that tree node, I am implementing an Immediate Editor along the lines in the Geary Swing Book.
    However, a method to calculate the correct offset is not working:
    PMSPropertyBrowserTreeCellRenderer.getPropertyValueTextFieldOffset fails to calculate the correct value as two things appear to fail
    1. the "lastRow" member of the Tree is not the last component selected
    2. the call to obtain the Graphics class from the renderer's panel always returns null
    From Immediate Editor
    * Provides the means to edit a cell immediately with a mouse click
    * @param event
    * @return true if the event is of the right type
    protected boolean canEditImmediately(EventObject event)
    boolean retval = false;
    if (event instanceof MouseEvent)
    MouseEvent me = (MouseEvent)event;
    retval = inTextFieldHitRegion(me);
    return retval;
    * Should determine if the pointer is in the region of the property text field
    * @param me
    * @return id the mouse pointer is in the text field
    private boolean inTextFieldHitRegion(MouseEvent me)
    // obtain the place in the tree where this mouse event came from
    TreePath path = tree.getPathForLocation(me.getX(), me.getY());
    PMSPropertyBrowserTreeNode node =
    (PMSPropertyBrowserTreeNode)path.getLastPathComponent();
    boolean retval = false;
    // if the node is a leaf
    if (node.isLeaf())
    // determine if mouse point is in the JTextField part of the renderer component
    Rectangle bounds = tree.getRowBounds(this.lastRow);
    Dimension textFieldOffset = renderer.getPropertyValueTextFieldOffset();
    bounds.translate(
    offset + textFieldOffset.width,
    textFieldOffset.height);
    retval = bounds.contains(me.getPoint());
    return retval;
    public boolean shouldSelectCell(EventObject event)
    GUILog.log.writeLog(
    GUILog.logTypes.ADMINISTRATIVE_EVENT,
    "shouldSelectCell called");
    boolean retval = false;
    if (event instanceof MouseEvent)
    MouseEvent me = (MouseEvent)event;
    TreePath path = tree.getPathForLocation(me.getX(), me.getY());
    PMSPropertyBrowserTreeNode node =
    (PMSPropertyBrowserTreeNode)path.getLastPathComponent();
    boolean inField = !inTextFieldHitRegion(me);
    retval = node.isLeaf() || !inTextFieldHitRegion(me);
    return retval;
    ... end from ImmediateEditor
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JTree;
    import javax.swing.tree.*;
    import java.awt.Component;
    public class PMSPropertyBrowserTreeCellRenderer extends DefaultTreeCellRenderer
    private JPanel propertyPanel = new JPanel();
    private JLabel propertyValueLabel = new JLabel();
    protected JTextField propertyValueTextField = new JTextField();
    private Component spacer = Box.createHorizontalStrut(5);
    public PMSPropertyBrowserTreeCellRenderer()
    super();
    propertyPanel.setBackground(UIManager.getColor("Tree.textBackground"));
    setOpaque(false);
    propertyValueTextField.setOpaque(false);
    propertyValueTextField.setBorder( BorderFactory.createLoweredBevelBorder());
    propertyValueTextField.setText("<empty>");
    propertyPanel.setOpaque(false);
    propertyPanel.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
    propertyPanel.add(this);
    propertyPanel.add(spacer);
    propertyPanel.add(propertyValueTextField);
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
    * Gives the offset for the tree node as far as the text component
    * Currently the graphics reference returns null.
    * @return an offset into the text field component
    public Dimension getPropertyValueTextFieldOffset()
    Graphics g = propertyPanel.getGraphics();
    int offset = 0;
    if (g != null)
    try
    FontMetrics fm = g.getFontMetrics();
    offset =
    fm.stringWidth(getText()+spacer.getPreferredSize().width);
    catch (Exception ex)
    // nothing happens if we get an exception
    finally
    g.dispose();
    } // end if
    return new Dimension(offset,0);
    } // end method

    JTree has a setRowHeight(int rowHeight) method. "If
    the specified value is less than or equal to zero the current cell
    renderer is queried for each row's height."
    (Say if you're reposting this in the Swing forum.)

  • JTable custom cell renderer and editor breaks row sorting

    Hello Forum,
    I have a JTable on which I set setAutoCreateRowSorter(true); I then hook up a custom cell editor and renderer for the Date class.
    this.tblLeden.setDefaultRenderer(Date.class, new DateCellEditor());
    this.tblLeden.setDefaultEditor(Date.class, new DateCellEditor());
    The sorting for that particular row then breaks, it works fine for every other row. How do I fix this? Just directions where to look would be great too.
    Here is my code for the renderer/editor:
    (btw this is probably not the best way to do this so any suggestions for optimizing are great too)
    import java.awt.Component;
    import java.util.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor extends JDateChooser implements TableCellRenderer, TableCellEditor
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return null;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
    }

    This seems to work:
    import java.awt.Component;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.sql.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor implements TableCellRenderer, TableCellEditor, PropertyChangeListener
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      private Date storedValue = null;
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return this.storedValue;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
      @Override
      public final void propertyChange(final PropertyChangeEvent arg0)
        if (((JDateChooser) arg0.getSource()).getDate() == null)
          return;
        this.storedValue = new Date(((JDateChooser) arg0.getSource()).getDate().getTime());
        ChangeEvent event = new ChangeEvent(arg0.getSource());
        for (int i = 0; i < this.listeners.size(); i++)
          this.listeners.elementAt(i).editingStopped(event);
    }

  • Set Cell Editor Image and Caption to Rows in ALV

    Hi,
    i want to set cell editor different elements to a column of alv. Please follow the link of screenshot.
    [www.menstasarim.com/mmesut/state1.JPG]
    Can somebody help me pls?
    Thanks.

    yes it is possible, basically you have to change the cell desing (for background colors) and insert the icons based on some condition.
    lr_col = lr_config_model->if_salv_wd_column_settings~get_column( 'CARRID' ).
      lr_col->SET_CELL_DESIGN( '02' ) .
    this will change the background color, and you have to call another method to insert the icon.

  • How to combine a JFormattedTextField and a button in a cell editor

    Outside of a table we have a JFormattedTextField into which the user types an amount. Next to the field is a calculator button. If the user clicks the calculator button, we open a calculator, enable the user to type his calculations, and when he presses OK, we copy the result to the field.
    Now we want the field to be a cell editor and to display the button next to the field (in the table cell). How can we do this? Do I have to make the button a separate column, or can I combine the field and button in 1 column?
    Thanks,
    Eli

    Hi,
    Try like this:
    DATA: BEGIN OF line,
          col1 TYPE i,
          col2 TYPE i,
          END OF line.
    DATA itab LIKE STANDARD TABLE OF line.
    data ch(1) type c.
    PERFORM fill CHANGING itab.
    PERFORM out USING itab.
    FORM fill CHANGING f_itab LIKE itab.
      DATA f_fill LIKE LINE OF f_itab.
      DO 3 TIMES.
        f_fill-col1 = sy-index.
        f_fill-col2 = sy-index ** 2.
        APPEND f_fill TO f_itab.
      ENDDO.
    ENDFORM.                    "FILL
    FORM out USING value(f_itab) LIKE itab.
      DATA f_fill LIKE LINE OF f_itab.
    write ch as checkbox.
      LOOP AT f_itab INTO f_fill.
        WRITE:/ f_fill-col1, f_fill-col2.
      ENDLOOP.
    Regards,
    Bhaskar
    ENDFORM.                    "OUT

  • Tab transversal while using JTextArea as a JTable cell editor..

    I'm working on a project that will use a JTable with a JTextArea cell editor to create a chart for classroom scheduling. Searching on Google, I found a way to use a JTextArea as a cell editor and render the cell properly. However, when editing a cell, pressing the Tab key inserts a tab, rather than leaving the cell and going to the next one, as happens with just a regular JTable. In fact, none of the keyboard shortcuts that work on a JTable work once the JTextArea cell editor is used. Does anyone know of any way to resolve this? Below is some code I'm using to create a sample GUI, just to verify that I can do this. Another question is would it be easier to use a bunch of JLabels and JTextAreas, remove the padding from those JTextAreas, and try to allow for Tab transversals between stand-alone JTextAreas, rather than JTextAreas as JTable cell editors?
    Thanks!
    package edu.elon.table;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GUI
         private JFrame frame;
         private String[] columnNames = {"Classroom", "8:00-9:10", "9:25-10:35",
              "10:50-12:00", "12:15-1:25", "1:40-2:50", "1:40-3:20 (MW)",
              "3:35-5:15 (MW)", "5:30-7:10 (MW)"};
         private Object[][] data = {columnNames,
              {"ALAM 201 (42)\nENG 110 LAB", "", "", "", "", "", "", "", ""},
              {"ALAM 202 (42)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 203 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 205 (40)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 206 (39)\nSINK, TV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 207 (40+)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 214 (38)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 215 (42)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 216 (42)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 301 (40)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 302 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 304 (35)\nFRENCH", "", "", "", "", "", "", "", ""},
              {"ALAM 314 (30)\nDP, PSY, COMPUTER ASSISTED", "", "", "", "", "", "",
              {"ALAM 315 (40)\nPC LAB, DP/DVD", "", "", "", "", "", "", "", ""}};
         private JTable table;
         public GUI()
              frame = new JFrame();
              table = new JTable(data, columnNames);
              table.setRowHeight(table.getRowHeight()*2);
              TableColumnModel cModel = table.getColumnModel();
              TextAreaRenderer renderer = new TextAreaRenderer();
              TextAreaEditor editor = new TextAreaEditor();
              for (int i = 0; i < cModel.getColumnCount(); i++)
                   cModel.getColumn(i).setCellRenderer(renderer);
                   cModel.getColumn(i).setCellEditor(editor);
              frame.setLayout(new GridLayout(1,0));
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
    public static void main (String[] args)
    GUI gui = new gui();
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaRenderer extends JTextArea
    implements TableCellRenderer {
    private final DefaultTableCellRenderer adaptee =
    new DefaultTableCellRenderer();
    /** map from table to map of rows to map of column heights */
    private final Map cellSizes = new HashMap();
    public TextAreaRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    public Component getTableCellRendererComponent(//
    JTable table, Object obj, boolean isSelected,
    boolean hasFocus, int row, int column) {
    // set the colours, etc. using the standard for that platform
    adaptee.getTableCellRendererComponent(table, obj,
    isSelected, hasFocus, row, column);
    setForeground(adaptee.getForeground());
    setBackground(adaptee.getBackground());
    setBorder(adaptee.getBorder());
    setFont(adaptee.getFont());
    setText(adaptee.getText());
    // This line was very important to get it working with JDK1.4
    TableColumnModel columnModel = table.getColumnModel();
    setSize(columnModel.getColumn(column).getWidth(), 100000);
    int height_wanted = (int) getPreferredSize().getHeight();
    addSize(table, row, column, height_wanted);
    height_wanted = findTotalMaximumRowSize(table, row);
    if (height_wanted != table.getRowHeight(row)) {
    table.setRowHeight(row, height_wanted);
    return this;
    private void addSize(JTable table, int row, int column,
    int height) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) {
    cellSizes.put(table, rows = new HashMap());
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) {
    rows.put(new Integer(row), rowheights = new HashMap());
    rowheights.put(new Integer(column), new Integer(height));
    * Look through all columns and get the renderer. If it is
    * also a TextAreaRenderer, we look at the maximum height in
    * its hash table for this row.
    private int findTotalMaximumRowSize(JTable table, int row) {
    int maximum_height = 0;
    Enumeration columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
    TableColumn tc = (TableColumn) columns.nextElement();
    TableCellRenderer cellRenderer = tc.getCellRenderer();
    if (cellRenderer instanceof TextAreaRenderer) {
    TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
    maximum_height = Math.max(maximum_height,
    tar.findMaximumRowSize(table, row));
    return maximum_height;
    private int findMaximumRowSize(JTable table, int row) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) return 0;
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) return 0;
    int maximum_height = 0;
    for (Iterator it = rowheights.entrySet().iterator();
    it.hasNext();) {
    Map.Entry entry = (Map.Entry) it.next();
    int cellHeight = ((Integer) entry.getValue()).intValue();
    maximum_height = Math.max(maximum_height, cellHeight);
    return maximum_height;
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaEditor extends DefaultCellEditor
    public TextAreaEditor() {
         super(new JTextField());
    final JTextArea textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(null);
    editorComponent = scrollPane;
    delegate = new DefaultCellEditor.EditorDelegate() {
    public void setValue(Object value)
    textArea.setText((value != null) ? value.toString() : "");
    public Object getCellEditorValue()
    return textArea.getText();
    }

    Using the KeyEvent manager and playing around with the JTextArea, I was able to get a JTable using JTextAreas as the cell editors that worked very close to the way the regular JTable works. You have to hit Tab twice to shift focus to another cell, or hit Tab once and then an arrow key. Also, Alt-Enter will allow you to enter a cell for editing. All of the changes were made to the TextAreaEditor class, which should now read as follows:
    class TextAreaEditor extends DefaultCellEditor implements KeyListener
         private int lastKeyCode;
         public TextAreaEditor(final JTable table) {
              super(new JTextField());
              lastKeyCode = KeyEvent.CTRL_DOWN_MASK;
              final JTextArea textArea = new JTextArea();
              textArea.setWrapStyleWord(true);
              textArea.setLineWrap(true);
              textArea.addKeyListener(this);
              textArea.setFocusable(true);
              textArea.setFocusAccelerator((char) KeyEvent.VK_ENTER);
              JScrollPane scrollPane = new JScrollPane(textArea);
              scrollPane.setBorder(null);
              scrollPane.setFocusable(false);
              editorComponent = scrollPane;
              delegate = new DefaultCellEditor.EditorDelegate() {
                   public void setValue(Object value) {
                        textArea.setText((value != null) ? value.toString() : "");
                   public Object getCellEditorValue() {
                        return textArea.getText();
         public void keyTyped(KeyEvent ke)
              // TODO Auto-generated method stub
         public void keyPressed(KeyEvent ke)
              if (ke.getKeyCode() == KeyEvent.VK_TAB)
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusNextComponent();
                   return;
              if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.isShiftDown())
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusPreviousComponent();
                   return;
              if ((lastKeyCode == KeyEvent.CTRL_DOWN_MASK) &&
                        (ke.getKeyCode() == KeyEvent.VK_ENTER))
                   ke.consume();
                   editorComponent.requestFocus();
              else
                   lastKeyCode = ke.getKeyCode();
         public void keyReleased(KeyEvent ke)
              // TODO Auto-generated method stub
         }

  • Problem with Cell Editor

    Hi,
    I have a table and one of the columns take a decimal value....for this I have a custom cell editor and a renderer.
    But once I try to enter some value into that field and then resize/drag the column headers, the value entered is getting reset to the old value.
    So I added a mouse listener on the header and when mouse presses, I am doing a stopCellEditing(). This is working, but the same problem is seen when the dialog containing this table is resized i.e if I enter some value in that column and then resize the dialog containing this table..the entered value is getting reset to the older value.
    Can somebody suggest me on this. I also tried to add focus listener to that decimalTextFiedcomponent and upon focus lost, I am calling stopCellEditor..but this is not working...
    Thanks
    scsc

    When changing the value in the cell, do you call table.setValueAt( ...) or you call table.getModel().setValueAt(...). (They ought to be the same though)
    However, this is important cause you just need to make sure the new value gets to the TableModel else on repaint the table will display value in the model, no the new one in the view. Also, check if you are overriding the new set by replacing it from a database or some other storage point

Maybe you are looking for

  • Finder keeps crashing (and restarting)

    I recently installed StuffIt 11 and Toast 8 around pretty much the same time. Ever since, I find that Finder keeps crashing whenever I am trying to do something using the right click context menu (i.e. move to trash or open with etc) I had a look at

  • Firefox 21.0 android will not display websites but will when highlighted then searched

    on my tablet android 4.0.4 when I load a website, the address bar shows the site has finished loading but the site is empty. if I then touch and highlight the address then push search, the page displays immediately. any clues guys?

  • Restiction of Production Order Operation Confirmation

    Dear Friends, I need to restrict Production Order Confirmation among Production & Quality Control users i.e. production order contains both Production as well as Quality Inspection operations. I want to put restriction such that Production people sho

  • AVI with DIVX compression

    Hi, Is it possible to get an AVI with DIVX compression out of Premiere or Media Encoder (CS6)? I have a client who's 'in house' screen system requires this format. Thanks

  • Supress a window in script layout

    While modifying the standard scripts, how can we  comment or suppress a window in scripts so that it will not appear in the output, instead of actually deleting the window from the layout. Thanks & Regards, Saroja.