Change color in a cell in JTable

Hi, i need to Change color in a cell when this have the focus in a JTable.
Thanks

Override the prepareRenderer(...) method. Something like this:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

Similar Messages

  • How to change the Background color of a cell in JTable

    hi!
    Actually i want to change the background color of few cells in JTable
    is there any method to make this change in JTable ?
    and also is it possible to have 5 rows with single column and 5 rows with 3 columns in a single JTable

    i want to change the background color of few cells in JTableDepending on your requirements for the coloring of cells it may be easier to override the prepareRenderer() method of JTable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Change the background color of a cell in JTable

    Hi all,
    How can I change the background color of individual cell in JTable. I need to construct my own TableCellRenderer or not? I'm now using the DefaultTableCellRenderer now.
    Thx

    You could create your own renderer or you could try something like:
    table = new JTable(model)
         public TableCellRenderer getCellRenderer(int row, int column)
              DefaultTableCellRenderer tcr =
               (DefaultTableCellRenderer)super.getCellRenderer(row, column);
              if (row == 1 && column == 1)
                   tcr.setBackground(Color.green);
              else
                   tcr.setBackground(Color.red);
              return tcr;
    };

  • Set color of specific cells in JTable.

    I have a JTable where I want to set the color for specific cells. Is this possible to do, and if so, how?

    Well, one way is to create a custom renderer that know the background color of each cell in the table. The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer]How to Use Table has an example you might be able to build on.
    Or, this posting may give you another approach. The key to both solutions is to somehow specify the color for every cell:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • How to change color of cl_gui_alv_grid - cell ?

    Hi,
    i´m using cl_gui_alv_grid to display a table. In the table are colored cells.
      gs_layout-ctab_fname = 'COLINFO'.
          clear lcl_color.
          lcl_color-fname = 'DELIV_DATE_AB'.
          lcl_color-color-col = cl_gui_resources=>list_col_negative.
          lcl_color-color-int = 0.
          lcl_color-color-inv = 0.
          append lcl_color.
        wa_output-colinfo[] = lcl_color[].
        append wa_output to it_output.
    call method grid1->set_table_for_first_display
         exporting
    *    I_BYPASSING_BUFFER            =
    *    I_BUFFER_ACTIVE               =
    *    I_CONSISTENCY_CHECK           =
    *    I_STRUCTURE_NAME              =
         is_variant                    = gs_variant
         i_save                        = 'U'
    *    I_DEFAULT                     = 'X'
           is_layout                     = gs_layout
    *    IS_PRINT                      =
    *    IT_SPECIAL_GROUPS             =
         it_toolbar_excluding          = it_excluding
    *    IT_HYPERLINK                  =
    *    IT_ALV_GRAPHICS               =
    *    IT_EXCEPT_QINFO               =
        changing
          it_outtab                     = it_output
         it_fieldcatalog               = gt_fieldcat[]
    *    IT_SORT                       =
    *    IT_FILTER                     =
         exceptions
           invalid_parameter_combination = 1
           program_error                 = 2
           too_many_lines                = 3
           others                        = 4.
    That all works fine!
    Now i want to change the color of the colored cell. I changed the table wa_output-colinfo in this way:
    read table wa_output-colinfo into lcl_color
                with key fname = 'DELIV_DATE_AB'.
              if sy-subrc = 0.
                clear lcl_color-color-col.
                lcl_color-color-int = 0.
                lcl_color-color-inv = 0.
                modify wa_output-colinfo from lcl_color index sy-tabix.
              endif.
    After that i call:
    ls_stable-row = 'X'.
    ls_stable-col = 'X'.
            call method grid1->refresh_table_display
               exporting
                 is_stable      = ls_stable
               exceptions
                 finished       = 1
                 others         = 2.
    But nothing happens with the colored cell!
    Any ideas?
    thanks&regards
    Dirk

    Hello Dirk
    As I said the problem is the time point when you call the REFRESH_TABLE_DISPLAY method.
    Please note that after handling an event usually PAI of the dynpro is NOT pass and therefore the list is not refreshed.
    The following sample report shows how to solve this problem:
    *& Report  ZUS_SDN_ALV_EDITABLE_1D
    * Flow logic of screen '100' (no elements, ok-code => gd_okcode ):
    **PROCESS BEFORE OUTPUT.
    **  MODULE STATUS_0100.
    **PROCESS AFTER INPUT.
    **  MODULE USER_COMMAND_0100.
    REPORT  zus_sdn_alv_editable_1d.
    TYPE-POOLS: abap.
    CONSTANTS:
      gc_tabname       TYPE tabname  VALUE 'KNB1'.
    TYPES: BEGIN OF ty_s_outtab.
    INCLUDE TYPE knb1.
    TYPES: cellcolor  TYPE lvc_t_scol.
    TYPES: END OF ty_s_outtab.
    TYPES: ty_t_outtab    TYPE STANDARD TABLE OF ty_s_outtab
                          WITH DEFAULT KEY.
    DATA:
      gd_okcode        TYPE ui_func,
      gt_fcat          TYPE lvc_t_fcat,
      gs_layout        TYPE lvc_s_layo,
      gs_variant       TYPE disvariant,
      go_docking       TYPE REF TO cl_gui_docking_container,
      go_grid          TYPE REF TO cl_gui_alv_grid.
    DATA:
      gs_outtab        TYPE ty_s_outtab,
      gt_outtab        TYPE ty_t_outtab.
    " Set new ok code in event handler: 'X' = yes, ELSE = no
    PARAMETER:
      p_newokc         AS CHECKBOX  DEFAULT ' '.
    *       CLASS lcl_eventhandler DEFINITION
    CLASS lcl_eventhandler DEFINITION.
      PUBLIC SECTION.
        CLASS-METHODS:
          handle_data_changed FOR EVENT data_changed OF cl_gui_alv_grid
            IMPORTING
              er_data_changed
              e_onf4
              e_onf4_before
              e_onf4_after
              e_ucomm
              sender.
    ENDCLASS.                    "lcl_eventhandler DEFINITION
    *       CLASS lcl_eventhandler IMPLEMENTATION
    CLASS lcl_eventhandler IMPLEMENTATION.
      METHOD handle_data_changed.
    *   define local data
        DATA: ld_answer(1)  TYPE c.
        check ( p_newokc = abap_true ).
        " Triggers PAI -> required for list refresh
        CALL METHOD cl_gui_cfw=>set_new_ok_code
          EXPORTING
            new_code = 'REFRESH'
    *        IMPORTING
    *          rc       =
      ENDMETHOD.                    "handle_data_changed
    ENDCLASS.                    "lcl_eventhandler IMPLEMENTATION
    START-OF-SELECTION.
      SELECT * FROM  (gc_tabname)
        INTO CORRESPONDING FIELDS OF TABLE gt_outtab UP TO 99 ROWS.
      PERFORM colour_cells.
    * Create docking container
      CREATE OBJECT go_docking
        EXPORTING
          parent = cl_gui_container=>screen0
          ratio  = 90
        EXCEPTIONS
          OTHERS = 6.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * Create ALV grid
      CREATE OBJECT go_grid
        EXPORTING
          i_parent = go_docking
        EXCEPTIONS
          OTHERS   = 5.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      SET HANDLER:
        lcl_eventhandler=>handle_data_changed FOR go_grid.
      " Triggers event DATA_CHANGED by pushing ENTER
      CALL METHOD go_grid->register_edit_event
        EXPORTING
          i_event_id = cl_gui_alv_grid=>mc_evt_enter
        EXCEPTIONS
          error      = 1
          OTHERS     = 2.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * Build fieldcatalog and set hotspot for field KUNNR
      PERFORM build_fieldcatalog.
      PERFORM set_layout_and_variant.
    * Display data
      CALL METHOD go_grid->set_table_for_first_display
        EXPORTING
          is_layout       = gs_layout
          is_variant      = gs_variant
          i_save          = 'A'
        CHANGING
          it_outtab       = gt_outtab
          it_fieldcatalog = gt_fcat
        EXCEPTIONS
          OTHERS          = 4.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * NOTE:
    * Documenation of I_SAVE ("An Easy Reference for ALV Grid Control")
    *I_SAVE
    *Determines the options available to the user for saving a layout:
    *? 'X': global saving only
    *? 'U': user-specific saving only
    *? 'A': corresponds to 'X' and 'U'
    *? SPACE: no saving
    * Link the docking container to the target dynpro
      CALL METHOD go_docking->link
        EXPORTING
          repid                       = syst-repid
          dynnr                       = '0100'
    *      CONTAINER                   =
        EXCEPTIONS
          OTHERS                      = 4.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * ok-code field = GD_OKCODE
      CALL SCREEN '0100'.
    END-OF-SELECTION.
    *&      Module  STATUS_0100  OUTPUT
    *       text
    MODULE status_0100 OUTPUT.
      SET PF-STATUS 'STATUS_0100'.
    *  SET TITLEBAR 'xxx'.
    ENDMODULE.                 " STATUS_0100  OUTPUT
    *&      Module  USER_COMMAND_0100  INPUT
    *       text
    MODULE user_command_0100 INPUT.
      go_grid->check_changed_data( ).
      CASE gd_okcode.
        WHEN 'BACK'  OR
             'EXIT'  OR
             'CANC'.
          SET SCREEN 0. LEAVE SCREEN.
        WHEN 'REFRESH'.
          PERFORM colour_cells.
          CALL METHOD go_grid->refresh_table_display
    *        EXPORTING
    *          is_stable      =
    *          i_soft_refresh =
    *        EXCEPTIONS
    *          finished       = 1
    *          others         = 2
          IF sy-subrc <> 0.
    *       MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *                  WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
        WHEN OTHERS.
      ENDCASE.
      CLEAR: gd_okcode.
    ENDMODULE.                 " USER_COMMAND_0100  INPUT
    *&      Form  BUILD_FIELDCATALOG
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM build_fieldcatalog .
    * define local data
      DATA:
        ls_fcat        TYPE lvc_s_fcat.
      CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
        EXPORTING
    *     I_BUFFER_ACTIVE              =
          i_structure_name             = gc_tabname
    *     I_CLIENT_NEVER_DISPLAY       = 'X'
    *     I_BYPASSING_BUFFER           =
    *     I_INTERNAL_TABNAME           =
        CHANGING
          ct_fieldcat                  = gt_fcat
        EXCEPTIONS
          inconsistent_interface       = 1
          program_error                = 2
          OTHERS                       = 3.
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      ls_fcat-edit = abap_true.
      MODIFY gt_fcat FROM ls_fcat
          TRANSPORTING edit
        WHERE ( key NE abap_true ).
    ENDFORM.                    " BUILD_FIELDCATALOG
    *&      Form  SET_LAYOUT_AND_VARIANT
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM set_layout_and_variant .
      CLEAR: gs_layout,
             gs_variant.
      gs_layout-cwidth_opt = abap_true.
      gs_layout-zebra      = abap_true.
      gs_layout-ctab_fname = 'CELLCOLOR'.
      gs_variant-report = syst-repid.
      gs_variant-handle = 'GRID'.
    ENDFORM.                    " SET_LAYOUT_AND_VARIANT
    *&      Form  COLOUR_CELLS
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM colour_cells .
    * define local data
      DATA: ls_outtab   TYPE ty_s_outtab,
            ls_color    TYPE lvc_s_scol,
            ld_idx      TYPE i.
      LOOP AT gt_outtab INTO ls_outtab.
        ld_idx = syst-tabix.
        REFRESH: ls_outtab-cellcolor.
        IF ( ls_outtab-erdat+0(4) <= '2000' ).
          CLEAR: ls_color.
          ls_color-fname = 'ERDAT'.
          ls_color-color-col = cl_gui_resources=>list_col_negative.
          ls_color-color-int = 0.
          ls_color-color-inv = 0.
          APPEND ls_color TO ls_outtab-cellcolor.
        ENDIF.
        MODIFY gt_outtab FROM ls_outtab INDEX ld_idx.
      ENDLOOP.
    ENDFORM.                    " COLOUR_CELLS
    Regards
      Uwe

  • Conditional Formatting - change color for matching cell

    I have two sheets, Sheet1 and Sheet2.
    Sheet1 contains the following data:
    abc
    def
    ghi
    jkl
    mno
    pqr
    stu
    vwx
    yz
    Sheet2 contains the following:
    abc
    ghi
    jkl
    mno
    pqr
    yz
    I want to apply conditional formatting in Sheet1 for matches in Sheet2, so that for each match, the cell's fill color is changed to, say green.
    I select the entire range in Sheet1 and as a New Formatting Rule, choose Cell Value equal to = Sheet2!$A$2:$A$6
    However, this throws the following error:
    "This type of reference cannot be used in a Conditional Formatting formula.
    Change the reference to a single cell, or use the reference with a worksheet function, such as =SUM(A1:E5)"
    Any help here is greatly appreciated. Thanks.

    Use the formula:
    =ISNUMBER(MATCH(A1,Sheet2!$A$1:$A$6,0))

  • HOW TO CHANGE COLOR OF PARTICULAR CELL  IN ALV

    I HAVE DISPLAYED A REPORT IN ALV
    I WANT TO CHANGE THE COLOR OF VBELN FIELD  ON WHICH HOTSPOT IS ON?
    HOW TO DO THIS?

    Hi Lovleen,
    Check out the code
    *& Report  ZDEMO_ALVGRID                                               *
    *& Example of a simple ALV Grid Report                                 *
    *& The basic ALV grid, Enhanced to display each row in a different     *
    *& colour                                                              *
    REPORT  zdemo_alvgrid                 .
    TABLES:     ekko.
    type-pools: slis.                                 "ALV Declarations
    *Data Declaration
    TYPES: BEGIN OF t_ekko,
      ebeln TYPE ekpo-ebeln,
      ebelp TYPE ekpo-ebelp,
      statu TYPE ekpo-statu,
      aedat TYPE ekpo-aedat,
      matnr TYPE ekpo-matnr,
      menge TYPE ekpo-menge,
      meins TYPE ekpo-meins,
      netpr TYPE ekpo-netpr,
      peinh TYPE ekpo-peinh,
      line_color(4) type c,     "Used to store row color attributes
    END OF t_ekko.
    DATA: it_ekko TYPE STANDARD TABLE OF t_ekko INITIAL SIZE 0,
          wa_ekko TYPE t_ekko.
    *ALV data declarations
    data: fieldcatalog type slis_t_fieldcat_alv with header line,
          gd_tab_group type slis_t_sp_group_alv,
          gd_layout    type slis_layout_alv,
          gd_repid     like sy-repid.
    *Start-of-selection.
    START-OF-SELECTION.
    perform data_retrieval.
    perform build_fieldcatalog.
    perform build_layout.
    perform display_alv_report.
    *&      Form  BUILD_FIELDCATALOG
          Build Fieldcatalog for ALV Report
    form build_fieldcatalog.
    There are a number of ways to create a fieldcat.
    For the purpose of this example i will build the fieldcatalog manualy
    by populating the internal table fields individually and then
    appending the rows. This method can be the most time consuming but can
    also allow you  more control of the final product.
    Beware though, you need to ensure that all fields required are
    populated. When using some of functionality available via ALV, such as
    total. You may need to provide more information than if you were
    simply displaying the result
                  I.e. Field type may be required in-order for
                       the 'TOTAL' function to work.
      fieldcatalog-fieldname   = 'EBELN'.
      fieldcatalog-seltext_m   = 'Purchase Order'.
      fieldcatalog-col_pos     = 0.
      fieldcatalog-outputlen   = 10.
      fieldcatalog-emphasize   = 'X'.
      fieldcatalog-key         = 'X'.
    fieldcatalog-do_sum      = 'X'.
    fieldcatalog-no_zero     = 'X'.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'EBELP'.
      fieldcatalog-seltext_m   = 'PO Item'.
      fieldcatalog-col_pos     = 1.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'STATU'.
      fieldcatalog-seltext_m   = 'Status'.
      fieldcatalog-col_pos     = 2.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'AEDAT'.
      fieldcatalog-seltext_m   = 'Item change date'.
      fieldcatalog-col_pos     = 3.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'MATNR'.
      fieldcatalog-seltext_m   = 'Material Number'.
      fieldcatalog-col_pos     = 4.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'MENGE'.
      fieldcatalog-seltext_m   = 'PO quantity'.
      fieldcatalog-col_pos     = 5.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'MEINS'.
      fieldcatalog-seltext_m   = 'Order Unit'.
      fieldcatalog-col_pos     = 6.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'NETPR'.
      fieldcatalog-seltext_m   = 'Net Price'.
      fieldcatalog-col_pos     = 7.
      fieldcatalog-outputlen   = 15.
      fieldcatalog-datatype     = 'CURR'.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
      fieldcatalog-fieldname   = 'PEINH'.
      fieldcatalog-seltext_m   = 'Price Unit'.
      fieldcatalog-col_pos     = 8.
      append fieldcatalog to fieldcatalog.
      clear  fieldcatalog.
    endform.                    " BUILD_FIELDCATALOG
    *&      Form  BUILD_LAYOUT
          Build layout for ALV grid report
    form build_layout.
      gd_layout-no_input          = 'X'.
      gd_layout-colwidth_optimize = 'X'.
      gd_layout-totals_text       = 'Totals'(201).
    Set layout field for row attributes(i.e. color)
      gd_layout-info_fieldname =      'LINE_COLOR'.
    gd_layout-totals_only        = 'X'.
    gd_layout-f2code            = 'DISP'.  "Sets fcode for when double
                                            "click(press f2)
    gd_layout-zebra             = 'X'.
    gd_layout-group_change_edit = 'X'.
    gd_layout-header_text       = 'helllllo'.
    endform.                    " BUILD_LAYOUT
    *&      Form  DISPLAY_ALV_REPORT
          Display report using ALV grid
    form display_alv_report.
      gd_repid = sy-repid.
      call function 'REUSE_ALV_GRID_DISPLAY'
           exporting
                i_callback_program      = gd_repid
               i_callback_top_of_page   = 'TOP-OF-PAGE'  "see FORM
               i_callback_user_command = 'USER_COMMAND'
               i_grid_title           = outtext
                is_layout               = gd_layout
                it_fieldcat             = fieldcatalog[]
               it_special_groups       = gd_tabgroup
               IT_EVENTS                = GT_XEVENTS
                i_save                  = 'X'
               is_variant              = z_template
           tables
                t_outtab                = it_ekko
           exceptions
                program_error           = 1
                others                  = 2.
      if sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      endif.
    endform.                    " DISPLAY_ALV_REPORT
    *&      Form  DATA_RETRIEVAL
          Retrieve data form EKPO table and populate itab it_ekko
    form data_retrieval.
    data: ld_color(1) type c.
    select ebeln ebelp statu aedat matnr menge meins netpr peinh
    up to 10 rows
      from ekpo
      into table it_ekko.
    *Populate field with color attributes
    loop at it_ekko into wa_ekko.
    Populate color variable with colour properties
    Char 1 = C (This is a color property)
    Char 2 = 3 (Color codes: 1 - 7)
    Char 3 = Intensified on/off ( 1 or 0 )
    Char 4 = Inverse display on/off ( 1 or 0 )
              i.e. wa_ekko-line_color = 'C410'
      ld_color = ld_color + 1.
    Only 7 colours so need to reset color value
      if ld_color = 8.
        ld_color = 1.
      endif.
      concatenate 'C' ld_color '10' into wa_ekko-line_color.
    wa_ekko-line_color = 'C410'.
      modify it_ekko from wa_ekko.
    endloop.
    endform.                    " DATA_RETRIEVAL
    Regards,
    Chandru

  • How can i change backgroup Color of a Row in JTable

    Hi,
    i want to change the backgroup color of a particular row in a JTable,
    How can i do it??
    i tried so far
    table.setDefaultRenderer(Integer.class,new DefaultTableCellRenderer(){
            private Color color1 = new Color(255,255,204);
            private Color color2 = Color.RED;
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if( row%2 == 0 ){
                    c.setBackground(color1);
                else{
                    c.setBackground(color2);
                return c;
      );and also i tried
    TableCellRenderer renderer=null;
    renderer = table.getCellRenderer(i,0);
                      Component component = renderer.getTableCellRendererComponent(table,"",true,true,i,0);
                        if(item.getItemStatus().equals("Open")){
                            component.setBackground(java.awt.Color.LIGHT_GRAY);
                        else if(item.getItemStatus().equals("Buy It Now")){
                            component.setBackground(java.awt.Color.YELLOW);
                        else {
                          component.setBackground(java.awt.Color.RED);
                        }the 2nd code change the background color of whole table, while the 1st one doing nothing. please help me.......

    Try setting the cell renderer this way:
             DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {
                  private Color color1 = new Color(255,255,204);
                  private Color color2 = Color.RED;
                  public Component getTableCellRendererComponent(JTable table, Object value,
                          boolean isSelected, boolean hasFocus, int row, int column) {
                      System.out.println("test");
                      Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                      if( row%2 == 0 ){
                          c.setBackground(color1);
                      else{
                          c.setBackground(color2);
                      return c;
              for (int i = 0; i < table.getColumnCount(); i++)
                  table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);

  • HOw can i change the color of a cell

    How can I change the color of a cell when it is selected. I select the cell by pressing enter, then I want the text in the cell to change color to red, but all the cells in the table change color. Please I would be grateful for some help

    Subclass DefaultTableCellRenderer.
    public class MyCellRenderer extends DefaultTableCellRenderer
    Override
    public Componet getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    JLabel lab = new JLabel(String)value);
    lab.setOpaque(true);
    return lab;
    if(isSelected)
    lab.setBackground(Color.red);
    else
    lab.setBackground(Color.white);
    Set the columns in your table:
    table.getCoulumModel.getColumn(0).setCellRenderer(new myCellRenderer());
    table.getCoulumModel.getColumn(1).setCellRenderer(new myCellRenderer());
    etc. for each column in your table.

  • How to change background color to JCheckBox in a JTable?

    Dear Friends,
    I have an JTable in my application. It has four columns. First, third and fourth column contains JCheckBox (JCheckBox is created using Boolean.class), secod column contains values.
    I have to change some of the cell color where JCheckBox is present.
    Could anyone please tell me how to change the color of the cell in the JTable?
    Thanks in advance,
    Sathish kumar D

    You would use a custom renderer.
    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db
    Alternative link: SSCCE
    Edited by: Darryl.Burke

  • How to change the color of the Cell in Table ?

    Thanks a lot

    Here is the code to change the color of the cell in Table.
    First you need to write a class extending JTextField and implementing TableCellRenderer interface which has only one method as follows
    public class MyCellRenderer extends JTextField implements TableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus,int row, int column)
    setForeground(Color.blue);
    and wherever you create the table you need to set this renderer as the table cell renderer for your table. code follows...
    TableColumnModel tcm = yourtable.getColumnModel();
              Enumeration tce =tcm.getColumns();
              while (tce.hasMoreElements())
                   TableColumn tc=(TableColumn)tce.nextElement();
                   tc.setCellRenderer(new MyCellRenderer());
    this will solve your problem. you need to import the required packages.
    Srinivas.

  • I need help highlighting an expiration date on my Numbers '09 spreadsheet. I want the text/fill of a cell to change color when the expiration date of an item is within 180 days of the current date.

    I need help highlighting cells on my Numbers '09 spreadsheet.  I want the cell text/fill to change color when the date is 180 days or less from the current date.  I already have a cell with the current date in it.  I also know how to change the fill/text colors.  All the cells have been formatted to show date only.  I am having trouble with the formula.  I can get to the Conditional Formatting menu and select "With Dates" but after that I am lost.  Can anyone help?
    Thank you for any assistance.
    B

    Set a Conditional Format rule as shown in the illustration below. The rule has been applied to all dates in column B of the table.
    Regards,
    Barry

  • How to change the background color of a cell in datagrid using flex3

    i want to change the background color of a cell.....how can i achieve this.....and also i want to know how a spacing cane be done between cells in a datagrid...plzzz help me???

    The only way I can see to do this is to use an item renderer for your cells.  This is really scruffy and would need tyding up, and maybe with a little more time could do better or someone else may have an idea but none the less this works.
    Define a custom component as below;
    This has logic to see what the value of the data is proveided by the dataprovider for the row, and if it matches the conditions in this case is equal to 5 sets the background color.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="88" height="26" dataChange="doColor()" borderColor="#000000" borderStyle="solid"
        backgroundAlpha="1">
        <mx:Script>
            <![CDATA[
                private function doColor():void {
                    if (data.value == 5) {
                        setStyle('backgroundColor', 0xcccccc);
                    } else {
                        setStyle('backgroundColor', 0xffffff);
            ]]>
        </mx:Script>
    </mx:Canvas>
    Now just apply the item renderer in the datagrid and that will do it.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  xmlns:ns1="*">
        <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                [Bindable]
                private var ac:ArrayCollection = new ArrayCollection([
                    {value : 1},
                    {value : 2},
                    {value : 3},
                    {value : 4},
                    {value : 5},
                    {value : 6},
                    {value : 7},
                    {value : 8},
                    {value : 9},
                    {value : 10}
          ]]>
        </mx:Script>
        <mx:DataGrid x="40" y="36" width="408" height="193" dataProvider="{ac}">
            <mx:columns>
                <mx:DataGridColumn headerText="Column 1" dataField="value" itemRenderer="MyComp"/>
                <mx:DataGridColumn headerText="Column 2" dataField="col2"/>
                <mx:DataGridColumn headerText="Column 3" dataField="col3"/>
            </mx:columns>
        </mx:DataGrid>
    </mx:Application>
    I hope this helps
    Andrew

  • How do i change the cell color of each cell in datagrid dynamically

    I have a  datagrid filled in with data..My job is to change the cell color of a particular cell in the datagrid when the user clicks that cell..Please help me asap..I have to change the color of each cell dynamically..

    Pls find the solution of ur problem.Let me know if you have any issue.
    MainApplicaion.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical">
        <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.events.ListEvent;
                [Bindable]
                  private var listDataArrayCollection:ArrayCollection=
                  new ArrayCollection([
                    {seq:'1',color:'0xFF0000', names:'John'},
                    {seq:'2',color:'0x00FF00', names:'Alex'},
                    {seq:'3',color:'0x0000FF', names:'Peter'},
                    {seq:'4',color:'0xFF0000', names:'Sam'},
                    {seq:'5',color:'0x00FF00', names:'Alis'},
                    {seq:'6',color:'0x0000FF', names:'Robin'},
                    {seq:'7',color:'0xFF0000', names:'Mark'},
                    {seq:'8',color:'0x00FF00', names:'Steave'},
                    {seq:'9',color:'0x0000FF', names:'Fill'},
                    {seq:'10',color:'0xFF0000', names:'Abraham'},
                    {seq:'11',color:'0x00FF00', names:'Hennery'},
                    {seq:'12',color:'0x0000FF', names:'Luis'},
                    {seq:'13',color:'0xFF0000', names:'Herry'},
                    {seq:'14',color:'0x00FF00', names:'Markus'},
                    {seq:'15',color:'0x0000FF', names:'Flip'},
                    {seq:'16',color:'0xFF0000', names:'John_1'},
                    {seq:'17',color:'0x00FF00', names:'Alex_1'},
                    {seq:'18',color:'0x0000FF', names:'Peter_1'},
                    {seq:'19',color:'0xFF0000', names:'Sam_1'},
                    {seq:'20',color:'0x00FF00', names:'Alis_1'},
                    {seq:'21',color:'0x0000FF', names:'Robin_1'},
                    {seq:'22',color:'0xFF0000', names:'Mark_1'},
                    {seq:'23',color:'0x00FF00', names:'Steave_1'},
                    {seq:'24',color:'0x0000FF', names:'Fill_1'},
                    {seq:'25',color:'0xFF0000', names:'Abraham_1'},
                    {seq:'26',color:'0x00FF00', names:'Hennery_1'},
                    {seq:'27',color:'0x0000FF', names:'Luis_1'},
                    {seq:'28',color:'0xFF0000', names:'Herry_1'},
                    {seq:'29',color:'0x00FF00', names:'Markus_1'},
                    {seq:'30',color:'0x0000FF', names:'Flip_2'}
                private function onItemClick(event : ListEvent):void
                    var dataObj : Object = event.itemRenderer.data;
                    dataObj.color = "0xFF00FF";
                    event.itemRenderer.data = dataObj;
            ]]>
        </mx:Script>
        <mx:VBox width="300" height="100%"
            horizontalAlign="center"
            verticalAlign="middle">
            <mx:DataGrid id="listComponent" width="50%"
                     height="100%"
                     borderStyle="none"
                     dataProvider="{listDataArrayCollection}"
                     itemClick="onItemClick(event)">
                     <mx:columns>
                     <mx:DataGridColumn width="100" dataField="{data.seq}" headerText="Seq" itemRenderer="SeqItemRenderer" />
                     <mx:DataGridColumn width="100" dataField="{data.names}" headerText="Name" itemRenderer="NameItemRenderer"/>
                     </mx:columns>
                     </mx:DataGrid>
        </mx:VBox>
    </mx:Application
    NameItemRenderer.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
        width="100" height="30" horizontalGap="5" horizontalScrollPolicy="off">
    <mx:Script>
        <![CDATA[
            override public function set data(value:Object):void
                 super.data = value;
        ]]>
    </mx:Script>
            <mx:TextInput width="75" height="30"
                 text="{data.names}"
                 editable="false" backgroundColor="{data.color}"/>
        </mx:HBox>
    SeqItemRenderer.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
        width="100" height="30" horizontalGap="5" horizontalScrollPolicy="off">
    <mx:Script>
        <![CDATA[
            override public function set data(value:Object):void
                 super.data = value;
        ]]>
    </mx:Script>
            <mx:TextInput width="75" height="30"
                 text="{data.seq}"
                 editable="false" backgroundColor="{data.color}"/>
        </mx:HBox>
    with Regards,
    Shardul Singh Bartwal

  • URGENT - Change color for a set of rows in JTable

    Hello all,
    How can i set color for a particular set of row which are all having same values in a cell. If any other rows contains same value that should also be in different color.
    Example:
    I have 10 rows containing itemcode and taxes in JTable.
    1st, 2nd and 4 th row contains same value of Taxes -- It should be in a set of color. red
    6th and 8th row containing same value of Taxes -- it should be in a set of color blue
    other are in normal color. Kindly send the coding for the above. Advance thanks.
    Regards,
    N.A. Ramasubramani / Chennai.

    Hi,
    Here is how I do it... create a Vector of Vector or an array[row][col] containing colors for every cell (row,col). Create a custom Cell renderer in which you pass the color data variable. Then in the renderer you get the Row and Col and set the appropriated color for the background.
    JRG

Maybe you are looking for

  • Balance forward billing not working on r12.1.3

    Hi, I am unable to work on the Balance forward billing, the bill date is not getting generated. Can you please send me the solution for BFB for 12.1.3, also I need to customize the BFB to be based on Customer PO number and not date. Thanks in Advance

  • Installing Logic on an External Drive?

    Wondering... Can you install Logic on an external hard drive or does it need to go on the same drive as the system folder? I dont' have a free 4GB right now for the update. How much free space do you guys recommend for LP7? Chris

  • Safe download box in safari preferences?

    Is it a good idea to uncheck the safe download box the safari preferences?  I 've seen people talk about this & I'm new to the mac world.   THANKS!

  • Left over objects from install?

    I had started to migrate DNS and DHCP from a Netware 6.5 server to an OES 11 server and then held off. DNS and DHCP are both still running fine on my two Netware 6.5 servers. I noticed that I have some odd objects scattered around my tree now. Netwar

  • Threads with servlets

    Best groupmember, I have a jsp and a servlet. The jsp includes the servlet. The servlet looks like this: class TheServlet extends HttpServlet { private String myFirstname = ""; private String myLastname = ""; public void doPost(......) { //Loads of t