HELP!! set the cell color in jTable

I need to set the color of a specific cell in jTable, but, I need to retain the old color in the jTable. It must not reset the whole table.
would anyone help me in this problem... PLSSSSS its urgent

A flexible variation on this is to specify formatting options in the JTable's client properties:
// Use some sort of special "key" to indicate the cell and that you want to set the background color
String key = "background:" + row + "," + column;
table.putClientProperty(key, Color.green);You can then write a general table cell renderer that looks for these special formatting options and it doesn't disrupt your existing TableModel in any way:
public class FormattingTableCellRenderer extends DefaultTableCellRenderer
  public Component getTableCellRendererComponent(JTable table, Object value, int row, int column, ...)
    Component component = super.getTableCellRendererComponent(table, value, row, column, ...);
    // See if the JTable specifies any properties to override the default format
    Color backgroundColor = (Color)table.getClientProperty("background:" + row + "," + column);
    if(backgroundColor != null)
      component.setBackground(backgroundColor);
    return component;
}Any custom cell renderers you have then simply need to extend FormatTableCellRenderer instead of DefaultTableCellRenderer.
It's very easy to add formatting options other than background, such as font, to the list of recognised attributes. You'll probably need to make some alterations to get it to recognise selection/focus but hopefully you get the idea.
Hope this helps.

Similar Messages

  • Problem in setting the background color of jtable with Nimbus

    Hi
    I have created a java swing application. In which I am using JTable.
    When creating a simple JTable and displaying with Nimbus, the row background color alternates between white and a light blue-grey.
    I want the table with single colour. Only the first column should be grey colour and other should be white.
    I used this code to set the background and foreground colour.
    public Component prepareRenderer
        (TableCellRenderer renderer, int index_row, int index_col){      
                Component objComponent = super.prepareRenderer(renderer, index_row, index_col);         
                Color objGreyColour = new Color(240,240,240);
                Color objWhiteColour = new Color(255,255,255);
                if(index_col == 0){
                    objComponent.setBackground(objGreyColour);
                    objComponent.setFont(new java.awt.Font(CommonClass.getFontName(),java.awt.Font.BOLD, CommonClass.getFontSize()));
                    objComponent.setForeground(Color.BLACK);
                }else{               
                    setSelectionBackground(Color.BLUE);
                    objComponent.setBackground(objWhiteColour);
                    objComponent.setForeground(Color.BLACK);
                return objComponent;
            } Look wise it is fine but when i try to select the cell it is not highlighting the cell and also i m not able to select multiple cell with ctrl key.
    Any help would be appreciated
    Thanks
    Sonal

    Hello,
    1) if you want better help soone,r please post an SSCCE (http://sscce.org) instead of a code extract.
    2) selection highlighting is lost because your code... doesn't handle selection. To take selection into account, you can use <tt>if (super.isRowselected(index_row)) {...}</TT>.
    Regards,
    J.

  • Change the cell color in JTable?

    Hi all,
    I'm trying to do that, the user make a selection of multiple cells in a table. And when it press enter, I whant to change the color of the selected cells.(the isEditable of JTable it's already overwritten to return always false)
    I have already make my own CellRender, my problem is, because the cell remains unchanged the render are not called...
    Thanks,
    NeuralC

    You need not access this function when you want to paint a cell. This is how your code while instantiating the table should typically look like.
    JTable table = new JTable(model);
    table.setDefaultRenderer(Object.class,new MyCellRenderer());
    and
    public class MyTableCellRenderer extends JLabel implements TableCellRenderer
    public MyTableCellRenderer
    setOpaque(true);
    setBackground(Color.white);
    public Component getTable.....(JTable table,Object value,......) //fill all these things
    setFont(table.getFont());
    if(value != null && isSelected)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    return this;
    When you set MyTableCellRenderer to the table, the getTableCellRedererComponent method is called automatically to renderer the cells and only the selected cells will be hightlighted in blue color. For a better understanding of how tables work and their corresponding Renderers work, you might have to read the tutorial on JTable. Do that as that would help you in removing all the confusion.
    Thanks,
    Kalyan

  • Enter a brief summary here holding the cell color in jtable

    Hai every body, I hope someone can rescue me. we r building a standalone application(trading system) for the StockMarket. we r trying to update the watchlist,which displays the market ticks.those who r in this domain can understand this as live streaming.Everything is fine.i could acheive this task.but now my boss has created a problem. he wants the jtable cell to hold the color,once the packet has appeared for that symbol.But currently my system(jtable) holds only the latest color.this can be explained further like this,accoring to the market movement,once the tick has come ,basing on the previous value,say if the value has increased i make the table cell as blue and if the value has decreased the table cell is made red. Now i'm really struggling to hold the colors of the previous ticks.can anyone suggest me a solution for this... i hope someone will come to my rescue... i customized the defaulttablecellrenderer.
    thanks in advance regards,
    RaviTeja

    I think having a custom renderer like this might address your issue.
    public Component getTableCellRendererComponent(JTable table,
         Object value, boolean isSelected, boolean hasFocus,
         int row, int col) {
         String oldString = getText();
         if(oldString == null || oldString.length() == 0) {
              oldString = "0.00";
         double oldValue = Double.parseDouble(oldString);
         double newValue = ((Double) value).doubleValue();
         if(oldValue < newValue) {
              //Set desired background and foreground colors.
         else if(oldValue > newValue) {
              //Set desired background and foreground colors.
         else {
              //Set desired background and foreground colors.
         setText(String.valueOf(newValue));
         return null;
    }Hope this helps..
    Sai Pullabhotla

  • Help setting the background color in the browser

    I’m setting up my web pages to be 960 x 600 pixels (or possibly 960 x 660).  How do I define a background color for the overflow in case people are viewing on higher than 1024 x 768 resolution -  right now everything outside of my webpage shows up as the default white.
    Thanks

    Use CSS.
    body { background-color:heliotrope; }

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • Writing own TableCellRenderer for setting the Background Color of a cell ?

    Hello,
    I am using the JTable and DefaultTableModel for my GUI. I use also only plain text in the rows and columns. I have a method which examine every row wether something is wrong with a string so if something is wrong i want to set the BackgroundColor of this cell with the bad string to a color i can define.
    Do I need to write an own TableCellRenderer for this tiny task?
    Table class has no setBackground(new Color(22,22,22),posRow,posCol);

    http://forum.java.sun.com/thread.jspa?forumID=57&threa
    dID=606504this code is from your ColorRenderer class:
    public void actionPerformed(ActionEvent e)
                   Iterator it = colors.keySet().iterator();
                   while ( it.hasNext() )
                        Point key = (Point)it.next();
                        int row = key.x;
                        int column = key.y;
                        if (column == -1)
                             model.fireTableRowsUpdated(row, row);
                        else if (row == -1)
                             int rows = table.getRowCount();
                             for (int i = 0; i < rows; i++)
                                  model.fireTableCellUpdated(i, column);                              
              }you have set an ActionListener to the ColorRenderer class and put the actionPerformed method in it but compared to a JButton the actionPerformed method is called when i click the JButton but what you do in your code that the actionPerformed method is executed. I have deleted the whole actionPerformed method and the listener and still the cell is displayed with a color so was it for the blinking?
    And the method setBackground is nowhere called or run actively so is this method called internally by the ColorRenderer class? or is this method somehow called recursively as in the method setBackground I can see this method call:
    c.setBackground( (Color)o ); but i think this is another setBackground method right? because the first method i mentioned has 3 parameters not 1 parameter so where is the method setBackground with 3 parameters called actively in your code? i cant find anything. ok after examining again the c.setBackground( (Color)o ); is the one with 3 parameters ;-)
    public void setBackground(Component c, int row, int column)
              { that was set for the previous cell, so reset it here
                   if (c instanceof DefaultTableCellRenderer)
                        c.setBackground( table.getBackground() );
                   //  In case columns have been reordered, convert the column number
                   column = table.convertColumnIndexToModel(column);
                   //  Get cell color
                   Object key = getKey(row, column);
                   Object o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
                   //  Get row color
                   key = getKey(row, -1);
                   o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
                   //  Get column color
                   key = getKey(-1, column);
                   o = colors.get( key );
                   if (o != null)
                        c.setBackground( (Color)o );
                        return;
              }using your full code gives me a bug:
    when i double click in the first column to change some text doesnt matter which row then the selected cell gets a red border and the rest of the table freezes. When i exchange the order of the columns move column 1 to 2 and column 2 to 1 then the freezed table is working again?? could you help solving that problem else the cell color setting works fine for me :-) thank you very much!

  • 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

  • How can i set the alternating colors for a table rows

    Dear All,
    Please any one help me how can i set the Alternating colors for Table Rows.
    i created a theam there i set the background alternating color to brown and i set the table design properity to alternating. but it is not reflecting.

    Hi,
    The design property in Table properties should work for your requirement. Select "alternating" value for design.
    Please see the API below:
    design
    Determines the appearance of the table. The property design can take the following values and is represented by enumeration type WDTableDesign.
    alternating - The table rows are displayed alternately in a different color.
    standard - The table background has one color. The individual table rows are displayed with grid net lines.
    transparent - The table background is transparent. The individual table rows are displayed without grid net lines.
    Check whether you have changed the right property or not? Also table should contain more than one rows to test this scenario.
    Regards,
    Jaya.
    Edited by: VJR on Jun 17, 2009 6:43 PM

  • Can I invoke a SubVI in an event? and how do I set the background color of a pipe to #0000ff?

    When I click an image or a glass pipe(which belongs to Industry/Chesmitry category in palette), I want a SubVI to be invoked.
    The purpose is to fetch an OPC-UA data from a web service and to write to it via the service.
    We are building an HMI solution which displays an interactive water plant diagram.
    When users click pipes and motors in the diagram, clicked devices should be turned on and off and change their animations or colors accordingly.
    OPC-UA is for communication with devices.
    I couldn't even set the background color of a pipe to "#0000ff", but setting it to "Red" or "Blue" was possible, and I don't know how to invoke SubVIs in event scripts.
    The documentations in NI.com are confusing and lack depth.
    Even silverlight references are confusing.
    How do I do all of these?

    Hi iCat,
    Can you provide some more information about your current implementation so that we can help to answer your questions. Some questions I have for you are:
    Are you creating this project in the NI LabVIEW Web UI Builder or in LabVIEW?
    How are you publishing your webservice? Is this also in LabVIEW?
    How is your webservice interacting with an OPC-UA server?
    How is the certification set up with OPC-UA so that you can communicate between the server and the client?
    Best Regards,
    Allison M.
    Applications Engineer
    National Instruments
    ni.com/support

  • How to set the Background Color of a Text Field in a Tabular Report.

    Hello,
    I tried to set the Background Color of a Text Field in a Tabular Report.
    But I was not able to change this colur.
    In the report attributes --> column attributes
    I tried already:
    1. Column Formating -- >CSS Style (bgcolor: red)
    2. Tabular Form Element --> Element Attributes (bgcolor: red)
    but nothing worked.
    Can anybody help me?
    I Use Oracle Apex 2.2.1 on 10gR2
    thank you in advance.
    Oliver

    in "Report Attributes" select the column to move to the "Column Attributes" page. In the "Element Attributes" field under the "Tabular Form Element" region enter
    style="background-color:red;"
    I will also check if there is a way to do this via the template and post here again
    edit:
    in your template definition, above the template, enter the following:
    < STYLE TYPE="text/css" >
    .class INPUT {background-color:red;}
    < /STYLE >
    (remove the spaces after the < and before the >)
    change "class" to the class that the template is calling
    (I'm using theme 9, the table has: class="t9GCCReportsStyle1" so I would enter t9GCCReportsStyle1)
    A side-effect of using this second version is that ALL input types will have a red background color--checkboxes, input boxes, etc.
    Message was edited by:
    TheJosh

  • How can i set the different colors for a different group ui elements

    Hi All,
                  I Created a View Container in that i crated 2 views. In first view i created a group and in second
    view also i created a group. I want to set The First view group header colour as Golden colour and for second view group heder colour as Green colour. Please any one help me on this.
    Thanks&Regards,
    Bhargava.

    Dear GLM,
                         i got that. while creating the theme, in Complex Elements select the group element and  set the primary group header colour to golden and secondary group Header colour to Green and in ur webdynpro application set the Group Design property as Primary Color for which group u want to set the Golden color and set the Group Design property as Secondary Color for which group u want to set the Green color.
    Thanks&Regards,
    Bhargava.

  • How to set the cell size in a JFrame

    Hello. Is there any way of setting the cell size in a JFrame. The reason why I want to set the cell size is that I want to be sure of their location that when I am placing components on the JFrame. So is there any way of setting the cell size beforehand. Also for the following code.
    JFrame frame = new JFrame("Window");
    frame.setSize(100,100);is the size 100 by 100 is he size of the cell?

    smithbrian wrote:
    When I am placing a component on the grid I want to be sure the component is exactly where I place it. In order to do that I would need to know what is the size of the gird and how to change the size of the gird in the JFrame.What grid?? You're assuming that we know much more about your program than we actually do. We actually know zip. Please read this help site which will help you to avoid similar errors in posting questions here. It has helped me in the past: [smart questions|http://www.catb.org/~esr/faqs/smart-questions.html]

  • How do I set the background color of a page_item?

    I've been pasting "background-color:#5CD65C" in a number of places, like "HTML Table Cell Attributes" under the Label and the Element tabs, but get no results. Can anyone tell me how to set the background color of a cell, please?

    Hi Doug,
    Dynamic Actions is an alternative also, especially if it is conditional.
    Action Set Style
    Fire When Event Result Is True
    Style Name background-color
    Value #5CD65C
    Selection Type DOM Object
    DOM Object your item name
    Set your Condition Type and you have it.
    Jeff
    Edited by: jwellsnh on May 24, 2011 3:55 PM

  • Setting the series color of a bi beans graph based on the data values

    How do I conditionally set the series color of a bi beans graph based on the data values?
    I am using the following code to get the data values and set the series color:
    Graph gr=(Graph)CmdrDashboardP1_pres1.getView();
    DataAccess da=gr.getGraphModel().getDataAccess();
    DataDirector dd=gr.getDataDirector();
    DataMap dm=dd.getDataMap();
    int re=dd.ROW_EDGE;
    int ce=dd.COLUMN_EDGE;
    Object val=da.getValue(re,ce,dm.DATA_TYPE);
    int seriesCount=da.getEdgeCurrentSlice(DataDirector.ROW_EDGE);
    if (val <=45.0)
    gr.getSeries().setColor(new Color(255,0,0),seriesCount);
    I get a NullPointerException from the line of code "Object val=da.getValue(re,ce,dm.DATA_TYPE)." I have tried the code with DATA_UNFORMATTED as well, but get the same exception. When I print the DataMap value of dm the results are [dataUnformatted, dataViewFormat, value, dataIsTotal, dataType].
    Also, I get the error "method <= (java.lang.Object,double) not found in class _CmdrDashboardP1" from the "if (val <=45.0)" code.
    Thanks for any assistance

    How do I conditionally set the series color of a bi beans graph based on the data values?
    I am using the following code to get the data values and set the series color:
    Graph gr=(Graph)CmdrDashboardP1_pres1.getView();
    DataAccess da=gr.getGraphModel().getDataAccess();
    DataDirector dd=gr.getDataDirector();
    DataMap dm=dd.getDataMap();
    int re=dd.ROW_EDGE;
    int ce=dd.COLUMN_EDGE;
    Object val=da.getValue(re,ce,dm.DATA_TYPE);
    int seriesCount=da.getEdgeCurrentSlice(DataDirector.ROW_EDGE);
    if (val <=45.0)
    gr.getSeries().setColor(new Color(255,0,0),seriesCount);
    I get a NullPointerException from the line of code "Object val=da.getValue(re,ce,dm.DATA_TYPE)." I have tried the code with DATA_UNFORMATTED as well, but get the same exception. When I print the DataMap value of dm the results are [dataUnformatted, dataViewFormat, value, dataIsTotal, dataType].
    Also, I get the error "method <= (java.lang.Object,double) not found in class _CmdrDashboardP1" from the "if (val <=45.0)" code.
    Thanks for any assistance

Maybe you are looking for