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

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;
    };

  • Setting the backgroundcolor of cell of JTable

    Hi
    My Problem is.
    I have a JTable with 2 columns ( Rows can be 1-10 depending upon the size of
    input vector)
    I have provided two button in my Frame
    1)Update Row
    2) Update whole Table.
    Now i want I want that if a user makes a change in any cell say cell( row
    3,Col 1) ;and moves to next row , then the color (background/foreground) of
    that cell should change to any other color .Again if he presses any of the
    button then the default color of the cell should be restored.Basically i
    want to indicate the user that he has made changes in the cell and he needs
    to press the button for updation
    Regards
    Aminur

    You need to write your own TableCellRenderer if you want to control how individual table cells appear. Look in the How to Use Table tutorial if you haven't already done that; you'll find a link to it in the API documentation for the JTable class. And in that renderer, if you use a JLabel to render the cell, remember that a JLabel defaults to being transparent, i.e. you can't see its background. Use "setOpaque(true)" if you want to control the background colour.

  • 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

  • Set color alv output cell abap webdynpro

    Hi Guys ,
    i wanted to set the color of some cells in alv output to red in ABAP WebDynpro.
    i am using the salv_wd_table.
    any piece of code is appreciated.
    thanks,
    Bobby.

    Bobby,
    If let's say you are build a ALV table to output 'SFLIGHT' table, and you want PLANETYPE '747-400' to be displayed in green, and PLANETYPE '146-200' displayed in red.
    Also, let's just say, you already had a context node 'SFLIGHT_NODE' that is mapped to the external node 'DATA' of your ALV.
    Now:
    1.  you need to modify the context node 'SFLIGHT_NODE' to add an attribute -- say 'CELL_COLOR' of type 'WDY_UIE_LIBRARY_ENUM_TYPE' -- to the SFLIGHT_NODE (note, you need to delete 'DICTIONARY structure' that is bind to the 'SFLIGHT_NODE' node, otherwise, you will not be able to create addition attributes)
    After, you will have something like this for your context node .
      CONTEXT
        --> SFLIGHT_NODE  
    > CARRID
    > CONNID
    > FLDATE
    > PRICE
    > PLANETYPE
    > <and any other attributes you had pulled from SFLIGHT)
    > CELL_COLOR (TYPE WDY_UIE_LIBRARY_ENUM_TYPE)
    2.  In your supply function to the 'SFLIGHT_NODE', you now need to supply the data to this newly added attribute:
    METHOD supply_sflight_node .
    ** data declaration
      DATA:
        itab_sflight_node            TYPE if_componentcontroller=>elements_sflight_node,
        stru_sflight_node            LIKE LINE OF itab_sflight_node.
    ** read sflight data
      SELECT * FROM sflight INTO CORRESPONDING FIELDS OF TABLE itab_sflight_node.
    ** populate the 'CELL_COLOR' field
      LOOP AT itab_sflight_node INTO stru_sflight_node .
        IF stru_sflight_node-planetype = '747-400'.
          stru_sflight_node-cell_color = CL_WD_TABLE_COLUMN=>E_CELL_DESIGN-GOODVALUE_DARK .
         ELSEIF stru_sflight_node-planetype = '146-200'.
          stru_sflight_node-cell_color = CL_WD_TABLE_COLUMN=>E_CELL_DESIGN-BADVALUE_DARK .  
        ELSE.
          stru_sflight_node-cell_color = CL_WD_TABLE_COLUMN=>E_CELL_DESIGN-STANDARD .
        ENDIF.
        modify itab_sflight_node from stru_sflight_node.
      ENDLOOP.
    ** bind all the elements
      node->bind_table(
        new_items =  itab_sflight_node
        set_initial_elements = abap_true ).
    ENDMETHOD.
    3. Now, you need to obtain the configuration model of the ALV and config it before display.  (say you have an method does this 'init_alv_table_settings', and it is called from your view's wddoinit() method)
    METHOD init_alv_table_settings .
      DATA: l_ref_cmp_usage TYPE REF TO if_wd_component_usage.
      l_ref_cmp_usage =   wd_this->wd_cpuse_alv_table( ).
      IF l_ref_cmp_usage->has_active_component( ) IS INITIAL.
        l_ref_cmp_usage->create_component( ).
      ENDIF.
      DATA: l_ref_interfacecontroller TYPE REF TO iwci_salv_wd_table .
      l_ref_interfacecontroller =   wd_this->wd_cpifc_alv_table( ).
      DATA:
      node_sflight_node                   TYPE REF TO if_wd_context_node .
      node_sflight_node = wd_context->get_child_node( name = if_flights_view=>wdctx_sflight_node ).
      CALL METHOD l_ref_interfacecontroller->set_data
        EXPORTING
          r_node_data = node_sflight_node.
    **  get ConfigurationModel from ALV Component
      DATA:    lr_table TYPE REF TO cl_salv_wd_config_table.
      lr_table = l_ref_interfacecontroller->get_model( ).
    ** change the color of the cell
      DATA: lr_column_settings TYPE REF TO if_salv_wd_column_settings.
      DATA: lr_column TYPE REF TO cl_salv_wd_column.
      lr_column_settings ?= lr_table.
      lr_column = lr_column_settings->get_column( 'PLANETYPE' ).
      DATA: lr_input_field TYPE REF TO cl_salv_wd_uie_input_field.
      CREATE OBJECT lr_input_field EXPORTING value_fieldname = 'PLANETYPE'.
      lr_column->set_cell_editor( lr_input_field ).
      lr_column->set_cell_design_fieldname( value = 'CELL_COLOR' ).
    ENDMETHOD.
    Compile and activate your code.
    Regards,
    Tina Yang
    Message was edited by: Tina Yang

  • Help needed badly with coloring of specific cells in a tble

    I have an existing table and when this code, it colors all the cells in a column. Hoe can I use the funktion getCellRenderer: to color only one cell at a time and implement it in an already existing table.
    THX for any help I can get :)
    ColorRenderer cell=new ColorRender();
    // for(int i=0;i<table.getModel().getColumnCount();i++){
    // TableColumn mod=this.getColumn((this.getModel().getColumnName(i)));
    mod.setCellRenderer(cell);
    And ur ColorRender calss should override DefaultTableCellRenderer like this
    class ColorRenderer extends DefaultTableCellRenderer {
    protected int align;
    public ColorRenderer(int align) {
    this.align=align;
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row,
    int column) {
    setHorizontalAlignment(align);
    super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
    if(col==4){
    setBackground(Color.cyan);
    return this;
    }

    Here's a bit of Friday Fun: before you run this code, what do you think the table will look like?
    What will it look like as you click and drag on it to select cells?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class X {
        static class R extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component that = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                Color bk = that.getBackground();
                that.setBackground((row + column)%2==0? bk.darker() : bk.brighter());
                return that;
        public static void main(String[] args) {
            JTable table = new JTable(20,10);
            table.setDefaultRenderer(Object.class, new R());
            JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(table));
            f.setSize(400, 300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);

  • How to color a specific cell in ALV (not REUSE_ALV_GRID_DISPLAY)

    Hi
    I want to change color font or background to a specify position in ALV grid
    It is possible but by creating ALV container (not FM for example REUSE_ALV_GRID_DISPLAY)?

    Hi,
    REPORT ZALV_LIST1.
    TABLES:
    SPFLI.
    TYPE-POOLS:
    SLIS.
    PARAMETERS:
    P_COL TYPE I ,
    P_ROW TYPE I,
    P_COLOR(4) TYPE C .
    DATA:
    T_FIELDCAT TYPE SLIS_T_FIELDCAT_ALV,
    FS_FIELDCAT LIKE LINE OF T_FIELDCAT,
    FS_LAYOUT TYPE SLIS_LAYOUT_ALV ,
    W_COLOR(4) ,
    W_ROW TYPE I,
    W_FIELDNAME(20),
    W_PROG TYPE SY-REPID.
    DATA:
    BEGIN OF T_SPFLI OCCURS 0,
    COLOR(4),
    CHECKBOX ,
    CELL TYPE SLIS_T_SPECIALCOL_ALV,
    CARRID TYPE SPFLI-CARRID,
    CONNID TYPE SPFLI-CONNID,
    CITYFROM TYPE SPFLI-CITYFROM,
    CITYTO TYPE SPFLI-CITYTO,
    DISTANCE TYPE SPFLI-DISTANCE,
    END OF T_SPFLI.
    DATA:
    FS_CELL LIKE LINE OF T_SPFLI-CELL.
    SELECT *
    FROM SPFLI
    INTO CORRESPONDING FIELDS OF TABLE T_SPFLI.
    W_COLOR = P_COLOR.
    T_SPFLI-COLOR = P_COLOR.
    IF P_COL IS INITIAL AND P_ROW GT 0.
    MODIFY T_SPFLI INDEX P_ROW TRANSPORTING COLOR.
    ENDIF.
    FS_FIELDCAT-FIELDNAME = 'CARRID'.
    FS_FIELDCAT-REF_TABNAME = 'SPFLI'.
    FS_FIELDCAT-COL_POS = 1.
    FS_FIELDCAT-KEY = 'X'.
    FS_FIELDCAT-HOTSPOT = 'X'.
    APPEND FS_FIELDCAT TO T_FIELDCAT.
    CLEAR FS_FIELDCAT .
    FS_FIELDCAT-FIELDNAME = 'CONNID'.
    FS_FIELDCAT-REF_TABNAME = 'SPFLI'.
    FS_FIELDCAT-COL_POS = 2.
    FS_FIELDCAT-KEY = 'X'.
    FS_FIELDCAT-HOTSPOT = 'X'.
    APPEND FS_FIELDCAT TO T_FIELDCAT.
    CLEAR FS_FIELDCAT .
    FS_FIELDCAT-FIELDNAME = 'DISTANCE'.
    FS_FIELDCAT-REF_TABNAME = 'SPFLI'.
    FS_FIELDCAT-COL_POS = 3.
    FS_FIELDCAT-KEY = ' '.
    FS_FIELDCAT-EDIT = 'X'.
    APPEND FS_FIELDCAT TO T_FIELDCAT.
    CLEAR FS_FIELDCAT.
    FS_FIELDCAT-FIELDNAME = 'CITYFROM'.
    FS_FIELDCAT-REF_TABNAME = 'SPFLI'.
    FS_FIELDCAT-COL_POS = 4.
    FS_FIELDCAT-KEY = ' '.
    APPEND FS_FIELDCAT TO T_FIELDCAT.
    LOOP AT T_FIELDCAT INTO FS_FIELDCAT.
    IF FS_FIELDCAT-COL_POS EQ P_COL.
    FS_FIELDCAT-EMPHASIZE = P_COLOR.
    W_FIELDNAME = FS_FIELDCAT-FIELDNAME.
    IF P_ROW IS INITIAL AND P_COL GT 0.
    MODIFY T_FIELDCAT FROM FS_FIELDCAT TRANSPORTING EMPHASIZE.
    ENDIF.
    ENDIF.
    ENDLOOP.
    FS_CELL-FIELDNAME = W_FIELDNAME .
    FS_CELL-COLOR-COL = 6.
    FS_CELL-NOKEYCOL = 'X'.
    APPEND FS_CELL TO T_SPFLI-CELL.
    IF P_ROW IS NOT INITIAL AND P_COL IS NOT INITIAL.
    MODIFY T_SPFLI INDEX P_ROW TRANSPORTING CELL.
    ENDIF.
    FS_LAYOUT-INFO_FIELDNAME = 'COLOR'.
    FS_LAYOUT-BOX_FIELDNAME = 'CHECKBOX'.
    FS_LAYOUT-COLTAB_FIELDNAME = 'CELL'.
    FS_LAYOUT-F2CODE = '&ETA'.
    W_PROG = SY-REPID.
    CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
    EXPORTING
    I_CALLBACK_PROGRAM = W_PROG
    IS_LAYOUT = FS_LAYOUT
    IT_FIELDCAT = T_FIELDCAT
    TABLES
    T_OUTTAB = T_SPFLI
    EXCEPTIONS
    PROGRAM_ERROR = 1
    OTHERS = 2

  • How to apply different colors to specific rows in JTable

    hi,
    Anybody could tell me the way of colorising the rows in jtable.. I want to apply different colors to diff rows..
    If i get a piece of code that could help me a lot..
    thanks in advance,
    Sapna

    you'll find the answer at http://www2.gol.com/users/tame/swing/examples/SwingExamples.html

  • How to set Color of Specific String in JEditorPane?

    I have tried using jp1.setForeground(Color.red) but all the text in JEditorPane are set to red. I want the JEditorPane to display red for all text except a particular string 'xyz'. Can anyone pls help me?
    Thank you.

    Its easier to use a JTextPane. Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html]Using Text Components.
    And here's another thread that will help:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=342068

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

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

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

  • Setting color in cfgrid cell

    Hi,
    I'd like to access particular cell properties in cfgrid to
    change its' background color. I know how to change whole row color
    or column color but I'm interested in changing only one cell.
    Thanks in advance
    CM

    You can probably do it with a bit of ActionScript.
    I did a bit of googling and found an example of someone altering the way cells are rendered here:
    http://www.asfusion.com/blog/entry/using-labelfunction-to-format-cfgrid
    Not quite what you want, byut it points to using ActionScript to effect these sorts of things.
    I'm sure if you do a bit of googling you can turn up more info.
    Adam

  • How to disable a particular cell in JTable ?

    I having a problem on how to set disable a particular cell in JTable. At the first place to load the JTable, I want to set some of the cell to disabled, it only will run at the first time, is there anyway to do it ?

    This is the function that disable/enable cells in JTables.
    Are you looking for this?
    public boolean isCellEditable(int row, int col)
      if(((new Integer((String)(getValueAt(row,0)).toString()).intValue()>9))&&(col==1))
        return true;
      if(row!=4&&col!=5)
        return true;
      return false;
         this metod belong to the TableModel function
    and what I gave you is only an example of what you can do with it.
    if it return false it disable and if true it enable the cell...but I think this you allready know!
    Regards Amnon

  • Setting color in a specific JTable

    I was wondering if anyone could help me with this problem. I wish to set some cells in the first column only to Yellow. I have done the following;public class customTableCellRenderer extends
    DefaultTableCellRenderer
        JTable table;
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    Component cell = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);//getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if(value instanceof String)
                 String s= (String) value;
                 if(value.equals("Monday"))
                    cell.setBackground(Color.YELLOW);
                else
                    cell.setBackground(Color.BLUE);
                 return cell;
    }and my class with the JTable calls the above class:
        public JPanel centre()
            JPanel tablePanel=new JPanel(new BorderLayout());
            Object[] titles = new String[]{"","9.00","10.00","11.00","12.00","13.00","14.00","15.00","16.00","17.00","18.00","19.00"};
            String[] rows = new String[]{"Monday","Tuesday","Wednesday","Thursday","Friday"};
            Object[][] data ={
                        {"Monday","","","","","","","","","","",""},
                         {"Tuesday","","","","","","","","","","",""}};
              DefaultTableModel model=new DefaultTableModel(data,titles); 
              table=new JTable(model);
             String[][] data = new String[rows.length][titles.length];
            JTable timeTable = new JTable(data, titles);         customTableCellRenderer cr=new customTableCellRenderer();
               try
                table.setDefaultRenderer( Class.forName
                   ( "java.lang.Integer" ), cr );
            catch( ClassNotFoundException ex )
                System.exit( 0 );
            table.setDefaultRenderer(Color.class, cr);
            JScrollPane pane = new JScrollPane(table);  
            pane.setSize(new Dimension(500,300));
            pane.setViewportView(table);
            tablePanel.add("Center", pane);
            return tablePanel;
    }it still doesnt set the color in the cells for; Monday, Tuesday, Wednesday, Thursday, Friday.

    Your renderer isn't being used.
    JTable chooses the appropriate renderer based on the value of the getColumnClass(...) method. Since you haven't overridden that method it thinks all data is an Object and uses the Object renderer.
    The following lines accomplish nothing, since you don't store any Integers or Color objects in your table. Every Object is a String.
    table.setDefaultRenderer( Class.forName( "java.lang.Integer" ), cr );
    table.setDefaultRenderer(Color.class, cr);
    If you want you can specifiy a renderer for a specific column. You get the TableColumn from the TableColumnModel and add the renderer directly to the column.
    If all you want to do is color a cell, then another option is to override the prepareRenderer() method. Something like this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Setting color for cells in a particular column of a jtable

    Hi, I know how to set the color for a cell in a column if the cell contains an Integer object and if I have default Integers already in the JTable when I begin. However I want the JTable to look blank at the beginning. As I can't make an Integer object invisible on the JTable I need to specify the colum in which I want the cells to change color in. I want to specify the column some how and then when the table later has Integers in it i can do a comparison to decide whether i want to change the color or not. Does anyone know how I will do this.
    Please HELP.

    1) You need to set the tooptip text on the renderer for the column (yourTable.getColumnModel().getColumn(...).getHeaderRenderer()).
    2) The header is a separate component to the table. When you add a table to a scroll pane it automatically adds the header to the scroll pane too. You can get the component (yourTable.getTableHeader()) and add it to your own container if you wish.

Maybe you are looking for