Change semanticColor of cell editor

Hi Experts,
I have a table and depending on the values of a particular field I want the color of the cell editor to change in one of the columns. How can I achieve that. The table has values populated at run time depending on the inputs from the user.
Regards,
Abdullah

hi abdhullah.......
       bind the cell design property of the column to an attribute of type string and pass number like '2' to it to change the colour at runtime.
---regards,
   alex b justin

Similar Messages

  • 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

  • Changing the event that starts JTree cell editor

    I've implemented a JTree that uses a custom cell renderer and editor. Everything is going well except for a look and feel issue. When I double click on a JTree entry or single click on a node that has already been selected, the cell editor starts immediately. This is way to generous, and I'm finding I'm often editing cells when I just want to navigate the tree.
    I'd much prefer to have the edit event be something harder to do like a right click or a triple left click. Is there a way to change the event that starts the JTree cell editor?

    DefaultCellEditor provides a method boolean isCellEditable(EventObject anEvent), by default it always returns true. Override that method in your cell editor to only return true if the event is a right click, or whatever you want.

  • Table UI element - dynamic cell editor change on runtime

    Hello,
    I have standard table UI element defined on one of the views as part of it's layout, two columns only - KEY and VALUE. Both defined as text cell editor by default. Content of the table is dynamic and different combination of keys and values are presented depending on the app context.
    Recently the need arised to (depending on the key value) change the cell editor type for single rows only, dynamically from text to link to action - and to register a triggable event for that with some logic behind (to open new window when link is clicked).
    Is it possible at all to have a column in Table UI element with different editor types set dynamically on runtime for different rows? Some cells then wolud still be presented as text, some would have a link to action in them.
    If possible can I ask for any hints on how to achieve that?
    I imagine that first I have to get somehow a reference to the UI element created when the view is triggered first time, then after I recieve values from backend but prior (or after?) binding it to the table context I would like to evaulate the keys and change cell editors accordingly. Then for changed editors (link to action) I would like to register triggable events (on action) which would call some custom methods for further processing. Please advice.
    Best regards,
    Marcin

    Hi,
       You can use the cell variants to display different cell editors in different rows.
       First in your table column where you want to display different cell editors insert two cell variants
       and fill the VARIANT KEY for each cell variant and insert textview under one cell variant and input field
       under another cell variant, and bind the text to be displayed to these cell editors, now take an extra
       attribute of type string in your node and bind it to the table column property SELECTED CELL VARIANT.
       Now depending on your requirement change this attribute to any of the VARIANT KEY defined for cell variants. 
    loop at itab into wa.
          if 'YOUR CONDITION'.
            wa-cellvar = 'VAR1'.                 "cellvar is the attribute which is bound to SELECTED CELL VARIANT
            else.                                          " of table column
              wa-cellvar = 'VAR2'.                 " VAR1 and VAr2 are the variant keys of cellvariants
              endif.
              modify itab from wa.
          endloop.
    Hope this solves your problem.

  • Dynamically changing dropdown options in JCombox cell editor

    Hi all,
    I have a JTable with one column with JComboBox renderer and i am using the cell editor for that column as new DefaultCellEditor(JComBoBox renderer class).
    My requirement is i want to change the dropdown options basing on another column value.
    So what i did is in the setValueAt(...) function i got the table column renderer and as send the new values in a object to the renderer and in the getTableCellRendererComponent method i am checking the row number and setting the dropdown options to the JComboxBox. This works fine and the JComboBox is showing the new dropdown options correctly but when i click on the JcomboxBox cell it is showing the old dropdown options.
    So my question is how can i change the values in the editor.
    I tried like this in my setValueAt(..) functioin in my JTable model
    ( (my custom class) ((DefaultCellEditor) table.getColumnModel.getColumn(int)).getComponent).add(NewObject)
    in the new object i am sending new dropdown values and row and column but it some how it is updating renderer but not editor. Please give me the solution
    Thanks in advance
    Sunil

    You can extend DefaultCellEditor the same way as you extend cell renderer.
    After that you can set it back to your table using table.setCellEditor() method.
    best regards
    Stas

  • How to change the colour of the table cell editor on some condition?

    Hi all,
    I have a requirment acco which i need to make the colour of the tableceleditor ias RED and font color white when the data in that is < 0.please tell me how is this possible and its urgent..
    regards
    Sharan

    If you are using release NW04 and have a TextView as table cell editor, you can do this:
    Add a calculated attribute "Color" of DDIC type "com.sap.ide.webdynpro.uielementdefinitions.TextViewSemanticColor" under the data source node of the table.
    Bind the "semanticColor" of the cell editor to this context attribute.
    Implement the get-method for the calc. attribute like this
    WDTextViewSemanticColor get<DataSourceNode>Color(I<DataSourceNode>Element element)
      return element.getValue() < 0 ? WDTextViewSemanticColor.NEGATIVE : WDTextViewSemanticColor.STANDARD;
    Armin

  • PLEASE HELP-JTable cell editor-change one cell, changes all cells of column

    for example i have 3 rows 4 columns, column 3 and 4 are dates. now if i change the date to a new value (eg for of column 3)
    for any row, and then i click on any other cell. All cell values ie all rows for that column are changed to that new value.
    ie it changed column 3 for all rows 1, 2 and 3 to that new value which i changed in only one cell of that column.
    PLEASE HELP me , tell me what change i make to the code to fix it ....
    this is my cell renderer for date
    class DateCellRenderer extends JbcDateTimeChooser implements TableCellRenderer {
      protected Border m_noFocusBorder;
      public DateCellRenderer() {
        super();
        setStylePattern(JbcDateTimeChooser.MEDIUM);
        m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
        setOpaque(true);
        setBorder(m_noFocusBorder);
      public Component getTableCellRendererComponent(JTable table,
       Object value, boolean isSelected, boolean hasFocus,
       int row, int column)
      if(value instanceof Date) {
          Date b = (Date)value;
          setDate(b);
        setFont(table.getFont());
        setBorder(hasFocus ? UIManager.getBorder(
          "Table.focusCellHighlightBorder") : m_noFocusBorder);
        return this;
    }I have this custom cell editor date
    class DateCellEditor extends AbstractCellEditor implements TableCellEditor {
      protected JbcDateTimeChooser editor;
      public DateCellEditor() {
        super();
        editor = new JbcDateTimeChooser();
        editor.setStylePattern(JbcDateTimeChooser.MEDIUM);
      public Object getCellEditorValue() {
        return editor.getDate();
      public Component getTableCellEditorComponent(JTable table,
       Object value, boolean isSelected, int row, int column)
        if(value instanceof Date) {
          editor.setDate((Date)value);
        return editor;
    }and this is how i defined in jtable
        lnnTableModel = new CellSiteLNNTableModel();
        lnnTable.setModel(lnnTableModel);
        lnnTableModel.addColumn("ABC");
        lnnTableModel.addColumn("DEF");
        lnnTableModel.addColumn("Date From");
        lnnTableModel.addColumn("Date To");
        for(int k = 0; k < lnnTableModel.getColumnCount(); k++) {
          TableColumn col = lnnTable.getColumn(lnnTableModel.getColumnName(k));
          TableCellRenderer renderer;
            DefaultTableCellRenderer textRenderer = new DefaultTableCellRenderer();
            renderer = textRenderer;
          TableCellEditor editor;
          JTextField textColumn = new JTextField();
          if((k == CellSiteLNN.DATE_FROM) || (k == CellSiteLNN.DATE_TO)) {
            editor = new DateCellEditor();  //  this is the cell editor
         renderer = new DateCellRenderer(); // this is the assigned cell renderer
          } else {
            editor = new DefaultCellEditor(textColumn);
          col.setCellRenderer(renderer);
          col.setCellEditor(editor);
        }

    table model is extended from AbstractTableModel
    and have these methods
    do you see anything wrong here.....
      public Object getValueAt(int row, int column) {
        Vector rowVector = (Vector)dataVector.elementAt(row);
        return rowVector.elementAt(column);
      public void setValueAt(Object aValue, int row, int column) {
        Vector rowVector = (Vector)dataVector.elementAt(row);
        rowVector.setElementAt(aValue, column);
        // generate notification
        fireTableChanged(new TableModelEvent(this, row, row, column));
      } // end method (setValueAt)

  • Using a JPanel as cell editor in JTable

    I have a composite component (JPanel that contains a JTextField and a
    JButton) that I would like to use as the a cell editor in a JTable.The JButton instantiates a UI editor component that I have designed. Example would be date editor for dates, tet editor for strings etc. This editor allows the user to select a date to populate the JTextField (the date may also be manually entered).
    I have no problem with the rendering of the component within the table.However, I would like for the JTextField embedded within the JPanel to receive focus and a visible caret, when using the tab key to navigate to the cell. After reading through some of the posts here , I was able to transfer the focus. But I dont see a visible caret. I am unable to edit. I have to click on the text box and then start typing. Its a great pain in the ass.
    I have a custom designed table and custom designed editor. Code is attached...
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))) {     
    if (selCol == 1) {
    isSelected= getCellEditor(selRow,selCol).stopCellEditing();
    targetRow = (selRow + 1) % rowCount;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    if (editCellAt(targetRow, 1, obj)) {
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    } else {
    getCellEditor(selRow, selCol).shouldSelectCell(obj);
    return super.processKeyBinding(ks,e,condition,pressed);
    </pre>
    Relevant code of my custom editor is below....
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    lastEditedRow = row;
    lastEditedCol = column;
    lastEditedTable = table;
    lastEditedValue = value;
    val = value;
    ((JTextField)editorComponent).
    setText(val == null ? "" : val.toString());
    setClickCountToStart(1);
    if (value instanceof CycCollectionChooserModel) {
    String collection = ((CycCollectionChooserModel)value).
    getCollection().cyclify();
    button.setVisible(EditorForCollectionMap.hasUIEditor(collection));
    button.setMargin (new Insets (1,1,1,1));
    button.setIconTextGap(0);
    buttonListener.model = (CycCollectionChooserModel)value;
    buttonListener.rowIndex = row;
    buttonListener.localTable = table;
    return panel;
    public boolean isCellEditable(EventObject evt) {
    if (evt instanceof MouseEvent) {
    int clickCount;
    clickCount = 1;
    return ((MouseEvent)evt).getClickCount() >= clickCount;
    return super.isCellEditable(evt);
    public boolean stopCellEditing() {   
    if (super.stopCellEditing()) {
    final int targetRow = (lastEditedRow+1)%lastEditedTable.getRowCount();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    lastEditedTable.changeSelection(targetRow, 1, false, false);
    lastEditedTable.getComponentAt(targetRow, 1).requestFocus();
    return true;
    return false;
    Does any one know why I am not able to see the caret? Any insights you have will be most welcome.
    Thanks in advance,
    Praveen.

    Almost solved the problem. Navigation through Tab key, up/ down arrow, Enter key works for text boxes. Navigation through Tab Key, Up/down arrow works for combo boxes. But for "Enter" key it doesnt. Changes in code ....
    (I have added a key listener to my editor class)
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0))) {     
    if (selCol == 1) {
    final int targetRow = (selRow + 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1))) {
    if (selCol == 1) {
    final int targetRow = (selRow - 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    return super.processKeyBinding(ks,e,condition,pressed);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    </pre>
    P.S : viravan, help me solve this problem and you will get the rest of the dukes LOL

  • List UIBB - Access to cell editor for a certain table line possible

    Hi,
    I am looking for a way to access the cell editor of the last table line as I want to mark it as a special - summary - line.
    I intend a similar approach like in WebDynrpo ABAP when accessing the node info and modifying the "CELL DESIGN" attribute like in the following code (copied from WD Comp WDR_TEST_TABLE, View CELL DESIGN, method FILL_CELL_DESIGNS) :
      data tab type IF_CELL_DESIGN=>Elements_Cell_Designs.
      data line type IF_CELL_DESIGN=>Element_Cell_Designs.
      data node_info type ref to if_wd_context_node_info.
      data attribute_info type wdr_context_attribute_info.
      data attr_value type WDR_CONTEXT_ATTR_VALUE.
      node_info = node->get_node_info( ).
      attribute_info = node_info->get_attribute( 'CELL_DESIGN' ).
      line-is_expanded = abap_true.
      line-is_leaf     = abap_false.
      line-key         = 'FIRST'.
      loop at attribute_info-value_set into attr_value.
        line-text = sy-tabix.
        concatenate 'Text #' line-text into line-text. "#EC NOTEXT
        line-cell_design = attr_value-value.
        insert line into table tab.
        line-is_leaf = abap_true.
        line-key = attr_value-value.
        line-parent_key = 'FIRST'.
      endloop.
      node->bind_table( tab ).
    I suspect the method IF_FPM_GUIBB_LISTGET_DATA (or IF_FPM_GUIBB_LISTGET_DEFINITION) of my feeder class to be the right access point.
    But unfortunately, I have not yet found out how to change the cell design for specific lines, only for whole columns.
    Can anyone give me a hint here?
    BTW: The "summary" line is not a sum of the lines above, but determined by backend logic, so not ALV-summary line for me.
    Kind Regards

    Hi,
    A short update for all interested:
    My current work around is to always set the lead selection to the summary line. It does in a kind "mark" that line as special as long as I cannot mark it using a different cell design.
    How do I assure this?
    I have implemented the following code in a redefinition of the method ADJUST_SELECTION:
    *- alter selection
      DATA:
       ls_size TYPE rstabix.
      "get index of summary line
      ls_size-tabix = mo_collection->size( ).
      "change only if there are any cash conc. proposals
      IF ls_size-tabix > 0.
        "do FPM selection
        CLEAR: ev_lead_index, et_selection.
        ev_lead_index = ls_size-tabix.
        APPEND ls_size TO et_selection.
        "do BOL selection
        mo_collection->if_bol_bo_col_multi_sel~unmark_all( ).
        mo_collection->if_bol_bo_col_multi_sel~mark( iv_index = ls_size-tabix ).
      ENDIF.
    The general downside is, that no other selection is possible!
    The selection is always reset to the summary line with each roundtrip.
    Waiting for a better solution...
    Kind Regards,
    Robert

  • How to use the cell editor in FICO reports for YTD

    HI experts,
    I am working with BI7.0, in the below report, i have displayed result based on user input.but how to calculate the YTD values. User will give the input like 072007, results will be display one year from 072007 to 062006 (one yearback) and one more column is YTD
    Report structure is :
         user input(single value): 072007
              AUG06....JAN07....JULY07....YTD
    KEYFIGURE-1        453      -
    777     -
       232       -
      777 (Only Jan07 value of Keyfigure-1)   
    KEYFIGURE-2        879      -
    233        -
    123       -
      ???? (only sum from Jan07 to July07)
    KEYFIGURE-3        212            -
    879      -
    989                -
    KEYFIGURE-4        234            -
    656      -
    788                   -
    KEYFIGURE-5        345            -
    878      -
    878                 -
    KEYFIGURE-6        767            -
    767       -
    323                 -
    KEYFIGURE-7        879            -
    878     -
    999                -
    999 (Only last value of keyfigure-7 (July07)
    in the above report, total 7 keyfigures so 7rows of YTD column
    1) in the first YTD column, how will display only one value (keyfigure-1) of Jan07?
    2) in the last YTD Column, how will display only one value (keyfigure-7) of July07?
    3) from 2 to 6 columns of YTD, how will display the sum from Jan07 to July07?
    Note: months will be changed based on user input(single Value)
    how can use cell editor for above the senior.
    if any option is availabel please let me know
    Thanks
    kishore

    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

  • 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

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a 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

  • Requirement in Cell Editor

    Hello Guys,
    I am having one requirement in Cell Editor. My report is static report. I mean all the columns and rows already decided. My infoprovider is contain only one characteristics and two key figures.
    My characteristic is Circle and the Key Figures are Minutes of Usage and Revenue. I have to shwo the report like this:
    Circle  | Minutes of Usaage |Revenue|Cost Center|Profit Center
    Tamil Nadu  |    100             |    10000 | 201300A    | 201300       
    Karnataka       |      50            |     5000 | 201001A    | 201001             
    I dont have details of Cost Center and Profit Center. All are hard coded values. No changes on that. So directly we can maintain like this values.
    Remember costcenter and profit center having characters. Otherwise in the cell definition we can create a formula and put this value.
    Any body having idea on this ??????
    If this will not work, i have to go with one more info provider and tranfer all the data with extra columns..... I dont want to do that........
    Regards,
    Vivek V

    Hi Vivek,
    Just a thought:
    Since you want to display Char - KF - Char - I dont know how that would be possible - So Can we use Profit/Cost centre ( they are hard coded already)  as KF..using replacement path/formula variable..so that it is Char - KF - KF...
    And then there should not be possible ??
    Dont knw if i m entirely on wrong path - but you can try - let me knw if it works..
    when you say hard coded - hard coded where?? Can you get value soem where from master data??
    Also Cell Editor makes query performance pathetic
    Hope it helps
    Gaurav
    Message was edited by:
            Gaurav

  • 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

Maybe you are looking for