TableView multiline cell

How can I do with a custom TableCellFactory a TableCell multiline and do the Rowhight changed dynamics. Or how can I calculate the height of the multiline label? It still gives me 0.

Edited by: 884604 the 12.09.2011 09:40

Ok. This can be achieved by using the 'Text' node in the table cell. Please check the code below.

TableColumn descCol = new TableColumn("Description");
descCol.setPrefWidth(150);
descCol.setCellValueFactory(new PropertyValueFactory("description"));
Callback cellFactory = new Callback() {
     @Override
     public TableCell call( TableColumn param) {
          final TableCell cell = new TableCell() {
               private Text text;
               @Override
               public void updateItem(Object item, boolean empty) {
                      super.updateItem(item, empty);
                      if (!isEmpty()) {
                        text= new Text(item.toString());
                        text.setWrappingWidth(140);
                           setGraphic(text);
                      }
               }
          };
          return cell;
     }
};
descCol.setCellFactory(cellFactory);

The important part is the width of the packaging for the text node.

text.setWrappingWidth(140);

Adjust the width of the package according to the width of your column.
I hope it will be useful to you.
Happy coding! :)

Tags: Java

Similar Questions

  • TableView Single Cell selection style

    Model selection TableView allows you to select individual cells in the table, but the default style highlights the entire line, regardless of the column that is selected on the line.

    I wonder what options are there to change this behavior so that the actual cell (row/column) highlighted instead of the whole line.

    Something like the cell $18,000 in the 'presentation of the Figure 1 Table' in https://wiki.openjdk.java.net/display/OpenJFX/TableView+User+Experience+Documentation

    Are you sure that you define the selection properly model?

        tableView.getSelectionModel () .setSelectionMode (SelectionMode.SINGLE);
        tableView.getSelectionModel () .setCellSelectionEnabled (true);

    A style like this should work:

    .table-view > .virtual stream > .clipped-container > .the > .table-line-cell > cell .table: selected {}

    -fx-border-color: red;

    }

  • How a TableView can iterate over the lines and get the cells?

    I need to iterate over all rows in a TableView without using events. I would like to get the total number of lines, TableRow and a cell of a TableColumn specified in the TableRow.

    Something like this:
    for(TableRow tableRow: tableView.getRows()){
        Cell cell = tableRow.getColumn(4).getCell();
        // do something to the cell 
    }
    Is this possible?

    Published by: Conzar on May 19, 2013 23:18

    However, the problem with the checkbox has been resolved so I don't need to iterate over the lines longer.

    Yes, don't use do not research to manage this is a much better solution, I just gave my search for a solution based on because you asked an iterative solution.

    Below (research) code produces no output.

    It works for me, I've included an example of executable, so you can try it.

    My guess is that you are not taking into account the fact that the research is just a glimpse of the cells of the table at a time in time.
    If you do a search for cell before show you the table on a stage, he's not coming back what it is because the cells are generated only on an as needed basis, and there is no need to generate all the cells before displaying the table on a stage.

    I get the following output on Win7 Java8b89:

    NumberedTableViewSample$2$1@344fe46[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@44187690[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@34618adc[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@61eb7609[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@50b006a1[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@307d4153[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@89b7483[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@70ce61fd[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@178969ad[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@e3149ea[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@3683d879[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@589e421f[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@7e26215b[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@69d59720[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1ad26ff1[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@32b058e4[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@582e254[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@261c4ebd[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@2cb9cfb[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@63c6fe00[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@16a98443[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@58247401[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@34dc3da4[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@78a62ea[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@29e0032e[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1781c971[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@18b2e479[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@4801295b[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@19e4c622[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@6a766d41[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@572aed5d[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@3bdf71a4[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@524c48c7[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@47b5a3ea[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@6ef8b38b[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@7fd2ee72[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@4994195c[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@49620450[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@246d8751[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@17e90472[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@def00[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@d1aa50a[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@2a7a58ba[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@2675cbd1[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@1c06ee08[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1685718d[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@6ba1936c[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@61ef15e5[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@6b2ace30[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@3c4d17c7[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1c3c9aad[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@27eadfe[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@3f83a064[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@579615f1[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@52a9271b[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1d221557[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@18947d9e[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@537eab32[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@687cc257[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@3d524978[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@44554375[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@22f89594[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@1f891aaf[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@bafcb2f[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@7ddeea8c[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@26023325[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@4b14700f[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@89eb58[styleClass=cell indexed-cell table-cell table-column]
    NumberedTableViewSample$2$1@6a55a4a6[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@7d95454d[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@375592eb[styleClass=cell indexed-cell table-cell table-column]
    TableColumn$1$1@7add3f35[styleClass=cell indexed-cell table-cell table-column]
    

    TestApp:

    import javafx.application.Application;
    import javafx.beans.property.ReadOnlyObjectWrapper;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.geometry.Insets;
    import javafx.scene.Group;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.VBox;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    public class NumberedTableViewSample extends Application {
    
        private TableView table = new TableView<>();
        private final ObservableList data =
            FXCollections.observableArrayList(
                new Person("Jacob", "Smith", "[email protected]"),
                new Person("Isabella", "Johnson", "[email protected]"),
                new Person("Ethan", "Williams", "[email protected]"),
                new Person("Emma", "Jones", "[email protected]"),
                new Person("Michael", "Brown", "[email protected]")
            );
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage stage) {
            Scene scene = new Scene(new Group());
            stage.setTitle("Table View Sample");
            stage.setWidth(470);
            stage.setHeight(500);
    
            final Label label = new Label("Address Book");
            label.setFont(new Font("Arial", 20));
    
            table.setEditable(true);
    
            TableColumn numberCol = new TableColumn("#");
            numberCol.setMinWidth(20);
            numberCol.setCellValueFactory(new Callback, ObservableValue>() {
              @Override public ObservableValue call(CellDataFeatures p) {
                return new ReadOnlyObjectWrapper(p.getValue());
              }
            });
    
            numberCol.setCellFactory(new Callback, TableCell>() {
              @Override public TableCell call(TableColumn param) {
                return new TableCell() {
                    @Override protected void updateItem(Person item, boolean empty) {
                        super.updateItem(item, empty);
    
                        if (this.getTableRow() != null && item != null) {
                          setText(this.getTableRow().getIndex()+"");
                        } else {
                          setText(null);
                        }
                    }
                };
              }
            });
            numberCol.setSortable(false);
    
            TableColumn firstNameCol = new TableColumn("First Name");
            firstNameCol.setMinWidth(100);
            firstNameCol.setCellValueFactory(
                    new PropertyValueFactory("firstName"));
    
            TableColumn lastNameCol = new TableColumn("Last Name");
            lastNameCol.setMinWidth(100);
            lastNameCol.setCellValueFactory(
                    new PropertyValueFactory("lastName"));
    
            TableColumn emailCol = new TableColumn("Email");
            emailCol.setMinWidth(200);
            emailCol.setCellValueFactory(
                    new PropertyValueFactory("email"));
    
            table.setItems(data);
            table.getColumns().addAll(numberCol, firstNameCol, lastNameCol, emailCol);
    
            final VBox vbox = new VBox();
            vbox.setSpacing(5);
            vbox.setPadding(new Insets(10, 0, 0, 10));
            vbox.getChildren().addAll(label, table);
    
            // this lookup set won't print anything as no cells have been generated.
            for (Node r: table.lookupAll(".table-row-cell")){
                for (Node c: r.lookupAll(".table-cell")){
                    System.out.println(c);
                }
            }
    
            ((Group) scene.getRoot()).getChildren().addAll(vbox);
            stage.setScene(scene);
            stage.show();
    
            // now the table has been initially rendered and it's initial set of cells generated,
            // the cells can be looked up.
            for (Node r: table.lookupAll(".table-row-cell")){
                for (Node c: r.lookupAll(".table-cell")){
                    System.out.println(c);
                }
            }
        }
    
        public static class Person {
    
            private final SimpleStringProperty firstName;
            private final SimpleStringProperty lastName;
            private final SimpleStringProperty email;
    
            private Person(String fName, String lName, String email) {
                this.firstName = new SimpleStringProperty(fName);
                this.lastName = new SimpleStringProperty(lName);
                this.email = new SimpleStringProperty(email);
            }
    
            public String getFirstName() {
                return firstName.get();
            }
    
            public void setFirstName(String fName) {
                firstName.set(fName);
            }
    
            public String getLastName() {
                return lastName.get();
            }
    
            public void setLastName(String fName) {
                lastName.set(fName);
            }
    
            public String getEmail() {
                return email.get();
            }
    
            public void setEmail(String fName) {
                email.set(fName);
            }
        }
    } 
    
  • Scope of column support in TableView

    I use JDK 8 and Javafx supports column or a line spanning the function? TableView documentation speaks Customization Visual TableView and cell covering. Examples of code for this will be of great use.

    Thank you.

    Spanning cells is not currently available in the JavaFX TableView control. There is already a feature request Jira for this here:

    http://JavaFX-JIRA.Kenai.com/browse/RT-24747

    Control of SpreadsheetView which is part of the open source ControlsFX project here may also interest you:

    http://www.controlsfx.org

    -Jonathan

  • APEX 5 interactive report data column alignment

    Hello

    I want to vertically align a column of APEX 5 interactive report data to the top of the cell (currently using the universal theme). By default, if a cell in the column in the file contains several lines (for example via the packaging), the other cells in the same row are centered compared to this in terms of vertical alignment multiline cell. I guess this can be managed with a set column expression shaped HTML, but I was not able to do so far.

    More generally how can it be implemented for all interactive reports / classics in a given application?

    I searched the forum etc. for similar positions, but not found a solution.

    See you soon,.

    Alan

    a_rintoul wrote:

    I want to vertically align a column of APEX 5 interactive report data to the top of the cell (currently using the universal theme). By default, if a cell in the column in the file contains several lines (for example via the packaging), the other cells in the same row are centered compared to this in terms of vertical alignment multiline cell. I guess this can be managed with a set column expression shaped HTML, but I was not able to do so far.

    It requires CSS rather than HTML, specifically the vertical-align property on the report table cells. For a single report, add a static region ID in the report area and include this style sheet in CSS Inline property page:

    #static-region-id .a-IRR-table td {
      vertical-align: top;
    }
    

    Leave aside the #static-region-id selector to apply the rule to each SORTING on a page.

    More generally how can it be implemented for all interactive reports / classics in a given application?

    Creating Styles of theme using the theme roller is the privileged and supported way to customize the appearance of the applications that use the universal theme.

    • Go to a page of IR in your application.
    • Click the Thème Roller on the developer toolbar.
    • Expand the CSS custom section.
    • Add this style custom rule:
    /* Interactive report cells */
    .a-IRR-table td,
    /* Standard report template cells: add selectors as required for other report templates */
    .t-Report-report td.t-Report-cell {
      vertical-align: top;
    }
    
    • The page will automatically preview changes.
    • Click on record under and type a name for the style of custom theme.
    • Topic close Roller
  • TableView: column widths computed for the contents of the cells and ignorant header

    Hallo,

    I use the tableview component. The header font size is higher then that of the cells. The problem is: the width of the column based on the cell that contains the longest string, and if the header-string has a length, then the header is truncated (it shows the points of suspension) and I need to change the width of column manually. How could I solve this problem? The easiest way would be to calculate the width of column on myself. I can't find any method in javafx, allowing to calculate the width of the string in pixels. Bat there is the FontMetrics class and the Graphics class, so it's easy to get the width in pixels. There pendants to this course in JavaFX?

    regarding

    Rafal Z

    It is indeed a problem valid and I had only a short time consuming solution. You can create a new instance of a few well-chosen javafx.scene.Node and apply the same style you have in your column header. You would then proceed with

    new Scene( new Group( YourNode ) );
    YourNode.applyCss( );
    YourColumn.setPrefWidth( YourNode.getLayoutBounds( ).getWidth( ) );
    

    You can get simple text width by using the javafx.scene.text.Text node, but it doesn't have some nice properties, you could use as padding.

  • Staining of cells TableView (new)

    Here is another question from staining of cells with a different plug.

    You have a TableView with three columns - category, inside and out. You add a blank line and then you start to edit the category column. When you have added a category you want to see a change in the color of the other cells two columns in the same row as the value of the category.

    Say if the category is "income" then the cell 'In' will become green and the 'Out' cell becomes red. The important point here is that these cells and the underlying domain object has not all the values associated with these columns again. The cells are empty and color change is to show the user where the value must be set for the category concerned (in the green cell ).

    After that the category value is committed a 'message' must therefore being propagated in the category for the current line (or the entire table) column to extricate himself. I tried to call the following methods of method 'commit()' of the category column, but none of them does raise a repaint:

    -getTableRow () .requestLayout ();

    -getTableRow (.updateTableView) (getTableView ())

    -getTableRow (.updateIndex) (getTableView () .selectionModelProperty () .get () .selectedIndexProperty () .get ());

    Any suggestion of work would be more then welcomed.

    Once paint it is triggered then incoming and outgoing of cells in a table column can take the current value of the underlying domain object category (say MyRecord) like this

    Registration of MyRecord = getTableView () .getItems () .get (getTableRow () .getIndex ());

    String category = row.getCategory ();

    and call the setStyle ("...") on the cell to change the color.

    Isn't time for a complete example now, but a strategy is:

    Set a rowFactory on the table view that returns a table row that falls into the category for its corresponding article. Update the class style (in JavaFX 2.2) or a State of alright (in Java 8) for the row in the table according to the category.

    Define a factory of cells for columns that statically defines a class on cells (for example 'in' and 'out').

    Use an external style sheet that looks like this:

    .table-row-cell.income .table-cell.in, .table-row-cell.expenditure .table-cell.out {
    -fx-background-color: green ;
    }
    
    .table-row-cell.income .table-cell.out, .table-row-cell.expenditure .table-cell.in {
    -fx-background-color: red ;
    }
    

    Here is an example of a row of table factory that manipulates the class style of the table cell. There is a link to a version that uses Java 8 alright States, that is much cleaner.

  • Please explain the guidelines related to the Platform.invokeLater and reuse of cell in tableview

    Hello

    1.

    Whenever I see tableview in JavaFX 2 + I see

    1. @Override   
    2. public Sub updateItem (last element of the string, Boolean void) { }
    3. Super .updateItem (element, empty);   
    4. if (item != null) {   
    5. button.setText (item);
    6. setGraphic (button);
    7. else
    8. (setGraphic)); /
    9. }
    10. }


    11. So basically, this method is called for each item in my list. Now my questions:

      + where element can be null? I have a list < String > so I don't see the point of what's going on

      + Why does the (null) setGraphic else? Or more if the item is null then null graphics also.


      I understand that this code is related to the loading of data that you highlight and reuse the cells, but it is not clear to me how it works. Please explain a little bit what happens and what makes the super.update done too if possible.


      2.


      1. Platform.runLater (new Runnable() { })
      2. public void run() { 
      3. final Node scrollBar = comboBox.lookup (".scroll-bar: vertical '); 
      4. scrollBar.setOpacity (0,); 
      5. }
      6. });

      In the present code why can't then I just directly called search & 'SetOpacity?

      I suppose that if I call it directly then it will run right in this moment. But if I wrap in this executable, then it is added to a queue of javafx, which will process my application when it can then perhaps do not stress the UI? But I don't know, can you tell if it is correct or not I think?

      I think it's very important for all developers who start with FX to understand the purpose of the present code.

      Thank you

      Desmond

      (When you have two questions, please post two separate interviews. It makes it easier for people to seek and find the answer in the future).

      So basically, this method is called for each item in my list.

      No, actually.

      The cells are just for rendering in your list items. If you have a lot of articles (or even a lot), so some scrolls off the screen, TableCells will not be created for them. In addition, the user scrolls around, the cells that represent the items that scroll off the screen can be used for items that are now visible. The updateItem (...) method will be called to update the cell to display the new item in this case.

      If relatively few cells is created. On the other hand, the updateItem (...) method can be called in quite frequently in certain circumstances as the cells are re-used.

      + where element can be null? I have a list of , so I don't see the point of what's going on

      There are two possibilities:

      1. The cell is empty. Note that in a table with very few objects, the table is filled with empty lines. Those are always represented by cells, which have the empty flag set to true and the item the null value property.
      2. NULL is a valid value perfectly put in (some implementations of) list. Therefore, it is possible that you really have null values in your list. In addition, in a TableView property to the value of the column for a given row can be set to null.

      + Why does the (null) setGraphic else?

      If the cell contained a non-null value before and is updated to represent a null value, then you will need to remove the graphic. (Otherwise you may find yourself with buttons in the empty lines, which is probably not what you want.) This can happen if the lines are removed, or possibly during scrolling like cells are reused (the latter is possible, but it is difficult to see what happens to implementation). In trees, the cells can become empty as nodes in the tree are reduced.

      What makes the super.update makes

      The default TableCell performs a lot of work. He calls the behavior by default until your custom implementation is called. This default behavior includes up-to-date of the item and empty properties to new values, saving listeners of the mouse to the selection behavior and editing behavior if the cell is editable, etc..

      It is not clear to me how it works

      It's not really supposed to be. It is object oriented programming: you're supposed to only rely on the feature (which it does) rather than implementing (how it does). This frees up developers to JavaFX to vary the implementation (to improve performance, for example) from one version to the other, as they did quite significantly from 2.2 JavaFX JavaFX 8. All you know is that some cells are created, they can be reused, and the updateItem (...) method will be called whenever the modification of the element in a particular cell. Which may be because the property that the cell is the changed view, either because the cell was re-used for another element. The cells can become empty due to reuse. No guarantees are made as to how and when reuse will occur. (Make these guarantees would greatly limit the ability of the JavaFX team to change things in the future)

      In the present code why can't then I just directly called search & 'SetOpacity?

      It's not easy without a context, but I guess that this code is in a (...) Platform.runLater to ensure that the nodes were posted on the screen.

      The problem is that research based on css will not succeed usually until a render pass is filed, which is always after the step was established, but can not be immediately after. The Platform.runLater (...) here forces the code to execute after all what is currently pending on the Thread of the FX Application.

    12. How to change the background color of a line when you have the selection of cells in tableview?

      I have a tableview and I chose the selection of cells. How can I change the background color of a line, if I select a cell?

      The usual example using:

      import javafx.application.Application;
      import javafx.beans.binding.Bindings;
      import javafx.beans.binding.BooleanBinding;
      import javafx.beans.property.SimpleStringProperty;
      import javafx.beans.property.StringProperty;
      import javafx.collections.FXCollections;
      import javafx.collections.ListChangeListener.Change;
      import javafx.collections.ObservableList;
      import javafx.collections.ObservableSet;
      import javafx.css.PseudoClass;
      import javafx.geometry.Insets;
      import javafx.scene.Group;
      import javafx.scene.Scene;
      import javafx.scene.control.Label;
      import javafx.scene.control.SelectionMode;
      import javafx.scene.control.TableColumn;
      import javafx.scene.control.TablePosition;
      import javafx.scene.control.TableRow;
      import javafx.scene.control.TableView;
      import javafx.scene.control.cell.PropertyValueFactory;
      import javafx.scene.layout.VBox;
      import javafx.scene.text.Font;
      import javafx.stage.Stage;
      
      public class RowHighlightedCellSelectionTableViewSample extends Application {
      
          public static void main(String[] args) {
              launch(args);
          }
      
          @Override
          public void start(Stage stage) {
              Scene scene = new Scene(new Group());
              scene.getStylesheets().add(getClass().getResource("selected-row-table.css").toExternalForm());
              stage.setTitle("Table View Sample");
              stage.setWidth(450);
              stage.setHeight(500);
      
              final Label label = new Label("Address Book");
              label.setFont(new Font("Arial", 20));
      
              final TableView table = new TableView<>();
              final ObservableList data =
                  FXCollections.observableArrayList(
                      new Person("Jacob", "Smith", "[email protected]"),
                      new Person("Isabella", "Johnson", "[email protected]"),
                      new Person("Ethan", "Williams", "[email protected]"),
                      new Person("Emma", "Jones", "[email protected]"),
                      new Person("Michael", "Brown", "[email protected]")
              );
      
              table.getSelectionModel().setCellSelectionEnabled(true);
              table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
      
              final PseudoClass selectedRowPseudoClass = PseudoClass.getPseudoClass("selected-row");
              final ObservableSet selectedRowIndexes = FXCollections.observableSet();
              table.getSelectionModel().getSelectedCells().addListener((Change change) -> {
                  selectedRowIndexes.clear();
                  table.getSelectionModel().getSelectedCells().stream().map(TablePosition::getRow).forEach(row -> {
                      selectedRowIndexes.add(row);
                  });
              });
      
              table.setRowFactory(tableView -> {
                  final TableRow row = new TableRow<>();
                  BooleanBinding selectedRow = Bindings.createBooleanBinding(() ->
                          selectedRowIndexes.contains(new Integer(row.getIndex())), row.indexProperty(), selectedRowIndexes);
                  selectedRow.addListener((observable, oldValue, newValue) ->
                      row.pseudoClassStateChanged(selectedRowPseudoClass, newValue)
                  );
                  return row ;
              });
      
              TableColumn firstNameCol = new TableColumn<>("First Name");
              firstNameCol.setMinWidth(100);
              firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
      
              TableColumn lastNameCol = new TableColumn<>("Last Name");
              lastNameCol.setMinWidth(100);
              lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
      
              TableColumn emailCol = new TableColumn<>("Email");
              emailCol.setMinWidth(200);
              emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
      
              table.setItems(data);
              table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
      
              final VBox vbox = new VBox();
              vbox.setSpacing(5);
              vbox.setPadding(new Insets(10, 0, 0, 10));
              vbox.getChildren().addAll(label, table);
      
              ((Group) scene.getRoot()).getChildren().addAll(vbox);
      
              stage.setScene(scene);
              stage.show();
          }
      
          public static class Person {
      
              private final StringProperty firstName;
              private final StringProperty lastName;
              private final StringProperty email;
      
              private Person(String fName, String lName, String email) {
                  this.firstName = new SimpleStringProperty(fName);
                  this.lastName = new SimpleStringProperty(lName);
                  this.email = new SimpleStringProperty(email);
              }
      
              public String getFirstName() {
                  return firstName.get();
              }
      
              public void setFirstName(String fName) {
                  firstName.set(fName);
              }
      
              public StringProperty firstNameProperty() {
                  return firstName ;
              }
      
              public String getLastName() {
                  return lastName.get();
              }
      
              public void setLastName(String fName) {
                  lastName.set(fName);
              }
      
              public StringProperty lastNameProperty() {
                  return lastName ;
              }
      
              public String getEmail() {
                  return email.get();
              }
      
              public void setEmail(String fName) {
                  email.set(fName);
              }
      
              public StringProperty emailProperty() {
                  return email ;
              }
          }
      }
      

      And then the selected line - table.css:

      .table-line-cell: {selected row

      -fx-background-color: lightskyblue;

      }

    13. How can I select multiple cells in tableview with javafx only with the mouse?

      I have an application with a tableview in javafx and I want to select more than one cell only with the mouse (something like the selection that exists in excel). I tried with setOnMouseDragged but I cant'n do something because the selection only returns the cell from which the selection started. Can someone help me?

      For events of the mouse to be propagated to other than the node in which nodes the drag started, you must activate a 'full-drag-release press gesture' by calling startFullDrag (...) on the original node. (For more details, see the Javadocs MouseEvent and MouseDragEvent .) You can register for MouseDragEvents on cells of the table in order to receive and process these events.

      Here's a simple example: the user interface is not supposed to be perfect, but it will give you the idea.

      import java.util.Arrays;
      
      import javafx.application.Application;
      import javafx.beans.property.SimpleStringProperty;
      import javafx.collections.FXCollections;
      import javafx.collections.ObservableList;
      import javafx.event.EventHandler;
      import javafx.geometry.Insets;
      import javafx.scene.Group;
      import javafx.scene.Scene;
      import javafx.scene.control.Label;
      import javafx.scene.control.SelectionMode;
      import javafx.scene.control.TableCell;
      import javafx.scene.control.TableColumn;
      import javafx.scene.control.TableView;
      import javafx.scene.control.cell.PropertyValueFactory;
      import javafx.scene.input.MouseDragEvent;
      import javafx.scene.input.MouseEvent;
      import javafx.scene.layout.VBox;
      import javafx.scene.text.Font;
      import javafx.stage.Stage;
      import javafx.util.Callback;
      
      public class DragSelectionTable extends Application {
      
          private TableView table = new TableView();
          private final ObservableList data =
              FXCollections.observableArrayList(
                  new Person("Jacob", "Smith", "[email protected]"),
                  new Person("Isabella", "Johnson", "[email protected]"),
                  new Person("Ethan", "Williams", "[email protected]"),
                  new Person("Emma", "Jones", "[email protected]"),
                  new Person("Michael", "Brown", "[email protected]")
              );
      
          public static void main(String[] args) {
              launch(args);
          }
      
          @Override
          public void start(Stage stage) {
              Scene scene = new Scene(new Group());
              stage.setTitle("Table View Sample");
              stage.setWidth(450);
              stage.setHeight(500);
      
              final Label label = new Label("Address Book");
              label.setFont(new Font("Arial", 20));
      
              table.setEditable(true);
      
              TableColumn firstNameCol = new TableColumn<>("First Name");
              firstNameCol.setMinWidth(100);
              firstNameCol.setCellValueFactory(
                      new PropertyValueFactory("firstName"));
      
              TableColumn lastNameCol = new TableColumn<>("Last Name");
              lastNameCol.setMinWidth(100);
              lastNameCol.setCellValueFactory(
                      new PropertyValueFactory("lastName"));
      
              TableColumn emailCol = new TableColumn<>("Email");
              emailCol.setMinWidth(200);
              emailCol.setCellValueFactory(
                      new PropertyValueFactory("email"));
      
              final Callback, TableCell> cellFactory = new DragSelectionCellFactory();
              firstNameCol.setCellFactory(cellFactory);
              lastNameCol.setCellFactory(cellFactory);
              emailCol.setCellFactory(cellFactory);
      
              table.setItems(data);
              table.getColumns().addAll(Arrays.asList(firstNameCol, lastNameCol, emailCol));
      
              table.getSelectionModel().setCellSelectionEnabled(true);
              table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
      
              final VBox vbox = new VBox();
              vbox.setSpacing(5);
              vbox.setPadding(new Insets(10, 0, 0, 10));
              vbox.getChildren().addAll(label, table);
      
              ((Group) scene.getRoot()).getChildren().addAll(vbox);
      
              stage.setScene(scene);
              stage.show();
          }
      
          public static class DragSelectionCell extends TableCell {
      
              public DragSelectionCell() {
                  setOnDragDetected(new EventHandler() {
                      @Override
                      public void handle(MouseEvent event) {
                          startFullDrag();
                          getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                      }
                  });
                  setOnMouseDragEntered(new EventHandler() {
      
                      @Override
                      public void handle(MouseDragEvent event) {
                          getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                      }
      
                  });
              }
              @Override
              public void updateItem(String item, boolean empty) {
                  super.updateItem(item, empty);
                  if (empty) {
                      setText(null);
                  } else {
                      setText(item);
                  }
              }
      
          }
      
          public static class DragSelectionCellFactory implements Callback, TableCell> {
      
              @Override
              public TableCell call(final TableColumn col) {
                  return new DragSelectionCell();
              }
      
          }
      
          public static class Person {
      
              private final SimpleStringProperty firstName;
              private final SimpleStringProperty lastName;
              private final SimpleStringProperty email;
      
              private Person(String fName, String lName, String email) {
                  this.firstName = new SimpleStringProperty(fName);
                  this.lastName = new SimpleStringProperty(lName);
                  this.email = new SimpleStringProperty(email);
              }
      
              public String getFirstName() {
                  return firstName.get();
              }
      
              public void setFirstName(String fName) {
                  firstName.set(fName);
              }
      
              public String getLastName() {
                  return lastName.get();
              }
      
              public void setLastName(String fName) {
                  lastName.set(fName);
              }
      
              public String getEmail() {
                  return email.get();
              }
      
              public void setEmail(String fName) {
                  email.set(fName);
              }
          }
      
      }
      
    14. TableView: How to show that a line of a cell contains a multi-line String using «...» »

      Hello

      I am currently working with a TableView. While I'm quite fine with the behavior of the component displaying «...» "at the end of a string that would be otherwise too long, I don't know a way to do the same thing when a channel is on more than one line...

      I already understood how to specify the height of a line by using "setFixedCellSize" so that the lines are always a high line. However, I find it embarrassing not to show «...» "to inform the user that there is more than one line of text that could let her think that there is nothing more than a line.

      Is there a way to solve the problem other that manually add «...» "every time a line separator is located?

      Thanks in advance,

      Xavier G.

      I managed to find a way to fix my problem by using the cellFactory and substituting updateItem (the called function every time the cell must be returned)

      @Override

      protected void updateItem (Object, object, boolean selected)

      {

      super.updateItem (object, selected);

      If (item is nothing)

      {

      setGraphic (null);

      setText (null);

      }

      on the other

      {

      setText (object.toString().split("\\n|\\r")) [0] + '... ») ; This line does it all

      }

      }

      }

      I post this response to the case wherever it someone else might save time

      I'm not sure it's the cleaner way to solve the problem however.

    15. How can I customize the height of row or a cell in TableView?

      Hi all


      For example, title. And, if it is possible, if the rows in the table rendered in a TableView may have different line heights?

      Thank you!

      Jason

      Set the preferred height of the cell returned by your custom cell factory.

    16. Cell TableView coloring on updates - realizing if sort happened

      I'm doing has highlighted cells (in color) in a TableView whenever they are updated. My solution is based on the implementation of cell factories and use Animation (mounting) control cell background opacity - it works very well: whenever a cell value is updated, the background changes color, then fades away well.

      The problem is, that if the table is sorted by clicking a column header, the underlying list is changed (of course), and the GUI level, it is also understood as a change and depending on the circumstances by cell (I flash a cell if its new value is different from the previous), several cells show an update unnecessarily (flashing).

      I wonder how I could eliminate if a cell has been updated due to a 'real' update (an element has been updated) of the case when the list sort column and/or the order has been changed? I thought to catch the event of sorting (by adding an InvalidationListener to the sort order list) and ignore the updates, while it is underway, but I can't really know when it's over. I bet at the GUI level, there is no way to determine the reason, so I need a deeper understanding...

      Thanks for the tips.

      Register a listener for change with the appropriate property to change the highlight color for the cell according to the case. You need to do a bit of work to make sure that the listener is registered and non-registered as appropriate that the cell is reused for the different table elements: the trick is to use

      Bindings.Select (tableRowProperty (), "point")

      to get an observable of the current value of the line.

      Update:

      Well, the previous example did not work. For reasons I can't understand, after sorting (or scroll, in fact), the evil cell became the property change notifications.

      So here's another strategy: keep track of the last known value of the cell line, and don't make the highlight is still called same rank value after the update. I prefer kind of the strategy described above, but I couldn't make it work.

      import java.text.NumberFormat;
      import java.util.Arrays;
      import java.util.List;
      import java.util.Random;
      
      import javafx.animation.FadeTransition;
      import javafx.animation.KeyFrame;
      import javafx.animation.Timeline;
      import javafx.application.Application;
      import javafx.beans.property.DoubleProperty;
      import javafx.beans.property.ReadOnlyStringProperty;
      import javafx.beans.property.ReadOnlyStringWrapper;
      import javafx.beans.property.SimpleDoubleProperty;
      import javafx.event.ActionEvent;
      import javafx.event.EventHandler;
      import javafx.geometry.Pos;
      import javafx.scene.Scene;
      import javafx.scene.control.Label;
      import javafx.scene.control.TableCell;
      import javafx.scene.control.TableColumn;
      import javafx.scene.control.TableView;
      import javafx.scene.control.cell.PropertyValueFactory;
      import javafx.scene.layout.BorderPane;
      import javafx.scene.layout.StackPane;
      import javafx.scene.paint.Color;
      import javafx.scene.shape.Rectangle;
      import javafx.stage.Stage;
      import javafx.util.Callback;
      import javafx.util.Duration;
      
      public class TableChangeHighlightExample extends Application {
      
       @Override
        public void start(Stage primaryStage) {
          final Random rng = new Random();
        final TableView table = new TableView<>();
        table.getItems().addAll(createData(rng));
      
        TableColumn symbolColumn = new TableColumn<>("Symbol");
        TableColumn priceColumn = new TableColumn<>("Price");
        symbolColumn.setCellValueFactory(new PropertyValueFactory("symbol"));
        priceColumn.setCellValueFactory(new PropertyValueFactory("price"));
        priceColumn.setCellFactory(new Callback, TableCell>() {
            @Override
            public TableCell call(TableColumn table) {
              return new StockPriceCell();
            }
        });
        table.getColumns().addAll(Arrays.asList(symbolColumn, priceColumn));
      
        Timeline changeStockPricesRandomly = new Timeline(new KeyFrame(Duration.seconds(2), new EventHandler() {
          @Override
          public void handle(ActionEvent event) {
            StockValue stockToChange = table.getItems().get(rng.nextInt(table.getItems().size()));
            double changeFactor = 0.9 + rng.nextInt(200) / 1000.0 ;
            double oldPrice = stockToChange.getPrice();
            double newPrice = oldPrice * changeFactor ;
      //     System.out.println("Changing price for "+stockToChange+" to "+newPrice);
            stockToChange.setPrice(newPrice) ;
          }
        }));
        changeStockPricesRandomly.setCycleCount(Timeline.INDEFINITE);
        changeStockPricesRandomly.play();
      
        BorderPane root = new BorderPane();
        root.setCenter(table);
        primaryStage.setScene(new Scene(root, 300, 400));
        primaryStage.show();
        }
      
        private List createData(Random rng) {
          return Arrays.asList(
            new StockValue("ORCL", 20.0 + rng.nextInt(2000)/100.0),
            new StockValue("AAPL", 300.0 + rng.nextInt(20000)/100.0),
            new StockValue("GOOG", 500.0 + rng.nextInt(100000)/100.0),
            new StockValue("YHOO", 20.0 + rng.nextInt(2000)/100.0),
            new StockValue("FB", 20.0 + rng.nextInt(1000)/100.0)
          );
        }
      
        public static void main(String[] args) {
        launch(args);
        }
      
        public static class StockPriceCell extends TableCell {
          private static final Color INCREASE_HIGHLIGHT_COLOR = Color.GREEN ;
          private static final Color DECREASE_HIGHLIGHT_COLOR = Color.RED ;
          private static final Duration HIGHLIGHT_TIME = Duration.millis(500);
      
          private static final NumberFormat formatter = NumberFormat.getCurrencyInstance();
      
          private final Label priceLabel ;
          private final Rectangle overlayRectangle ;
          private StockValue lastRowValue ;
      
          public StockPriceCell() {
            overlayRectangle = new Rectangle();
            overlayRectangle.setFill(Color.TRANSPARENT);
            overlayRectangle.widthProperty().bind(this.widthProperty().subtract(8));
            overlayRectangle.heightProperty().bind(this.heightProperty().subtract(8));
            overlayRectangle.setMouseTransparent(true);
      
            this.priceLabel = new Label();
            priceLabel.setMaxWidth(Double.POSITIVE_INFINITY);
            priceLabel.setAlignment(Pos.CENTER_RIGHT);
            StackPane pane = new StackPane();
            pane.getChildren().addAll(overlayRectangle, priceLabel);
            setGraphic(pane);
          }
      
          @Override
          protected void updateItem(Double price, boolean empty) {
            Double oldPrice = getItem();
            super.updateItem(price, empty);
            StockValue currentRowValue = null ;
            if (getTableRow()!=null) {
              currentRowValue = (StockValue) getTableRow().getItem();
            }
            if (empty) {
              priceLabel.setText(null);
            } else {
              priceLabel.setText(formatter.format(price));
              if (price != null && oldPrice != null && currentRowValue == lastRowValue) {
                if (price.doubleValue() > oldPrice.doubleValue()) {
                  overlayRectangle.setFill(INCREASE_HIGHLIGHT_COLOR);
                } else if (price.doubleValue() < oldPrice.doubleValue()) {
                  overlayRectangle.setFill(DECREASE_HIGHLIGHT_COLOR);
                }
                FadeTransition fade = new FadeTransition(HIGHLIGHT_TIME, overlayRectangle);
                fade.setFromValue(1);
                fade.setToValue(0);
                fade.play();
              }
            }
            lastRowValue = currentRowValue ;
          }
        }
      
       public static class StockValue {
          private final ReadOnlyStringWrapper symbol ;
          private final DoubleProperty price ;
          public StockValue(String symbol, double price) {
            this.symbol = new ReadOnlyStringWrapper(this, "symbol", symbol);
            this.price = new SimpleDoubleProperty(this, "price", price);
          }
          public final ReadOnlyStringProperty symbolProperty() {
            return symbol.getReadOnlyProperty();
          }
          public final String getSymbol() {
            return symbol.get();
          }
          public final DoubleProperty priceProperty() {
            return price ;
          }
          public final double getPrice() {
            return price.get();
          }
          public final void setPrice(double price) {
            this.price.set(price);
          }
          @Override
          public String toString() {
            return symbol.get() + " : " + price.get() ;
          }
        }
      }
      

      Post edited by: James_D

    17. Impossible to select a cell specific tableview?

      I want to choose a particular cell of tableview.

      so my code is

      table.getSelectionModel (). Select (1, lastNameCol);

      where 1 is the row index

      and

      lastNameCol is TableColumn

      Please see http://www.pixhost.org/show/3301/12128778_cellselect.png snap

      If you see the wink from above link then you will come to know this line that no 2 are selected, but I expect to be select only the cells 'Johnson '.

      I don't know no is this javafx bug or am I wrong?

      I also tried in new construction javafx2.2

      Please help me

      You must change the selection type cell, rather than the default line-oriented mode. Refer to the following API on TableViewSelectionModel:

      http://docs.Oracle.com/JavaFX/2/API/JavaFX/scene/control/TableView.TableViewSelectionModel.html#setCellSelectionEnabled%28boolean%29

      After changing this, your code works perfectly.

      -Jonathan

    18. Select the full column in TableView on click in the cell

      Hello

      I need a dialog where the user can select a column to use the data in columns later in the process.

      The data in the table are read-only.

      bat, I would simply call

      jTable.setColumnSelectionAllowed (true);
      jTable.setRowSelectionAllowed (false);

      But how have I received the same behavior in JavaFX-8 as with this swing-NBS?

      public class TableSelectTest {
          public static void main(String[] args) {
              TableModel myModel = new DefaultTableModel(5, 5) {
      
                  @Override
                  public boolean isCellEditable(int row, int column) {
                      return false;
                  }
      
                  @Override
                  public Object getValueAt(int row, int column) {
                      return String.format("%s-%s", Character.valueOf((char) (0x41
                              + row)), column);
                  }
      
              };
              JTable jTable = new JTable(myModel);
              jTable.setColumnSelectionAllowed(true);
              jTable.setRowSelectionAllowed(false);
              while (4 > jTable.getSelectedColumn()) {
                  JOptionPane.showMessageDialog(null, jTable, "select a column", JOptionPane.QUESTION_MESSAGE);
                  JOptionPane.showMessageDialog(null,
                          String.format("column %s selected", jTable.getSelectedColumn()),
                          "result",
                          JOptionPane.INFORMATION_MESSAGE);
              }
          }
      }
      
      

      Good bye

      DPT

      Fotunately adding a Checkbox job to a FX-Table header is pretty easy, it's my work around my problem.

      Good bye

      DPT

Maybe you are looking for