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

Similar Messages

  • 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

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

  • Why is my calendar not holding the correct color.  I have reset the color of a particular calendar posting and within second the color reverts to purple.

    Why is my calendar not holding the set color.  I have reset the color of a particular calendar and within seconds it reverts back to purple.  I am using ICloud on a calander linked to my IPhone and IPad.

    set them at icloud.com on a computer.  its a work around.  Peace, Clyde

  • 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 to programmatically change the cell color of an ADF table ?

    Hi all,
    I have an ADF table with some fields on it. Depending on the value of a field named, say, "F1", I would like to change its background color.
    So far I can change the field color with this EL expression inside the InlineStyle table column property:
    font-size:medium; background-color:#{viewScope.myBean.setColor};
    where setColor is a bean function, in where I access the field "F1" via binding, parse its value, and return the right value - so far, so good.
    The bad thing is, the InlineStyle affects that field in all the rows of the table, while I would like to change only the field in the rows, which have that specific value in it.
    So for example having the rows:
    F1
    abc#1 ----> currently selected row
    cde#2
    efg#3
    I want to change the background color to all the F1 fields which have a "1" after the '#' and let the other "F1" row cells background color stay unchanged.
    But as you can imagine, the InlineStyle affect the "F1" background color in all the rows (assuming that the first row of the table is selected).
    So the question: how to access a single cell of a row in an ADF table, and programmatically change its background color ?
    So far I can iterate through the ADF table with:
    BindingContext bindingctx = BindingContext.getCurrent();
    BindingContainer bindings = bindingctx.getCurrentBindingsEntry();
    DCBindingContainer bindingsImpl = (DCBindingContainer) bindings;
    DCIteratorBinding dciter = bindingsImpl.findIteratorBinding("aTableIterator");//access the iterator by its ID value in the PageDef file
    RowSetIterator rsi = dciter.getRowSetIterator();
    System.out.println("rsi getrowcount = " rsi.getRowCount());+
    Row row = null;
    +if (rsi.getRowCount() > 0) {+
    row = rsi.getCurrentRow();
    System.out.println("row attr = " Arrays.toString(row.getAttributeNames()));+
    System.out.println("class : " row.getAttribute("F1").getClass().toString());+
    +}+
    +while (rsi.hasNext()) {+
    row = rsi.next();
    System.out.println("row attr = " Arrays.toString(row.getAttributeNames()));+
    +}+
    Regards,
    Sergio.

    Hi,
    I mean a specific cell within a row.
    Here are two pictures that show an ADF table with two rows and some fields on it:
    https://skydrive.live.com/?cid=7D3084D8BF755808&id=7D3084D8BF755808!107&sc=documents#cid=7D3084D8BF755808&id=7D3084D8BF755808!107&sc=documents
    bild_A is what I have, bild_B is what I would like. Note that:
    in bild_A the first row contain a yellow background color for the field F4 and an orange background color for the field F5. This is correct, because F4 has an "1" at the end of its string value, and F5 has a "3" at the end. So far so good.
    But the second row (again, bild_A) has also the fields F4 with yellow background color, and the field F5 with orange background color, even if the value in both fields is 0.
    What is should be, is shown in bild_B.
    The problem is that the solution provided affects all the cells of the column, while I need to change the background color of a single cell, and leave the other unchanged (see bild_B).
    I hope that clarify a bit :)
    Sergio.

  • ALV color priority:  The layout color or the cell color?

    I'm trying to assign an ALV at the cell level but it is not showing up.  I have specificed the column color at the layout level.  Does the layout level have color priority?

    Hi
    see the doc and do accordingly
    1. add one more field to ur final internal table say COLOR(4)
    2. in layout wa_layout-style_fname = 'COLOR'. " if its grid
    wa_layout-style_fieldname = 'COLOR'. "if its list
    3. read table itab index 3.
    itab-color = 'C410'.
    modify itab index 3
    4. see program SHOWCOLO for all color codes
    1. Add a field of data type CHAR(3) to the internal output table.
    2. Enter the color code in the appropriate field of the row to be colored in the internal
    output table:
    Code: 'Cxy'
    C = Color (all codes begin with 'C')
    x = color number ('1' - '9')
    y = highlight ('0' = off, '1' = on)
    3. Assign the internal output table color code field name to the IS_LAYOUT importing
    structure IS_LAYOUT-INFO_FIELDNAME field and pass this structure in the ALV call
    interface.
    To enable row coloring, you should add an additional field to your list data table. It should be of character type and length at least 4. This field will contain the color code for the row. So, let’s modify declaration of our list data table “gt_list”.
    you should fill the color code to this field. Its format will be the same as explained before at section C.6.3. But how will ALV Grid know that you have loaded the color data for the row to this field. So, you make it know this by passing the name of the field containing color codes to the field “INFO_FNAME” of the layout structure.
    e.g.
    ps_layout-info_fname = <field_name_containing_color_codes>. “e.g. ‘ROWCOLOR’
    You can fill that field anytime during execution. But, of course, due to the flow logic of screens, it will be reflected to your list display as soon as an ALV refresh occurs.
    You can color an entire row as described in the next section. However, this method is less time consuming.
    Coloring Individual Cells
    This is the last point about coloring procedures for the ALV Grid. The procedure is similar to coloring an entire row. However, since an individual cell can be addressed with two parameters we will need something more. What is meant by “more” is a table type structure to be included into the structure of the list data table. It seems strange, because including it will make our list data structure deep. But anyhow ALV Grid control handles this.
    The structure that should be included must be of type “LVC_T_SCOL”. If you want to color the entire row, this inner table should contain only one row with field “fname” is set to space, some color value at field “col”, “0” or “1” at fields “int” (intensified) and “inv” (inverse).
    If you want to color individual cells, then for each cell column, append a line to this inner table which also contains the column name at field “fname”. It is obvious that you can color an entire column by filling this inner table with a row for that column for each row in the list data table.
    Regards
    Anji

  • How to restrict the cell selection in JTable based on cell contents...

    Hi all,
    I have some problem related to table cell selection.
    I have a table that represets the calendar of some month and year.
    I have the restriction that at one time only one cell could be selected.
    Now i want the cell seletion like this,
    I want only those dates to be selected if that date is after 'today'.
    that is I want to restrict the selection of previous dates.
    how can i do this.
    I have overridden the table methods like this, still no use.
    table = new JTable(model) {
    setOpaque(false);
    setSurrendersFocusOnKeystroke(false);
    setRowHeight(20);
    JTableHeader header = getTableHeader();
    header.setOpaque(false);
    getTableHeader().setReorderingAllowed(false);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableHeader().setResizingAllowed(false);
    setCellSelectionEnabled(true);
    setFocusable(true);
    setBackground(new Color(247, 251, 255));
    setFont(newFont);
    public boolean isCellEditable(int row, int col) {
    return false;
    public boolean isCellSelected(int row, int col) {
    int r = getSelectedRow();
    int c = getSelectedColumn();
    String val = (String)getValueAt(r,c);
    Calendar cal = Calendar.getInstance();
    cal.set(currentYear+1900, month,Integer.parseInt(val));
    Date d = cal.getTime();
    Date currentDate = new Date();
    if (d.before(currentDate)) {
         return false;
    } else {
         return true;
    Someone please help...
    -Soni

    Try overriding the changeSelection(....) method of JTable.
    public void changeSelection(int row, int column, boolean toggle, boolean extend)
         if (d.after(currentDate)
              super.changeSelection(row, column, toggle, extend);
    }

  • Jtable in the cell of parent jtable

    hi,
    i wans to make jtable whose all cell's contains jtable and all of these jtables should dynamically get different datas .suppose i needs to create a parent 10*3 jtable,now all the 30 cells again contains jtable of 1*2 and all these 1*2 jtables contains different datas at runtime how can i do that plz sujjest me.

    Implement the TableCellRenderer interface to return a JTable.
    How to use tables: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Also worth asking yourself whether you really are better off with tables within tables, or if it's more appropriate to simply use a 10x6 table. Might be one, might be the other.

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

  • Changing the cells atribute in JTable

    Can You help me change the first row background & font color and to bold font in my table - and a question if I use swing must I import awt libraties?
    I've read that if smbd use swing than he should stay away from awt in term not to mix these two technologies - how do You know that You are using a SWING or an AWT library?
    Thanks in advance, smartduck
    here is my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Inventory2_17 {
    public JPanel buildUI() {
    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(50, //zgoraj
    50, //levo
    50, //spodaj
    50) //desno
    Object[][] data = {{"Item Num","Item Name","Units","On hand"},
    {"B1242","Bolt","Each","1000"},{"N1242","Nut","Each","1200"},{"W1242","Washer","Each","1150"},{"N2323","Nails","Lbs","2250"}};
    Object[] stolpci = {"0","1","2","3"};
    JTable table = new JTable(data,stolpci);
    table.setRowHeight(30);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              for (int i=0;i<stolpci.length;i++)     {
                   table.getColumnModel().getColumn(i).setMinWidth(180);
              panel.add(table);
    return panel;
    public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Congratulations!! You are a good student.");
    Inventory2_17 app = new Inventory2_17();
    frame.getContentPane().add(app.buildUI(), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

    Just read the tutorial, would you? Everything you need to know is there, it is pointless to ask uninformed questions here before you read it.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • Cell Colors in JTable

    Hello ! I have some Tables in my application (jTables) and I need change the color of some rows and cells of the tables, the rows are selected randomly and they can be uncontinues ...
    How can I do it ? Thanks.

    Have a look at:
    http://www2.gol.com/users/tame/swing/examples/

  • Change Cell Color of JTable-Please Help

    Hi All,
    I want to change the color of a Row in a JTable when i click on it. And After that when i click another row i want to retain this color and give another color to the second row.
    If somebody knows how to do this. Do Help
    Thanks in advance
    -Jeena

    Hi,
    thanks for the fast reply
    Using a TableCellRenderer i was able to give colors to the selected row. But when i click another row the color disappears.
    Thanks,
    Jeena

  • What exactly is the "cell factory?"

    So I've been seeing this term a lot on the forums, as well as http://docs.oracle.com/javafx/2/ui_controls/table-view.htm and on the ensemble, but I'm not 100% sure what it is.... It seems like just a method to set data into your tables, like the table model? Anyone have a more in depth explanation than the one in the docs, I would appreciate it!!!
    Thanks,
    ~KZ

    Cell factories create cells. A cell is a Labeled Node which contains some extra properties and methods for maintaining an editing and selection state and a link back to a cell value. Cells are used in a few places in JavaFX, for example in ListViews and TableViews, as well as TreeTables and ComboBoxes. The Cell is the visual representation (Node) which corresponds to a backing data item. The trick is that there is not necessarily a static one to one correspondence between cells and data values.
    Let's take an example. Here is an empty ListView in a Scene. When I run the app, it displays the ListView at it's preferred height, with 17 rows.
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.ListView;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    public class ListViewSample extends Application {
      @Override public void start(Stage stage) {
        ListView listView = new ListView();
        VBox layout = new VBox();
        VBox.setVgrow(listView, Priority.ALWAYS);
        layout.getChildren().addAll(listView);
        stage.setScene(new Scene(layout));
        stage.show();
      public static void main(String[] args) { launch(args); }
    }Each one of those 17 rows is empty. No Cell Factory has been set, yet you can see alternating light and dark shaded rows. Each one of these rows in the ListView corresponds to a Cell and each cell has been generated by the default ListView cell factory. When I drag the stage's bottom border to increase the size of the stage, the list view increases in size. When I drag the stage's bottom border to decrease the size of the stage, the list view decreases in size. When the list view increases in size, more rows are visible. Each of the new cells for the larger list view are generated by the cell factory on an as needed basis; i.e. the cells were not created when the app was first run but only created as there was a greater visible area available to the ListView in which the ListView could display more cells.
    Now everything is pretty boring so far. Let's add some data, using the following line of code:
    listView.setItems(FXCollections.observableArrayList("apple", "orange", "pear"));Now you will see the strings "apple", "orange" and "pear" rendered in the first three cells of the ListView again by using the default cell factory for the ListView. Again this is pretty boring.
    What we will do now is add some mutators which will change the observable list backing the list view in response to some user actions:
    import javafx.application.Application;
    import javafx.collections.FXCollections;
    import javafx.event.*;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    import java.util.Collections;
    import java.util.Comparator;
    public class ListViewSample extends Application {
      @Override public void start(Stage stage) {
        final ListView<String> listView = new ListView<>();
        listView.setItems(FXCollections.observableArrayList("apple", "orange", "pear"));
        ListViewSorter listViewSorter = new ListViewSorter(listView).invoke();
        VBox layout = new VBox(10);
        VBox.setVgrow(listView, Priority.ALWAYS);
        listView.setMinHeight(0);
        layout.getChildren().addAll(
            listView,
            HBoxBuilder
                .create()
                .spacing(10)
                .children(
                    guavaCreator(listView),
                    listViewSorter.getSorter(),
                    listViewSorter.getReverser()
                .build()
        stage.setScene(new Scene(layout));
        stage.show();
      private Button guavaCreator(final ListView<String> listView) {
        final Button guavatron = new Button("Add Guava");
        guavatron.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            listView.getItems().add("guava");
            guavatron.setDisable(true);
        return guavatron;
      public static void main(String[] args) { launch(args); }
      private class ListViewSorter {
        private final ListView<String> listView;
        private Button sorter;
        private Button reverser;
        public ListViewSorter(ListView<String> listView) {
          this.listView = listView;
        public Button getSorter() {
          return sorter;
        public Button getReverser() {
          return reverser;
        public ListViewSorter invoke() {
          sorter = new Button("Sort");
          sorter.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent actionEvent) {
              Collections.sort(listView.getItems());
          final Comparator<String> REVERSE_SORT = new Comparator<String>() {
            @Override  public int compare(String s1, String s2) {
              return -1 * s1.compareTo(s2);
          reverser = new Button("Reverse Sort");
          reverser.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent actionEvent) {
              Collections.sort(listView.getItems(), REVERSE_SORT);
          return this;
    }OK, now we have some extra buttons, the "Add guava" button will create a new item ("guava"), the "Sort" and "Reverse Sort", buttons will change the sort order of the backing list. Now to understand what happens behind the scenes when we use these buttons, let's take a look at the source code for the default list cell factory.
    new ListCell() {
       @Override public void updateItem(Object item, boolean empty) {
         super.updateItem(item, empty);
         if (empty) {
           setText(null);
           setGraphic(null);
         } else if (item instanceof Node) {
           setText(null);
           Node currentNode = getGraphic();
           Node newNode = (Node) item;
           if (currentNode == null || ! currentNode.equals(newNode)) {
             setGraphic(newNode);
         } else {
           setText(item == null ? "null" : item.toString());
           setGraphic(null);
    };This code is doing one of three things. If the list cell is empty, it sets the text and graphic to null, so you end up with a blank cell (the alternating light and dark grey bars are generated by the ListCell's parent setting differing style classes on alternate cells). If the item is a node, it sets the graphic to the node - this is the mechanism which allow you to place nodes directly in the backing list for the ListView and have the ListView display them OK. Otherwise a toString is called on the item to set the item's text (this is the case which is occurring for our simple example of Strings in the backing list).
    Now the important thing to note about the ListCell implementation is that the clever logic of translating the backing item for the cell to a visual representation is occurring in an updateItem call. This updateItem method is invoked by the JavaFX system on the ListCell whenever the backing item for the cell has been invalidated, for example the item has been edited, a new item added, or the items in the list have been reordered.
    So when somebody presses, the "Add Guava" button, a new ListCell is not created, instead updateItem is called on an already existing empty cell. This is because when we started the application, there was space for 17 rows, so 17 cells were already created, it is just that most of them were empty because we only had 3 items in the backing list for the ListView.
    Now, if we press one of the sort buttons to reorder the backing list, it will cause the existing list cells to become invalidated, and updateItem will be called on each of the cells according to the change permutations in the ObservableList. Note that as each item is updated, a new Labeled display node for the item is not created, instead the setText method is invoked which changes the text for the existing Labeled.
    There are a couple of extra cases to understand. Our backing list currently maxes out at 4 items. Let's say we drag the bottom of our stage up so that the available space for the ListView was made really small (e.g. only 2 rows high). In this case, you will two rows (cells) and a scrollbar you can use to scroll up and down. As you scroll up and down it seems that some rows are scrolling off the screen and some are scrolling on the screen. What is actually happening though is that the same two cells are remaining on screen and their contents being continually updated and replaced as backing items come in and out of view. This is the magic of how the ListView is able to achieve it's efficiency when dealing with potentially very large collections or collections where not all of the required data is available on the client at the current time. Instead of creating visual cells for all of the possible items which can be placed in the list, instead the ListView creates cells only for the visible items and updates the content of those cells on an as needed basis. This concept is known in the List Cell creators jargon as a Virtual Flow in a Virtualized control.
    OK, so that was a little more interesting, but there have been a lot of words so far, and no custom cell factory. This was partly on purpose - there is lot you can do with the default cell factory without needing to create your own custom cell factory.
    But sometimes you do actually want to create your own cell factory when you want fine control over the look or behaviour of the cells.
    Let's say you want to show each item in the list with a capitalized friendly name "Apple", "Orange" and "Pear" and an icon - a picture of the corresponding fruit. To do this you would create a cell factory - something that can produce the visual representation of these things from the corresponding data values.
    import javafx.application.Application;
    import javafx.collections.*;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.image.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class ListViewCustomCellFactorySample extends Application {
      ObservableMap<String, Image> iconMap = FXCollections.observableHashMap();
      @Override public void init() {
        iconMap.put(
          "apple", 
          new Image(
            "http://uhallnyu.files.wordpress.com/2011/11/green-apple.jpg",
            0, 32, true, true
        iconMap.put(
          "orange",
          new Image(
            "http://i.i.com.com/cnwk.1d/i/tim/2011/03/10/orange_iStock_000001331357X_540x405.jpg",
            0, 32, true, true
        iconMap.put(
          "pear",  
          new Image(
            "http://smoothiejuicerecipes.com/pear.jpg",
            0, 32, true, true
      @Override public void start(Stage stage) {
        final ListView<String> listView = new ListView<>();
        listView.setItems(FXCollections.observableArrayList("apple", "orange", "pear"));
        listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
          @Override public ListCell<String> call(ListView<String> stringListView) {
            return new LabeledIconListCell();
        VBox layout = new VBox(10);
        VBox.setVgrow(listView, Priority.ALWAYS);
        listView.setMinHeight(0);
        layout.getChildren().addAll(
            listView
        stage.setScene(new Scene(layout));
        stage.show();
      public static void main(String[] args) { launch(args); }
      private class LabeledIconListCell extends ListCell<String> {
        @Override protected void updateItem(String item, boolean empty) {
          super.updateItem(item, empty);
          if (item != null) {
            String friendlyText = item.toString();
            if (item.length() > 0) {
              friendlyText = item.substring(0, 1).toUpperCase() + item.substring(1);
            setText(friendlyText);
            setGraphic(
                StackPaneBuilder
                    .create()
                    .prefWidth(55)
                    .children(
                        new ImageView(
                            iconMap.get(item)
                    .build()
          } else {
            setText("");
            setGraphic(null);
    }Here what the cell factory has done is to check what value of the backing item for the cell is whenever that item has been updated, and set some customized label text and graphic representation for the cell.
    As a minor point, for efficiency, and because there are only a few of them, the required images are loaded and scaled up front so that they don't been to be reloaded every time the cell is updated with a different value (which if the image loading was within the cell's updateItem call could mean that the same image could potentially get loaded multiple times.
    My personal take on this is that it is powerful but complicated. Often people will gravitate towards using the complex ListView and TableView APIs when they don't necessarily need all of the functionality and virtualization efficiency capabilities that the virtualized controls offer. In many cases, simple layout mechanisms such VBoxes and Grids can be a better choice. However, if you have a need for the virtualized functions, then it's good to know that things like ListView and TableView are there if you can work out how to use them well in your case.
    Also note that JavaFX 2.2+ has numerous convenience methods for creating different kinds of cells which you may be able to use in standard cases to avoid some of the overhead in creating your own, for example the CheckBoxListCell, the ComboBoxListCell and the TextFieldListCell. And there are many more such simplifying higher level abstractions in the DataFX library.
    One other point worth observing is that if you have a list of mutatable objects, for example Person objects with a changable last name field, then you need to make the object an Observable object with an invalidation implementation if you want the updateItem call in the cell factory to be invoked automatically whenever the object is mutated.
    A cell factory and a cell value factory are different things, but that is probably a topic for a different post.
    I realize this was a round about and lengthy explanation - hopefully it served some purpose and helped to explain some of the mysteries of cell factories.
    http://docs.oracle.com/javafx/2/api/javafx/scene/control/Cell.html
    http://www.javafxdata.org
    http://docs.oracle.com/javafx/2/ui_controls/list-view.htm

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

Maybe you are looking for

  • How to get data  from an internal table in some other program

    I would like to get data from the internal table in the other program. When I using FM "LIST_FROM_MEMORY" to get the data, it doesn't work and the exception is not fount. If any special code need in the other program, like write data to memory . Many

  • Different execution of a Workbook

    Hi all, I'm facing a strange problem: on a 3.0b BW System I created a Workbook with 3 queries and some VBA. If I execute the workbook via User Menu it seems that the VBA doesn't work; if I execute the Workbook via Analyzer (via Business Explorer menu

  • Rearranging song order in Playlist - any help please?

    Folks, I have put together a playlist for a party and it is ~3 hrs long. I would like to move some of the songs around, perhaps listening tracks earlier, fast paced then dancing tracks later. I thought it would be easy enough to just drag tracks up o

  • Comment ajouter 1 image différente sur chaque face cube 3d avec Photoshop CS6

    Bonjour à tous. Est-ce que quelqu'un serait me dire comment faire pour appliquer une image différente sur chaque face d'un cube 3D avec Photoshop CS6? (Avec CS5 c'était facile avec le menu 3D, Nouveau filet à partir du calque, Filet prédéfini puis CU

  • 32 bit dissolve example not working (proxies not displaying, crashes)

    Hi We have just released a 64 bit Mac (cocoa) version of our plugin, which is going well.  But we've had requests for a 32 bit version, for use with PS Elements (versions 9/10/11). In Xcode, I duplicated the existing target, and set the architecture