Channels ▼

Eric Bruno

Dr. Dobb's Bloggers

JavaFX 8: Combining Language Features, Part 2

June 02, 2014

In this example, the file is attempted to be read, and the contents are placed in the Dragboard and system clipboard. This means that if you drop the file outside of the application and onto an editor, the contents of the file will be pasted into the editor, as shown below:

If instead you want to move the file to another directory within the application, you define the visuals that occur when the source is dragged over the target in the onDragEntered() method. In our sample, I set the text to be bolder and add an underline to illustrate the directory as a viable target (see the screen shot below).

Here's the code:


    public void onDragEntered(DragEvent event, Text target) {
        // entered the target region
        System.out.println("onDragEntered");
        if (event.getGestureSource() != target &&
                event.getDragboard().hasString()) {
            // Highlight the potential drop target
            target.setUnderline(true);
            target.setStroke(Color.BLACK);
        }

        event.consume();
    }

This code has two checks: First, that the item isn't being dragged over itself. Second, that the Dragboard contains something, which indicates that a drag-and-drop operation has actually begun. Next, let's skip to the chase and examine, in sections, what happens when the source (a file) is dropped onto the target (a directory):

    public void onDragDropped(DragEvent event, Text target) {
        System.out.println("onDragDropped");
        
        // Get data from the dragboard
        Dragboard db = event.getDragboard();
        boolean success = false;
        if (db.hasString()) {
            // Do the file move here
            Text source = (Text)event.getGestureSource();
            HeaderList sourceList = getParentHeaderList(source);
            HeaderList targetList = getParentHeaderList(target);
            String sourcePath = ...
            String targetPath = ...

First, since the target Node is given as a parameter, the source Node is obtained from the DragEvent object; now we have both. Next, we get the lists that each Text Node belongs to in order to get their file paths. Let's continue:

            Files.move( Paths.get(sourcePath), 
                        Paths.get(targetPath), ATOMIC_MOVE);

            // Update the source list
            ...
            populateList(path, dirname, sourceList);
        }

        // Inform the source that the drag/drop is complete
        event.setDropCompleted(success);
        event.consume();
    }

The source file is moved to the target directory via one line of code, thanks to the Java Files object, and the source file's list is updated to show its new contents (minus the file moved). Finally, the drag-and-drop operation is marked as complete via the call to setDropCompleted, after which the onDragDone is called on the source Node:


    private void onDragDone(DragEvent event, Text source) {
        Dragboard db = event.getDragboard();
        db.clear();
        event.consume();
    }

As a result, the code simply clears the Dragboard (including the system clipboard) for neatness.

Displaying File Contents

Continuing with our exploration of what's new in JavaFX 8, I added a little more functionally to this version of the File Manager: the ability to open files in the JavaFX application. Currently, this is a simple operation, one that I will extend in one of the next blogs in this series. For now, a when a file is clicked, a check is made to see if it's an HTML file. If so, a JavaFX HTMLEditor object is created and placed within its own Scene-graph to be displayed within a separate window with the file's contents. This control was enhanced in JavaFX 8, and not only does it render HTML5 quite nicely, but it allows you to edit the HTML as well (shown in the screen shot below).

Here's the code (skipping the non-essential portions):


    private void onTextClicked(MouseEvent me, HeaderList list) {
        // Get the file contents
        ...

        // Open in a new Stage/Scene graph with a TextFlow control
        Group grp = new Group();
        Node node;
        if ( sourcePath.endsWith("html") ) {
            HTMLEditor html = new HTMLEditor();
            html.setHtmlText(fileContents);
            node = html;
        }
        else {
            TextFlow txtFlow = new TextFlow(new Text(fileContents));
            node = txtFlow;
        }

        grp.getChildren().add(node);
        Scene scene = new Scene(grp, 640, 480);
        Stage editStg = new Stage();
        editStg.setScene(scene);
        editStg.show();
        editStg.centerOnScreen();
    }

You can see that if the file isn't an HTML, it's opened via the new TextFlow control (shown below), which is used to render rich text displays (something we'll explore in more detail going forward).

Stay tuned, because in the next installment in the series we'll explore more involved TextFlow implementations, and we still need to implement the custom FileSystem to be able to manage remote files via FTP.

Happy coding!
-EJB

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 


Video