[JavaFX] Editable TreeTableCells

Hello

I want to implement a TreeTableView where the cells in a column can be changed according to the other properties of the displayed object.

Bat I would control it via isCellEditable() method of TableModel.

What is the recommended way to make thin in JavaFX?

Here's a NBS that failed the behavior desired.

Could you please someone add the lines of bfing in there?

/*
 * //from www.java2s.com Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved. Use is
 * subject to license terms. This file is available and licensed under the following license: Redistribution
 * and use in source and binary forms, with or without modification, are permitted provided that the following
 * conditions are met: - Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer. - Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution. - Neither the name of Oracle nor the names of its contributors
 * may be used to endorse or promote products derived from this software without specific prior written
 * permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Arrays;
import java.util.List;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.stage.Stage;

public class FxMain extends Application {

    List<Employee> employees =
            Arrays.<Employee> asList(new Employee("Ethan Williams", "[email protected]", false),
                    new Employee("Emma Jones", "[email protected]", false),
                    new Employee("Michael Brown", "[email protected]", true),
                    new Employee("Anna Black", "[email protected]", true),
                    new Employee("Rodger York", "[email protected]", false),
                    new Employee("Susan Collins", "[email protected]", true));

    final TreeItem<Employee> root = new TreeItem<>(new Employee("Sales Department", "", false));

    public static void main(String[] args) {
        Application.launch(FxMain.class, args);
    }

    @Override
    public void start(Stage stage) {
        root.setExpanded(true);
        employees.stream().forEach((employee) -> {
            root.getChildren().add(new TreeItem<>(employee));
        });
        Scene scene = new Scene(new Group(), 400, 400);
        Group sceneRoot = (Group) scene.getRoot();

        TreeTableColumn<Employee, String> empColumn = new TreeTableColumn<>("Employee");
        empColumn.setPrefWidth(150);
        empColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue()
                .getValue()
                .nameProperty());

        TreeTableColumn<Employee, String> emailColumn = new TreeTableColumn<>("Email");
        emailColumn.setPrefWidth(190);
        emailColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue()
                .getValue()
                .emailProperty());

        TreeTableColumn<Employee, Boolean> superiorColumn = new TreeTableColumn<>("is Superior");
        superiorColumn.setPrefWidth(190);
        superiorColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, Boolean> param) -> {
            Employee employee = param.getValue().getValue();
            return employee.isSuperiorProperty();
        });
        superiorColumn.setCellFactory(col -> {
            // what to change here to get no checkbox for department entry??
            CheckBoxTreeTableCell<Employee, Boolean> checkBoxTreeTableCell = new CheckBoxTreeTableCell<>();
            // what to change here to deactivate checkbox for all superiors??
            checkBoxTreeTableCell.setEditable(false);
            return checkBoxTreeTableCell;
        });

        TreeTableView<Employee> treeTableView = new TreeTableView<>(root);
        treeTableView.setEditable(true);
        treeTableView.getColumns().setAll(empColumn, emailColumn, superiorColumn);
        sceneRoot.getChildren().add(treeTableView);
        stage.setScene(scene);
        stage.show();
    }

    public class Employee {

        private final SimpleStringProperty name;
        private final SimpleStringProperty email;
        private final BooleanProperty isSuperior;

        public Boolean getIsSuperior() {
            return isSuperior.get();
        }

        public void setIsSuperior(Boolean isSuperior) {
            this.isSuperior.set(isSuperior);
        }

        public SimpleStringProperty nameProperty() {
            return name;
        }

        public BooleanProperty isSuperiorProperty() {
            return isSuperior;
        }

        public SimpleStringProperty emailProperty() {
            return email;
        }

        private Employee(String name, String email, Boolean isSuperior) {
            this.name = new SimpleStringProperty(name);
            this.email = new SimpleStringProperty(email);
            this.isSuperior = new SimpleBooleanProperty(isSuperior);
        }

        public String getName() {
            return name.get();
        }

        public void setName(String fName) {
            name.set(fName);
        }

        public String getEmail() {
            return email.get();
        }

        public void setEmail(String fName) {
            email.set(fName);
        }

    }
}

Thank you

DPT

I want to implement a TreeTableView where the cells in a column can be changed according to the other properties of the displayed object.

Bat I would control it via isCellEditable() method of TableModel.

What is the recommended way to make thin in JavaFX?

Did not work with this but a simple web search for EXACTLY what you ask about "javafx editable tree table cell" produced the Oracle for TreeTableVIew API doc.

https://docs.Oracle.com/javase/8/JavaFX/API/JavaFX/scene/control/TreeTableView.html

Have you reviewed this API? He seems to have the info you need.

Edition

This control supports the online edition of values, and this section attempts to provide an overview of the available API and how you should use them.

First of all, the cells most often requires a different user interface than when a cell is not being edited. It is the responsibility of the Cell implementation used. For TreeTableView, it is strongly recommended that edition is per-TreeTableColumn , rather than per row , as more often than otherwise you want users to change the value of each column differently, and this approach allows for specific to each column publishers. It's your choice, if the cell is constantly in a State of change (for example, this is common for CheckBox of the cells), or to switch to a different user interface when editing begins (for example when a double click is received on a cell).

To find out what changes were requested on a cell, simply substitute the Cell.startEdit() method and update the cell text and graphic properties as appropriate (for example to set the null text and set the graphics to be a TextField ).

In addition, you must also override Cell.cancelEdit() to reset the user interface to its visual state of origin when the installation ends. In both cases, it is important that also ensure you that you call the method super for that cell to perform all the duties he has to do for his edit mode or its output.

Once your phone is in a State of change, the next thing you are probably interested is how to validate or cancel the current editing. It is your responsibility as a cell factory supplier. Your implementation of cell will know when the editing is complete, based on user input (for example when the user presses ESC or enter keys on their keyboard). When this happens, it is your responsibility to call Cell.commitEdit(Object) or Cell.cancelEdit() , as the case may be.

When you call Cell.commitEdit(Object) an event is fired to the TreeTableView, you can observe by adding a EventHandler via TreeTableColumn.setOnEditCommit(javafx.event.EventHandler) . Similarly, one can also observe edit events for edit start and edit cancel .

By default, the validation Manager TreeTableColumn edit is not null with a default manager who is trying to replace the property value for the item in the currently-being-edited line. It is able to do this as the Cell.commitEdit(Object) method is passed to the new value, and this should be transferred to the validation Manager change via the CellEditEvent , which is triggered. It is simply a matter of calling TreeTableColumn.CellEditEvent.getNewValue() to retrieve this value.

It is very important to note that if you call TreeTableColumn.setOnEditCommit(javafx.event.EventHandler) with your own EventHandler , then you will remove the default handler. Unless you then manage writeback in the property (or the relevant data source), nothing will happen. You can work around this by using the TableColumnBase.addEventHandler(javafx.event.EventType, javafx.event.EventHandler) method to add a TreeTableColumn.EDIT_COMMIT_EVENT EventType with desired EventHandler as the second argument. Using this method, you will not replace the default implementation, but you will be notified when a validation of the change has occurred.

I hope this summary answers some of the most frequently asked questions. Fortunately, JavaFX comes with a number of pre-built cell plants that handle all the requirements of editing on your behalf. You can find these cell factories pre-built in the javafx.scene.control.cell package.

Tags: Java

Similar Questions

  • Disable the line editable on TreeTableView

    Hello. I want to disable any cell editable in place of root root or sub on TreeTableView. Please check the code below. I disable the cell on updateItem() but does not work.

    import javafx.application.Application;
        import javafx.beans.property.ReadOnlyStringWrapper;
        import javafx.beans.property.SimpleStringProperty;
        import javafx.beans.property.StringProperty;
        import javafx.beans.value.ObservableValue;
        import javafx.scene.Scene;
        import javafx.scene.control.TextField;
        import javafx.scene.control.TreeItem;
        import javafx.scene.control.TreeTableCell;
        import javafx.scene.control.TreeTableColumn;
        import javafx.scene.control.TreeTableView;
        import javafx.scene.control.cell.TreeItemPropertyValueFactory;
        import javafx.scene.layout.HBox;
        import javafx.stage.Stage;
        import javafx.util.Callback;
        
        public class TreeTableExample extends Application {
        
            public static void main(String[] args) {
                Application.launch(args);
            }
        
            @Override
            @SuppressWarnings("unchecked")
            public void start(Stage stage) {
                
                HBox root = new HBox(createTable());
                Scene scene = new Scene(root);
                stage.setScene(scene);
                stage.setTitle("Using a TreeTableView");
                stage.show();
            }
        
            public TreeTableView createTable() {
        
                TreeTableView<Person> treeTable = new TreeTableView<>();
                treeTable.setEditable(true);
                
                Callback<TreeTableColumn<Person, String>, 
                    TreeTableCell<Person, String>> cellFactory
                        = (TreeTableColumn<Person, String> p) -> new EditingCell();
                
                TreeTableColumn<Person, String> firstName = new TreeTableColumn<>("First Name");
                firstName.setCellValueFactory(new TreeItemPropertyValueFactory<>("firstName"));
                firstName.setCellFactory(cellFactory);
                firstName.setOnEditCommit((TreeTableColumn.CellEditEvent<Person, String> event) -> {
                    if(event.getNewValue()!=null)
                        event.getRowValue().getValue().setFirstName(event.getNewValue());
                });
        
                TreeTableColumn<Person, String> lastName = new TreeTableColumn<>("Last Name");
                lastName.setCellValueFactory(new TreeItemPropertyValueFactory<>("lastName"));
                lastName.setCellFactory(cellFactory);
                lastName.setOnEditCommit((TreeTableColumn.CellEditEvent<Person, String> event) -> {
                    if(event.getNewValue()!=null)
                        event.getRowValue().getValue().setLastName(event.getNewValue());
                });
        
                treeTable.getColumns().addAll(firstName, lastName);
                TreeItem<Person> root = new TreeItem<>(new Person());
                for (int i = 0; i < 5; i++) {
                    root.getChildren().add(new TreeItem<>(new Person(String.valueOf(i),String.valueOf(i))));
                }
                treeTable.setRoot(root);
                return treeTable;
            }
        
            public class Person {
         
                private SimpleStringProperty firstName;
                private SimpleStringProperty lastName;
         
                public Person(){
                    this(null,null);
                };
         
                public Person(String fn, String ln){
                    firstName = new SimpleStringProperty(this, "firstName", fn);
                    lastName = new SimpleStringProperty(this, "lastName", ln);
    
                }
    
                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);
                }
        
            }
        
            class EditingCell extends TreeTableCell<Person, String> {
        
                private TextField textField;
        
                public EditingCell() {
                }
        
                @Override
                public void startEdit() {
                    if (!isEmpty()) {
                        super.startEdit();
                        createTextField();
                        setText(null);
                        setGraphic(textField);
                        textField.selectAll();
                    }
                }
        
                @Override
                public void cancelEdit() {
                    super.cancelEdit();
        
                    setText((String) getItem());
                    setGraphic(null);
                }
        
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
        
                    if (empty) {
                        setText(null);
                        setGraphic(null);
                    } else if (isEditing()) {
                        if(!getTreeTableView().getTreeItem(getIndex()).isLeaf())
                            setEditable(false);
                        if (textField != null) {
                            textField.setText(getString());
                        }
                        setText(null);
                        setGraphic(textField);
                    } else {
                        setText(getString());
                        setGraphic(null);
                    }
                }
        
                private void createTextField() {
                    textField = new TextField(getString());
                    textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
                    textField.focusedProperty().addListener(
                            (ObservableValue<? extends Boolean> arg0,
                                    Boolean arg1, Boolean arg2) -> {
                                if (!arg2) {
                                    commitEdit(textField.getText());
                                }
                            });
                }
        
                private String getString() {
                    return getItem() == null ? "" : getItem();
                }
            }
        }
    

    The problem is resolved. For more details in the method startEdit() to check the problem http://stackoverflow.com/questions/34548929/treetableview-disable-any-cell-in-parent-row/34567847#34567847 link does not check the editable property. In order to check before starting to edit the editable cell property

  • Can I use JavaFX in Swing without modifying source more?

    I had created a desktop in Java - Swing application.

    Now, I want to improve the GUI. So I had planned to upgrade to JavaFX.

    Can I use JavaFX in the swing and it is good to set up like this, rather than rewrite the program in JavaFx?

    Updated the Message was edited by: CyberBoy

    > Can I use JavaFX bat

    Yes, you can incorporate scenes of JavaFX in Swing and Swing components in JavaFX.

    See tutorial Oracle Interoperability JavaFX-Swing.

    > is good to be implemented like this, rather than rewrite the program in JavaFx

    Yes and no.  It depends on your application.

    Yes-online mix JavaFX and Swing is a good approach if you are integrating your application into a vast structure of swing established such as the NetBeans platform.

    No-online mix JavaFX and Swing is a bad approach, if you have an application that is relatively small and insignificant.

    Mixture of JavaFX and Swing makes your more complex program because:

    * You have to deal with different threading systems.

    * You have to deal with different toolkits to interface user.

    The JavaFX components looks do not match the appearance of the Swing components, if your application will look a little weird.

    * Swing apps will not support features like touch interfaces.

    Yes, the best to avoid mixing the two with the exception of special cases.  Valid reasons to mix the two (IMO) are:

    * You have a large, existing Swing code base, which completely makes the migration to JavaFX AND unreasonable

    * You want to use some specific features of JavaFX like WebView, multimedia playback in JavaFX, JavaFX graphics or 3D JavaFX which are not available in the swing.

    OR

    * You have a JavaFX application and the need to make use of some complex and Swing only existing component for which there is no counterpart in JavaFX (I think that for most people this will not be the case).

  • M3u8 sample Live Streaming HTTP plays don't not - stand-alone JavaFX 2.2.7 for java 1.6.0.32

    Hi all
    I searched high and low on the here and the wild wild web, but cannot find any support for my problem.

    I was testing my code of JavaFX2.2.7 Media Player based in a common Java 6 application when I discovered that HTTP Live Streaming does not seem to work.  I can play a local file of the format supported (Sintel trailor mp4 h264), but when I try and use a stream of Live HTTP instead, nothing plays. (for example http://download.oracle.com/otndocs/products/javafx/JavaRap/prog_index.m3u8 ).  I find myself with an empty drive and no exceptions or errors.

    private final static String MEDIA_URL = " " http://download.Oracle.com/otndocs/products/JavaFX/JavaRap/prog_index.m3u8 "; "

    Media = new Media (MEDIA_URL);

    MediaException ex = media.getError ();

    If (ex! = null) {}

    System.out.println ("Media error" + ex.getMessage ());

    } else {}

    System.out.println ("no media error");

    }

    Program the output to the console: "No. Media Error.

    I thought it was something wrong with my Player code, as a last resort, I went to JavaFX 2 - together and copied from the source and put it directly in my application and it ran... Unfortunately occurs the same result. The player runs, but simply shows a video window empty.  Controls are available, but the video plays.

    Based on the release notes for Java 2.2.7 that I was under the impression that HLS has been supported.  Am I incorrect?

    I can't upgrade to Java 7 because I'm firmly stuck with Java 1.6.0.32 for lack of project.

    Can anyone provide any assistance would be greatly appreciated.

    Post edited by: 2b18d6de-8200-4adc-a82a-88fc0451f448 I've updated for JavaFX 2.2.21 and this has not fixed the problem.  The result is exactly the same.  No exceptions, no error and no video...

    My Conclusion: Http Live Streaming does not seem to work with JavaFX 2.2.7 or 2.2.21.

    I've proved since the problem lies with 2.2.7 JavaFX and JavaFX 2.2.21, and that by using the new JavaFX comes with Jre7 solves the problem.

    I created a completely new and added that the JavaFX jars comes with 7 project JRE on my road to build.  I copied the code from http://download.oracle.com/otndocs/products/javafx/2/samples/Ensemble/index.html#SAMPLES/Media/Streaming%20Media%20Player and it works.

    So, I made a few changes on my original Java Eclipse project.

    Removed the build path:

    -C:\Program Files (x 86) \Oracle\JavaFX 2.2 Runtime\lib\jfxrt.jar

    -C:\Program Files (x 86) \Oracle\JavaFX 2.2 Runtime\lib\javaws.jar

    -C:\Program Files (x 86) \Oracle\JavaFX 2.2 Runtime\lib\plugin.jar

    -C:\Program Files (x 86) \Oracle\JavaFX 2.2 Runtime\lib\deploy.jar

    Added to build the path:

    -C:\Program Files (x86)\Java\jre7\lib\jfxrt.jar

    -C:\Program Files (x86)\Java\jre7\lib\javaws.jar

    -C:\Program Files (x86)\Java\jre7\lib\plugin.jar

    -C:\Program Files (x86)\Java\jre7\lib\deploy.jar

    Always using the 1.6.0_32 Java runtime, I ran my application and everything worked.

    Of course, this will be like a giant hack. I am disappointed by the release notes for JavaFX 2.2.7.

    NOTE: To export my request as an executable Jar, I also had to pull the related JavaFX ".dll" JRE 7 libraries and add them to the java.library.path (using script commands) before running the jar.

  • The JavaFX class hierarchy

    I have a question about the architecture of the JavaFX class. In fact, she should follow the pattern of composite named design looking for this http://en.wikipedia.org/wiki/Composite_pattern way somehow.

    However if I want to draw the composite model of the JavaFX package I find myself sort of this way:

    It seems that I can add children to buttons or labels. It was also possible with SWING. Why it has not been repaired? Is this a feature? On the other side window and the steps are now outside the model. In fact, they should be Parents I think. Why is it designed this way?

    Hope someone can enlighten me upward. Thank you very much for your answers in advance.

    > Actually it must follow the model of composite named design somehow.

    I think you are trying to simplify things.

    The JavaFX scene graph is a composite structure, but its design is subtler than a model composite vanilla.

    The basic concept of the presentation of JavaFX is a scene graph.  A scene contains a node tree, which forms the scene graph.  Any node that is not a leaf is a parent.  The parent base has a public method getChildrenUnmodifable and a protected getChildren method.  This means that you cannot add outwardly new nodes to a Parent unless you provide additional APIs.  The only thing that can add children to the mother is the Parent or the subclass of the Parent.  So, there's some cache information to go on.

    Some subclasses that act like editable containers expose their list of children to be publicly editable.  Usually, this is done by providing a public getChildren method.  A component, which is the root layout manager class, so in general, you can change the children of any pane layout is an example of such a class.  Conversely, if you have something that does not expose its getChildren method publicly, then external components cannot directly change the children of this thing.

    Region and the control are examples of nodes that extend from Parent and do not provide a public API getChildren.  As a button is a control, if you can not directly change her children through the public API.  The only way to change the control's children is to provide your own skin or to use additional modifier of APIs that control could provide.  For example, a button can have a chart, you can set the button and thus provide an arbitrary node or node tree to the button.  However, that is not quite the same Exhibitor getChildren button, because the graph is just a node, and layout in the button can be handled by the button through the display of the content of the button setting.

    OK, so JavaFX should not have had this complexity.  He could really go for a simpler approach where everything is a node, there are only a few types of nodes and HTML node types are not extensible example.  But he did not do this.  Instead, he went for a more detailed breakdown of the nodes of types, with each type supported by an object model providing State and functionality.  It's just a different approach.

    > It seems that I can add children to buttons or labels.

    Have you tried to do this by calling getChildren on one of them to get the list of children so you can change?  I bet that you could not do.

    > Window and steps are now outside the model.

    Yes, they are not part of the scene.

    All this is just a metaphor for the theatre.  Imagine that you go to the theater to watch Romeo and Juliet.  You sit in your Chair and watch the scene, the curtain has just unveiled the first scene.  The scene contains a background (a square of city to Verona in Italy), some accessories (swords and a fountain) and actors (nobles) who move and speak and go away.  These things in the scene are the nodes of the scene.  The curtain goes down and another scene appears, then again and another scene.  Finally, you arrive at the scene of the balcony where Romeo climbs the wall to join Juliette.  Whenever the curtain goes down, a new scene is assembled, and when the curtain rises the new scene appears.  All the time, the scene never changes.  This isn't a part of the scene.  The scene is the scaffolding in which many different scenes will appear.

  • JavaFX 2.0 crushed after the installation of the Netbeans 7.4 new and old projects imported into it.

    Hey there. I installed a new version of Netbeans and he asked me to import files, resources, etc. from the old version, so I agreed. However, when I open the old version that I realized all JavaFX projects contained errors. Then I open the properties of the project-> libraries section, it says broken reference: javafx.classpath.extension in the compile tab. I don't know why I'm dealing with this error, but I guess the reason is that I installed the latest version of Java with the new Netbeans import process caused what is happening. I would appreciate for any relpy. Thanks anyway

    EDIT: I'm impossible to import the screenshot, so you can see the same issue here

    Java - Broken reference: javafx.classpath.extension error after the new installation of Netbeans - stack overflows

    EDIT 2: Here you can also see the UPDATE: TXT file after you have installed the new Netbeans

    ==================================================

    JavaFXApplication1_1_Optimize update build script

    ==================================================

    Project build script file jfx - impl.xml in the nbproject subdirectory has not been recognised

    compatible with this version of NetBeans JavaFX supports the module. To ensure proper

    and all the features within this installation of NetBeans, the script file has been

    saved on jfx - impl_backup_3.xml and then updated to the State currently supported.

    FX Project build script auto-implementation to date can be triggered on the project to open after

    Updated NetBeans installation or manual changes in jfx - impl.xml. Please note that

    It is not recommended to change jfx - impl.xml to hand. Any customization of building code should

    be placed only in build.xml in the root directory of the project.

    Note: The automatic update mechanism can be disabled by setting the property

    JavaFX.Disable.AutoUpdate = true

    Automatic opening of the present notification when the project files are updated can be disabled by setting the property

    JavaFX.Disable.AutoUpdate.notification = true

    (in build.properties, private.properties ot project.properties).

    Note: The nbproject/jfx-impl_backup files * .xml and the nbproject/updated updated file. TXT

    are not used when you build the project, and can be freely removed.

    OK guys, I solved it with the way I opened a project new and imported complete documents to the new project.

  • Ways to restore an application JavaFx prev State when starting

    Usually what I do is write everything in xml when you close and then restart the application, I read this XML to set everything up as before.

    Is there a newer, more average Java FX version?

    XML is nice because you can edit in a text editor and it is relatively readable.  I never liked object streaming because it does not appear to age.  But I could be updated.  Database is too cumbersome to install.  But I've never tried an integrated db.

    Thank you

    > Usually what I do is write everything in xml when you close and then restart the application, I read this XML to set everything up as before. Is there a newer, more average Java FX version?

    JavaFX introduces almost nothing for it.  However, most of the means of the 'old' is always possible.  You're probably better off doing what you usually did before.

    Not new JavaFX, an alternative that isn't used, but a lot is the Java preferences API. I don't think that should make your easy editing in a test of the text editor, but if not, you might consider it.

    HTML5 local storage functions are implemented in Web for Java 8 mode.  There are no public Java API created to access the local storage used by WebView JavaFX HTML5 (I know), so to use it, you must create a WebView and access it's JavaScript API.  So, it would be a strange thing to do.

    If you have some sort of connected app, you can save the State if the cloud (I really hate that term) - things like s3 work well for storing things.

    > I never liked object streaming because it does not appear to age.

    It works even worse with JavaFX. JavaFX properties are often used in JavaFX applications to store the State of enforcement.  JavaFX properties are not serializable, as they do not implement the Serializable interface.

    > I've never tried an embedded db

    Embedded DBs such as H2 are very easy to use JavaFX.

    For some applications, persistent in a local database integrated state storage is a good option.  Depends on the app so considerably.

  • How to modify the data with dynamic TableView with dynamic columns in JAVAFX

    Today, it is the demo to display the data from the CSV to the custom class without doing DAT file on tableView in JavaFX 2.0. I call this TableView as dynamic TableView because the tableview automatically manages the columns and rows.
    My research on the editable on tableView, we have a custom of the class and apply it to tableView to show that this demo is > http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

    But in this case I can't do that because we don't know how many example of column with the csv file or .dat file... I want to make editable on this tableView in this case add TextField in the TableCell. How do custom class (because you don't have how column...) and so to do custom class then what thedesign of a custom for this case class?

    Could you please help me?

    It's the demo of code to display your csv or dat file in TableView

    private void getDataDetailWithDynamic() {
      tblView
    .getItems().clear();
      tblView
    .getColumns().clear();
      tblView
    .setPlaceholder(new Label("Loading..."));
      
    // @Override



      
    try {
           
    File aFile = new File(txtFilePath.getText());
           
    InputStream is = new BufferedInputStream(new FileInputStream(aFile));
           
    Reader reader = new InputStreamReader(is, "UTF-8");

           
    BufferedReader in = new BufferedReader(reader);

           
    final String headerLine = in.readLine();
           
    final String[] headerValues = headerLine.split("\t");
           
    for (int column = 0; column < headerValues.length; column++) {
                 tblView
    .getColumns().add(
                 createColumn
    (column, headerValues[column]));
           
    }

           
    // Data:

           
    String dataLine;
           
    while ((dataLine = in.readLine()) != null) {
                
    final String[] dataValues = dataLine.split("\t");
                
    // Add additional columns if necessary:
                
    for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
                      tblView
    .getColumns().add(createColumn(columnIndex, ""));
                
    }
                
    // Add data to table:
                
    ObservableList<StringProperty> data = FXCollections.observableArrayList();
                
    for (String value : dataValues) {
                     data
    .add(new SimpleStringProperty(value));
                
    }
                 tblView
    .getItems().add(data);
           
    }
      
    } catch (Exception ex) {
           
    System.out.println("ex: " + ex.toString());
      
    }


      
    for(int i=0; i<tblView.getColumns().size(); i++) {
           
    TableColumn col = (TableColumn)tblView.getColumns().get(i);
           col
    .setPrefWidth(70);
      
    }
    }

    private TableColumn createColumn(
      
    final int columnIndex, String columnTitle) {
           
    TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
           
    String title;
           
    if (columnTitle == null || columnTitle.trim().length() == 0) {
                title
    = "Column " + (columnIndex + 1);
           
    } else {
                title
    = columnTitle;
           
    }


           
    Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
           
    @Override
           
    public TableCell call(TableColumn p) {

                
    System.out.println("event cell");
                
    EditingCellData cellExtend = new EditingCellData();
                
    return cellExtend;
           
    }
      
    };

      column
    .setText(title);
      column
    .setCellValueFactory(cellFactory);
      
    return column;
    }


    Thanks for your reading.

    See this thread: Re: dynamically create columns

    This example is not editable, but to do so, simply add something like

        column.setCellFactory(TextFieldTableCell.>forTableColumn());
    

    the createTableColumn (...) method.

    Either said by the way, where did you code that you pasted in your post? It looks like in my previous post.

    Post edited by: James_D

  • JavaFX 2.2 equivalent to repaint() swing?

    Hello

    I am new to this forum and javafx.

    I'm very experienced in java, swing (and I used for the design of the JAVA virtual machine in a previous life for embedded mobile systems.including).

    Are there restrictions on when the JFX application is authorized to acquire a graphics context and to drawing on a canvas? (swing provides repaint() to plan graphic activity by the app). Must be present always could start via a UI control event handler?  In general, I wantr to draw on a canvas in response to several different triggers, including the control of based UI.

    I tried a few artisanal animation on the JFX App thread, with interesting results.

    If I use an AnimationTimer and tap into its recall, all right.

    Before that, I discovered, I tried intiially by own hack, with a small loop involving sleep() for 50ms and then by drawing.  This loop is triggered in response to a button event handler.  So, we are all still in the context of the App thread.  It did not work... the canvas layout screwed to the top, and no chart didn't seem in it.

    So, please can you answer 2 questions.

    1 / is there honor restrictions, and if so, where can I find these documented?  I have spent a lot of time to research the oracle site, with no luck.  For the real product, I develop, I need especially to know if there are problems with another thread by sending requests to the application thread, work that leads finally to the graphic.

    2 / the above behaviour may involve livelocks occur (somehow the wire of the ability to conduct its business of hunger), or behind the scenes ongoing thread synchronization that I managed to disrupt.  I saw very high level mention to Don for the JFX architecture.  Is there an explanation please?

    Thank you very much

    Jerry Kramskoy

    It is not too much that you need to know.

    The tutorial has a short section on threads in the section Architecture of JavaFX. API for node documentation describe the restrictions on what needs to be done on the Thread of the JavaFX Application:

    Node objects can be built and modified on any thread as long as they are not yet attached to a Scene . An application must determine nodes on a scene and change nodes that are already attached to a scene on the Thread of the JavaFX Application.

    Your canvas is a subclass of node, so cannot be changed on the Thread of the JavaFX Application. There is a Platform.runLater (...) method that can be invoked from threads to ask a Runnable run on the Thread of the JavaFX Application user-defined (this is similar to SwingUtilities.invokeLater (...)).

    The other important rule, of course, is that you must not block the Thread of the JavaFX Application. It looks like the loop that you describe might have done this ("we are all still in the context of the App thread").

    The javafx.concurrent package has a set of useful classes and interfaces for code execution in a background thread. For example, the Task class is an implementation of FutureTask providing also several callback methods that are called on the JavaFX Application Thread. One way to realize an animation that has updated the user interface at a specified interval would be to create a task with a set of a onSucceeded a Manager to update your canvas and then move this task to the scheduleAtFixedRate (...) method of a ScheduledExecutorService. See also the tutorial of JavaFX to competitive access .

    One last thing to note is that there are a javafx.animation package, which essentially has APIs to change the properties over time and to update the values of these properties on the JavaFX Application thread. You can make animation, for example, to create a timeline that modifies its translateX and translateY of a node properties. According to the animation that you are implemented, it's perhaps easier to roll your own loop animation and editing a Web. See the JavaDocs and the tutorial.

    In your example, things work very well using the AnimationTimer, that its handle (...) method is called on the Thread of the JavaFX Application. I'm not quite clear what happened when you tried to use your own loop, but either the loop was running on the Thread of the JavaFX Application, block it and it prevents to be part of its normal work, or you start a new thread and try to update the drawing area, breaking the rules on the threads and the scene graph.

    Note that if this can help. Maybe after a short example illustrating what you try to do it if not.

  • The use of javafx and awt on MAC

    I've read articles on no, the use of libraries SWT and AWT together in MAC systems. Then there's their constraints for JAVAFX and AWT as well?

    Please see this link.

    I have a similar case to write an image on the drive and I use javafx, the line doesn't seem to work on my mac.

    Post edited by: abhinay_agarwal

    The link you posted on the integration of SWT/AWT is not relevant to the integration of JavaFX/AWT.

    For abount JavaFX/Swing integration, see the tutorial Oracle Trail:

    JavaFX for developers of Swing: on this tutorial. Documentation and tutorials of JavaFX 2

    Swing is based on AWT, the trail tutorial also applies if you integrate JavaFX with AWT only or with the full Swing toolkit.

    In my view, there is little reason to integrate JavaFX with just the AWT toolkit, because there is little value to AWT provide that JavaFX does not already.

    JavaFX fits very well with ImageIO to write files to disk, Oracle provides a tutorial for this (see the section "Creating a snapshot"):

    With the help of the FPO Image API | Documentation and tutorials of JavaFX 2

    //Take snapshot of the scene
    WritableImage writableImage = scene.snapshot(null);
    
    // Write snapshot to file system as a .png image
    File outFile = new File("imageops-snapshot.png");
    try {
      ImageIO.write(
        SwingFXUtils.fromFXImage(writableImage, null),
        "png",
        outFile
      );
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    }
    
  • Icons in TreeView disappear after editing

    I have a weird bug where the graphic a TreeCell node is not displayed.

    Java version "1.7.0_25", Windows 7 Ultimate.

    The bug is not always reproducible. There are several housing starts of the application manifest.

    Example 13-3 'implementation a Cell Factory' of http://docs.oracle.com/javafx/2/ui_controls/tree-view.htm and

    Change the line

    TreeItem < String > empLeaf = new TreeItem < String > (employee.getName ());

    TO

    TreeItem < String > empLeaf = new TreeItem < String > (employee.getName (), new (depIcon) ImageView);

    for the nodes of the tree editable with icons. If we change the name of a node and attempts to change once again, but undoes the change

    -by selecting another cell with the mouse - icon of the affected node will become empty. See the image.

    I havemage

    If you put a println statement in the method the TreeCell cancelEdit(), you see, there are more alive than expected TreeCells.

    Code:

    test of the package;

    Import Java.util;

    Import javafx.application. *;

    Javafx.beans.property import. *;

    Javafx.event import. *;

    Javafx.scene import. *;

    Javafx.scene.control import. *;

    Javafx.scene.image import. *;

    Javafx.scene.input import. *;

    Javafx.scene.layout import. *;

    Javafx.scene.paint import. *;

    Javafx.stage import. *;

    Javafx.util import. *;

    SerializableAttribute public class TreeViewSample extends Application {}

    private final node = rootIcon

    new ImageView (new Image (getClass () .getResourceAsStream ("root.png")));

    depIcon private final image =

    New Image (getClass () .getResourceAsStream ("department.png"));

    The used < employee > list = asList (paintings). < employee >

    new employee ("Ethan Williams", "Sales"),

    new employee ("Emma Jones", "Sales"),

    new employee ("Michael Brown", "Sales"),

    new employee ("Anna Black", "Sales"),

    new employee ("Rodger York", "Sales"),

    new employee ("Susan Collins", "Sales"),

    new employee ("Mike Graham", "Support"),

    new employee ("Judy Mayer", "Support"),

    new employee ("Gregory Smith", "Support"),

    new employee ("Jacob Smith," 'Accounting'),

    new employee ("Isabella Johnson", 'Accounting'));

    TreeItem < String > = rootNode

    New TreeItem < String > ("mycompany HR", rootIcon);

    Public Shared Sub main (String [] args) {}

    Application.Launch (args);

    }

    @Override

    {} public void start (steps)

    rootNode.setExpanded (true);

    for (employee: employees) {}

    TreeItem < String > empLeaf = new TreeItem < String > (employee.getName (), new (depIcon) ImageView);

    Boolean found = false;

    for (TreeItem < String > depNode: rootNode.getChildren ()) {}

    If (depNode.getValue () .contentEquals (employee.getDepartment ())) {}

    depNode.getChildren () .add (empLeaf);

    found = true;

    break;

    }

    }

    If (! found) {}

    TreeItem < String > depNode = new TreeItem < String >)

    employee.getDepartment (),

    new ImageView (depIcon)

    );

    rootNode.getChildren () .add (depNode);

    depNode.getChildren () .add (empLeaf);

    }

    }

    stage.setTitle ("Tree View sample");

    Box of VBox = new VBox();

    a final scene = new scene (box, 400, 300);

    scene.setFill (Color.LIGHTGRAY);

    TreeView TreeView < String > = new TreeView < String > (rootNode);

    treeView.setEditable (true);

    treeView.setCellFactory (new recall < TreeView < String >, TreeCell < String > > () {}

    @Override

    public TreeCell < String > call (TreeView < String > p) {}

    return new TextFieldTreeCellImpl();

    }

    });

    box.getChildren () .add (treeView);

    stage.setScene (scene);

    internship. Show();

    }

    the final private class TextFieldTreeCellImpl extends TreeCell < String > {}

    private TextField textField;

    public TextFieldTreeCellImpl() {}

    }

    @Override

    public void startEdit() {}

    super.startEdit ();

    If (textField == null) {}

    createTextField();

    }

    setText (null);

    setGraphic (textField);

    textField.selectAll ();

    }

    @Override

    public void cancelEdit() {}

    super.cancelEdit ();

    setText ((String) getItem());

    setGraphic (getTreeItem () .getGraphic ());

    System.out.println ("cancelled point" + getItem());

    }

    @Override

    {} public Sub updateItem (empty string element, Boolean)

    super.updateItem point, empty;

    If {(empty)

    setText (null);

    setGraphic (null);

    } else {}

    If (isEditing()) {}

    If (textField! = null) {}

    textField.setText (getString ());

    }

    setText (null);

    setGraphic (textField);

    } else {}

    setText (getString ());

    setGraphic (getTreeItem () .getGraphic ());

    }

    }

    }

    private void createTextField() {}

    textField = new TextField (getString ());

    textField.setOnKeyReleased (new EventHandler < KeyEvent > () {}

    @Override

    {} public void handle (KeyEvent t)

    If (t.getCode () == KeyCode.ENTER) {}

    commitEdit (textField.getText ());

    } ElseIf (t.getCode () == KeyCode.ESCAPE) {}

    cancelEdit();

    }

    }

    });

    }

    private String getString() {}

    return getItem() is nothing? ' ': getItem () m:System.NET.SocketAddress.ToString ();

    }

    }

    Public NotInheritable class employee {}

    private final SimpleStringProperty name

    Department of SimpleStringProperty final private;

    private employee (String name, String department) {}

    myIdName = new SimpleStringProperty (name);

    This.Department = new SimpleStringProperty (department);

    }

    public String getName() {}

    Return name.get ();

    }

    {} public void setName (String fName)

    Name.Set (fname);

    }

    public String getDepartment() {}

    Return department.get ();

    }

    {} public void setDepartment (String fName)

    Department.Set (fname);

    }

    }

    }

    Solved

    I tried jdk build 1.8.0 - ea - b99 and is no more a problem.

  • can I run a javafx from main thread thread?

    EDIT: what I want the code for:
    (1) controller class
    -runs in the background
    -creates shopping cart
    -create listeners for applications that will add items to your basket
    -regulates which application has access to the screen
    (2) class ShoppingCart
    -runs in the background
    -receive the items of no Java-based applications
    -stores these items "in the basket.
    (3) class checkout
    -GUI for the user to remove items in their cart
    -complete the transaction before returning control to your cart

    I'm new to javafx - and haven't used Java over the years, namely, I'm trying the following:

    -------------------------------------------------------------------------------------------------------------------------------
    Controller class
    -------------------------------------------------------------------------------------------------------------------------------
    public class Controller {
         private static ShoppingCart shoppingCart;
    
         public static void main(String[] args) {
              ExecutorService exec = Executors.newFixedThreadPool(5);
              try {
                   shoppingCart = new ShoppingCart(2001);
                   exec.execute(shoppingCart);
              } catch (IOException ex) {
                   ex.printStackTrace();
              }
         }
    }
    -------------------------------------------------------------------------------------------------------------------------------
    Class ShoppingCart
    -------------------------------------------------------------------------------------------------------------------------------
    public class ShoppingCart extends Stage implements Runnable {
         private ServerSocket serverSocket;
         private Socket clientSocket;
         private Socket socket;
         private final int port;
         
         private BufferedReader bReader;
         private BufferedWriter bWriter;
         
         private final ArrayList<String> items = new ArrayList<Item>();
    
        public ShoppingCart(int port) throws IOException {
              this.port = port;
        }
         
         /*
          * when an item arrives at the port, pass the port through to RecieveItem to digest the incomming stream
          */
        @Override
        public void run() {
              
              boolean addMoreItems = true;
              try {
                   this.serverSocket = new ServerSocket(port);
              } catch (IOException ex) {
                   ex.printStackTrace();
              }
              try {
                   while(addMoreItems){
                        this.clientSocket = serverSocket.accept();
                        String theItem = receiveItem(clientSocket);
                        if(theItem == null)
                             addMoreItems = false;
                        else
                             this.items.add(theItem);
                   }
              } catch (IOException ex) {
                   ex.printStackTrace();
              }
        }
    
        private String receiveItem(Socket socket) throws IOException {
              String readLine = "";
              String itemString = "";
              
              this.socket = socket;
              this.bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              
              while(readLine != null){
                   readLine = bReader.readLine();
                   // if we are finished adding items, proceed to checkout
                   if(readLine.equalsIgnoreCase("checkout")) {
                        // show cart for user to see items before paying
                        itemString = null;
                   } else { // otherwise, add the item
                        itemString += "|" + readLine;
                   }
              }
              
              return itemString;
         }
    -------------------------------------------------------------------------------------------------------------------------------
    When I try to run the code, I get the following:
    -------------------------------------------------------------------------------------------------------------------------------
    Exception in thread "main" java.lang.IllegalStateException: Not on FX application thread; currentThread = main
    -------------------------------------------------------------------------------------------------------------------------------

    So, is this possible? What Miss me?
    Thanks for reading my questions :)
    Dave.

    Published by: 1003225 on 29 April 2013 20:26

    Published by: 1003225 on April 30, 2013 12:49

    I did some research and aparently you must republish the same answer for me to be able to show your answer as being correct (for some reason, it is not editable)

    Answer:

    You can launch an application Java to the main thread by calling Application.launch, but you can call it only once per process or an exception will be thrown:
    http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/application.html#launch%28Java.lang.class, %20java.lang.String...%29

    ---------

    Partners:

    The cycle of life and the management of threads that run user by the JavaFX application code is documented in the javadoc for JavaFX Application:
    http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/application.html

    Conditions of application output is kept by Platform.setImplicitExit:
    http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/platform.html#setImplicitExit%28boolean%29

  • JQuery library for JavaFX?

    Someone is aware of a JQuery library for querying/editing nodes in a JavaFX scene graph?
    If no library like that exist currently, anyone know if it is expected to provide something like this in the future?
    A declarative query and modify the nodes in the scene graph seems a very interesting library for me, and it shouldn't be that difficult to implement in practice, where it does not already exist.

    Kind regards

    Sergio

    to * wrote:
    Hello, Yes, I was looking for something like Node.lookupAll. Although the API that I had in mind was a little higher level, in JQuery, you can select a group of nodes and send them a message in a single step, something like:

    $('selector').do_something (...)

    I would have to explicitly iterate on the answer returned by lookupAll, but that's almost what I need.

    With the new features of Java 8 (java.util.Stream.forEach (...), for example) this becomes much easier too...

    root.lookupAll(".my-class")
       .stream()
       .forEach(node -> node.setVisible(false));
    

    Edited by: James_D April 3, 2013 15:08

  • javaFX: cellvalue TableView is not enough to display in columns, I want to...

    javaFX: cellvalue TableView is not enough to display in columns, it will cut end «...» "how show a tip on these cells?
    I need a gimmick because sometimes I can't drag the colunm head. So I can't see the contents of the cell.

    Create a custom cell and replace the updateItem method. Add a balloon:

                       Tooltip tip = new Tooltip(getString());
                       Tooltip.install(this, tip);
                  
    

    Here is an example (a ToolTip for the column email):

    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellEditEvent;
    import javafx.scene.control.TableView;
    import javafx.scene.control.TextField;
    import javafx.scene.control.Tooltip;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.VBox;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    public class TableViewToolTipSample 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]"));
        final HBox hb = new HBox();
    
        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(550);
    
            final Label label = new Label("Address Book");
            label.setFont(new Font("Arial", 20));
    
            table.setEditable(true);
            Callback cellFactory =
                    new Callback() {
                        public TableCell call(TableColumn p) {
                            return new CustomCell();
                        }
                    };
    
            TableColumn firstNameCol = new TableColumn("First Name");
            firstNameCol.setMinWidth(100);
            firstNameCol.setCellValueFactory(
                    new PropertyValueFactory("firstName"));
           // firstNameCol.setCellFactory(cellFactory);
    
            TableColumn lastNameCol = new TableColumn("Last Name");
            lastNameCol.setMinWidth(100);
            lastNameCol.setCellValueFactory(
                    new PropertyValueFactory("lastName"));
          //  lastNameCol.setCellFactory(cellFactory);
    
            TableColumn emailCol = new TableColumn("Email");
            emailCol.setMinWidth(200);
            emailCol.setCellValueFactory(
                    new PropertyValueFactory("email"));
            emailCol.setCellFactory(cellFactory);
    
            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, hb);
    
            ((Group) scene.getRoot()).getChildren().addAll(vbox);
    
            stage.setScene(scene);
            stage.show();
        }
    
        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);
            }
        }
    
        class CustomCell extends TableCell {
    
            private TextField textField;
    
            public CustomCell() {
            }
    
            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
    
                if (empty) {
                    setText(null);
                    setGraphic(null);
                } else {
                    if (isEditing()) {
                        if (textField != null) {
                            textField.setText(getString());
                        }
                        setText(null);
                        setGraphic(textField);
                    } else {
                        setText(getString());
                        setGraphic(null);
                        Tooltip tip = new Tooltip(getString());
                        Tooltip.install(this, tip);
    
                    }
                }
            }
    
            private String getString() {
                return getItem() == null ? "" : getItem().toString();
            }
        }
    }
    

    If you need a ToolTip for a column heading:

            TableColumn emailCol = new TableColumn();
            Label emailHeaderLabel = new Label("Email header label");
            emailCol.setGraphic(emailHeaderLabel);     
    
            Tooltip tip = new Tooltip("Email header label");
            Tooltip.install(emailHeaderLabel, tip);
    

    Edited: Add a ToolTip to a column header

  • Creating a dynamic column editable

    I tried to make my dynamic columns as editable. The problem is that my dynamic columns are nested.

    Now editable column works fine when I have diff columns with a different name. For example, col1, col2, col3 (not nested)

    Or I nested columns like "pass"(parent) given two columns col1 and col2. ".

    But, when I use them in a dynamic of columns in which all of them have the same name, in the example below, each with the same name 'col', I can change all of them, but the textfield never faded away, when I click on ENTER.


    Suppose I have an editable column with col name:
    for (final CategoryTypeVO type : typeList)
                    {
                           TableColumn<ItemVO, Integer> col = new TableColumn<ItemVO, Integer>(type.getTypeName());
                          col.setMinWidth(100);
                          col.setEditable(true);
                          col.setCellFactory(cellFactory);
                         
                         
                          col.setOnEditCommit(
                                   new EventHandler<TableColumn.CellEditEvent<ItemVO, Integer>>() {
                                   public void handle(TableColumn.CellEditEvent<ItemVO, Integer> t) {
                                   ((ItemVO)t.getTableView().getItems().get(
                                   t.getTablePosition().getRow())).getListType().get(type.getTypeId()).setQuantity(t.getNewValue());
                                   }
                                   });
                           quantity.getColumns().add(col);
                         }
    and cellfactory as:
    final Callback<TableColumn<ItemVO, Integer>, TableCell<ItemVO, Integer>> cellFactory = new Callback<TableColumn<ItemVO, Integer>, TableCell<ItemVO, Integer>>() {
                        public TableCell call(TableColumn p) {
                             return new EditingCell();
                        }
                   };
    and Editing class as
    class EditingCell extends TableCell<ItemVO, Integer> {
               
               private TextField textField;
              
               public EditingCell() {}
              
               @Override
               public void startEdit() {
                   super.startEdit();
                  
                   if (textField == null) {
                       createTextField();
                   }
                  
                   
                   setGraphic(textField);
                   setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                   textField.selectAll();
                   Platform.runLater(new Runnable() {
                       @Override
                       public void run() {
                           textField.requestFocus();
                       }
                  });
               }
              
               @Override
               public void cancelEdit() {
                   super.cancelEdit();
                  
                   setText(String.valueOf(getItem()));
                   setContentDisplay(ContentDisplay.TEXT_ONLY);
               }
          
               @Override
               public void updateItem(Integer item, boolean empty) {
                   super.updateItem(item, empty);
                  
                   if (empty) {
                       setText(null);
                       setGraphic(null);
                   } else {
                       if (isEditing()) {
                           if (textField != null) {
                               textField.setText(getString());
                           }
                           setGraphic(textField);
                           setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                       } else {
                           setText(getString());
                           setContentDisplay(ContentDisplay.TEXT_ONLY);
                       }
                   }
               }
               
              
               
          
               private void createTextField() {
                   textField = new TextField();
                   //textField.setText(getString());
                   textField.setText("0");
                   textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()*2);
                   
                   textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
    
                          @Override
                          public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) {
                              if (!arg2) {
                                  commitEdit(Integer.parseInt(textField.getText()));
                              }
                          }
                      });
                   
                   textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
                       @Override public void handle(KeyEvent t) {
                           if (t.getCode() == KeyCode.ENTER) {
                               commitEdit(Integer.parseInt(textField.getText()));
                           } else if (t.getCode() == KeyCode.ESCAPE) {
                               cancelEdit();
                           }
                       }
                   });
               }
    
              
               private String getString() {
                   return getItem() == null ? "" : getItem().toString();
               }
    Now what happens is this thing works fine if I separate columns with distinct names. But when it comes to dynamic columns, it fails, once I have edit a cell, the text field never leaves his place. It gets stuck in the cell. Any help!

    Published by: abhinay_a on January 21, 2013 12:31 AM

    Do not know what is the problem in your code, but it is easier to use TextFieldTableCell than building your own TableCell from scratch.

    This change to the example I posted in How to create a tableview for this? works for me:

    package itemtable;
    
    import javafx.application.Application;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.Scene;
    import javafx.scene.control.ChoiceBox;
    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.control.cell.TextFieldTableCell;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    import javafx.util.converter.NumberStringConverter;
    
    public class ItemTable extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        final DAO dao = new MockDAO();
        final ChoiceBox choiceBox = new ChoiceBox();
        choiceBox.getItems().setAll(dao.getCategories());
    
        final TableView table = new TableView();
    
        // Make table editable:
        table.setEditable(true);
    
        final TableColumn nameCol = new TableColumn("Name");
        nameCol.setCellValueFactory(new PropertyValueFactory("name"));
        nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
        final TableColumn priceCol = new TableColumn("Price");
        table.getColumns().addAll(nameCol, priceCol);
    
        choiceBox.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener() {
              @Override
              public void changed(ObservableValue observable, Category oldValue, Category newValue) {
                table.getItems().clear();
                priceCol.getColumns().clear();
                for (final Type type : newValue.getTypes()) {
                  final TableColumn col = new TableColumn(type.getName());
                  col.setCellValueFactory(new Callback, ObservableValue>() {
                    @Override
                    public ObservableValue call(CellDataFeatures cellData) {
                      Item item = cellData.getValue();
                      if (item == null) {
                        return null;
                      } else {
                        return item.priceProperty(type);
                      }
                    }
                  });
    
                  // Make column editable:
                  col.setEditable(true);
                  col.setCellFactory(TextFieldTableCell.forTableColumn(new NumberStringConverter()));
    
                  priceCol.getColumns().add(col);
                }
                table.getItems().setAll(dao.getItemsByCategory(newValue));
              }
            });
    
        BorderPane root = new BorderPane();
        root.setTop(choiceBox);
        root.setCenter(table);
    
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    }
    

    Edited by: James_D January 22, 2013 07:22

Maybe you are looking for

  • Malfunction of the battery (model No. PA3817U-1BRS)

    I received my laptop one after the expiration of the warranty the battery died I've only had this laptop for three years.Is that what I can do other than to make a purchase of a new battery? Mainly because I don't want to pay $99 to see the computer

  • C00D1198 error - unable to access the Media Player

    original title: Media window When I try to access the media player on a website I get a windows media error C00D1198 can you explain this message and help me access windows media

  • The total production drops

    Hello Please take a look at the topology. G0/1 interface to increase the Total counter output Drop. FA0/1 of HQRouter has no meter error. We changed the cable between the devices. Manually set us the speed and duplex (100, full). any idea? HQRouter c

  • After "without Accelerator crypto engine" No. VPN PLUS

    Hello In my test harness, I have a CISCO with a Council AIM-VPN/BPII-PLUS 1841, everything worked well, until I see the difference with and without the accelerator Sins as soon as IOS told me he'll change accelerator SW instead of HW Accelerator, I c

  • Automatic processing of the files in the folder

    Is it possible to use the ODI to automatically process a csv file, immediately it will be deposited in a folder without the user clicking anything?