Showing posts with label JavaFX 8. Show all posts
Showing posts with label JavaFX 8. Show all posts

Thursday, June 16, 2016

Read csv file, display in JavaFX TableView

Java example read csv file and display the content in JavaFX TableView.

To know how to prepare the csv file, and simple read csv file, refer to last post.


JavaFXCSVTableView.java
package javafxcsvtableview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXCSVTableView extends Application {

    public class Record {
        //Assume each record have 6 elements, all String

        private SimpleStringProperty f1, f2, f3, f4, f5, f6;

        public String getF1() {
            return f1.get();
        }

        public String getF2() {
            return f2.get();
        }

        public String getF3() {
            return f3.get();
        }

        public String getF4() {
            return f4.get();
        }

        public String getF5() {
            return f5.get();
        }

        public String getF6() {
            return f6.get();
        }

        Record(String f1, String f2, String f3, String f4,
                String f5, String f6) {
            this.f1 = new SimpleStringProperty(f1);
            this.f2 = new SimpleStringProperty(f2);
            this.f3 = new SimpleStringProperty(f3);
            this.f4 = new SimpleStringProperty(f4);
            this.f5 = new SimpleStringProperty(f5);
            this.f6 = new SimpleStringProperty(f6);
        }

    }

    private final TableView<Record> tableView = new TableView<>();

    private final ObservableList<Record> dataList
            = FXCollections.observableArrayList();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");

        Group root = new Group();

        TableColumn columnF1 = new TableColumn("f1");
        columnF1.setCellValueFactory(
                new PropertyValueFactory<>("f1"));

        TableColumn columnF2 = new TableColumn("f2");
        columnF2.setCellValueFactory(
                new PropertyValueFactory<>("f2"));

        TableColumn columnF3 = new TableColumn("f3");
        columnF3.setCellValueFactory(
                new PropertyValueFactory<>("f3"));

        TableColumn columnF4 = new TableColumn("f4");
        columnF4.setCellValueFactory(
                new PropertyValueFactory<>("f4"));

        TableColumn columnF5 = new TableColumn("f5");
        columnF5.setCellValueFactory(
                new PropertyValueFactory<>("f5"));

        TableColumn columnF6 = new TableColumn("f6");
        columnF6.setCellValueFactory(
                new PropertyValueFactory<>("f6"));

        tableView.setItems(dataList);
        tableView.getColumns().addAll(
                columnF1, columnF2, columnF3, columnF4, columnF5, columnF6);

        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.getChildren().add(tableView);

        root.getChildren().add(vBox);

        primaryStage.setScene(new Scene(root, 700, 250));
        primaryStage.show();

        readCSV();
    }

    private void readCSV() {

        String CsvFile = "/home/buddy/test/test.csv";
        String FieldDelimiter = ",";

        BufferedReader br;

        try {
            br = new BufferedReader(new FileReader(CsvFile));

            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(FieldDelimiter, -1);

                Record record = new Record(fields[0], fields[1], fields[2],
                        fields[3], fields[4], fields[5]);
                dataList.add(record);

            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaFXCSVTableView.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFXCSVTableView.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

    }

    public static void main(String[] args) {
        launch(args);
    }

}


Next post show how to do the job in background.

Wednesday, September 2, 2015

Introducing JavaFX 8 Programming (Oracle Press)


Learn the Fundamentals of JavaFX 8 from Programming Guru Herb Schildt

Introducing JavaFX 8 Programming provides a fast-paced, practical introduction to JavaFX, Java’s next-generation GUI programming framework. In this easy-to-read guide, best-selling author Herb Schildt presents the key topics and concepts you’ll need to start developing modern, dynamic JavaFX GUI applications. The book begins with the fundamentals, including the general form of a JavaFX program. You then advance to event handling, controls, images, fonts, layouts, effects, transforms, animations (including 3-D animations), menus, and more. Numerous complete examples are included that put key topics and techniques into action. Designed for Java programmers, the book’s focus is on the JavaFX API and all examples are written entirely in Java. Best of all, the book is written in the clear, crisp, uncompromising style that has made Herb Schildt the choice of millions worldwide.

  • Learn the general form of a JavaFX program
  • Work with scenes and stages
  • Understand the fundamentals of JavaFX event handling
  • Explore several controls, such as buttons, list views, sliders, trees, tables, scroll panes, and more
  • Work with images, fonts, and layouts
  • Explore the JavaFX menu system
  • Use visual effects and transforms
  • Incorporate 2-D and 3-D animation
  • Present data in JavaFX charts
  • Display Web-based content using WebView and WebEngine

Thursday, October 16, 2014

Mastering JavaFX 8 Controls

Design and Deploy High-Performance JavaFX Controls: Mastering JavaFX 8 Controls (Oracle (McGraw-Hill))

Deliver state-of-the-art applications with visually stunning UIs. Mastering JavaFX 8 Controls provides clear instructions, detailed examples, and ready-to-use code samples. Find out how to work with the latest JavaFX APIs, configure UI components, automatically generate FXML, build cutting-edge controls, and effectively apply CSS styling. Troubleshooting, tuning, and deployment are also covered in this Oracle Press guide.
  • Understand the properties of JavaFX 8 controls and APIs
  • Create custom controls, transformations, and layouts
  • Work from JavaFX Scene Graph and Scene Builder
  • Visualize data models using advanced control types
  • Use ListView, TableView, and TreeView APIs
  • Handle audio and video content using JavaFX media classes
  • Maximize separation between UI and application logic using FXML
  • Style controls and applications using CSS
  • Extend functionality of Swing and SWT applications with JavaFX
Code examples in the book are available for download.

Friday, August 8, 2014

JavaFX Dynamic TableView with button, something wrong on JDK 1.8/JavaFX 8

It's a updated version for my old example "JavaFX: Get row data from TableView" for JDK 1.7/JavaFX 2.

- In the original example, I haven't handle col.setOnEditCommit() to update the data in back-end. So when user click the Action button, it show the original data, not the updated data. It's added.

- This example work when compile with JDK 1.7 only, when compile with JDK 1.8, something wrong.
a) After edit a cell, then click to edit another cell below it, it show a wrong data.
b) Extra incorrect "Action" button added, when add New Record.

- If I ignore adding Action button, by commenting tableView.getColumns().add(col_action), problems seem temporarily fixed.

May be something changed in JDK 1.8/JavaFX 8 I haven't handle...! May be I have to re-check the updated documents...!

Work on JDK 1.7/JavaFX 2, under Windows 8.1, Netbeans 7.4:

Fail on Windows 8.1, Netbeans 7.4, JDK 1.8:

Fail on Ubuntu Linux 14.04, Netbeans 8, JDK 1.8:

Temporarily fixed by ignore the button:


Program code;
package javafxdyntable;

import java.util.Random;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
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.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXDynTable extends Application {

    private TableView tableView = new TableView();
    private Button btnNew = new Button("New Record");

    static Random random = new Random();

    static final String Day[] = {
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday"};

    public static class Record {

        private final SimpleIntegerProperty id;
        private final SimpleIntegerProperty value_0;
        private final SimpleIntegerProperty value_1;
        private final SimpleIntegerProperty value_2;
        private final SimpleIntegerProperty value_3;
        private final SimpleIntegerProperty value_4;

        Record(int i, int v0, int v1, int v2, int v3,
                int v4) {
            this.id = new SimpleIntegerProperty(i);
            this.value_0 = new SimpleIntegerProperty(v0);
            this.value_1 = new SimpleIntegerProperty(v1);
            this.value_2 = new SimpleIntegerProperty(v2);
            this.value_3 = new SimpleIntegerProperty(v3);
            this.value_4 = new SimpleIntegerProperty(v4);
        }

        public int getId() {
            return id.get();
        }

        public void setId(int v) {
            id.set(v);
        }

        public int getValue_0() {
            return value_0.get();
        }

        public void setValue_0(int v) {
            value_0.set(v);
        }

        public int getValue_1() {
            return value_1.get();
        }

        public void setValue_1(int v) {
            value_1.set(v);
        }

        public int getValue_2() {
            return value_2.get();
        }

        public void setValue_2(int v) {
            value_2.set(v);
        }

        public int getValue_3() {
            return value_3.get();
        }

        public void setValue_3(int v) {
            value_3.set(v);
        }

        public int getValue_4() {
            return value_4.get();
        }

        public void setValue_4(int v) {
            value_4.set(v);
        }

    };

    ObservableList<Record> data = FXCollections.observableArrayList();

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        tableView.setEditable(true);
        Callback<TableColumn, TableCell> cellFactory
                = new Callback<TableColumn, TableCell>() {

                    @Override
                    public TableCell call(TableColumn p) {
                        return new EditingCell();
                    }
                };

        btnNew.setOnAction(btnNewHandler);

        //init table
        //Un-editable column of "id"
        TableColumn col_id = new TableColumn("ID");
        tableView.getColumns().add(col_id);
        col_id.setCellValueFactory(
                new PropertyValueFactory<Record, String>("id"));

        //Editable columns
        for (int i = 0; i < Day.length; i++) {
            TableColumn col = new TableColumn(Day[i]);
            col.setCellValueFactory(
                    new PropertyValueFactory<Record, String>(
                            "value_" + String.valueOf(i)));
            tableView.getColumns().add(col);
            col.setCellFactory(cellFactory);
            
            final int idx = i;
            col.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Record, Integer>>() {

                @Override
                public void handle(TableColumn.CellEditEvent<Record, Integer> event) {
                    Record rec = event.getTableView().getItems().get(event.getTablePosition().getRow());
                    Integer newValue = event.getNewValue();
                    
                    switch(idx){
                        case 0: rec.setValue_0(newValue);
                                break;
                        case 1: rec.setValue_1(newValue);
                                break;
                        case 2: rec.setValue_2(newValue);
                                break;
                        case 3: rec.setValue_3(newValue);
                                break;
                        case 4: rec.setValue_4(newValue);
                                break;
                    }
                }
            });

        }

        //Insert Button
        TableColumn col_action = new TableColumn("Action");
        col_action.setSortable(false);

        col_action.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<Record, Boolean>, ObservableValue<Boolean>>() {

                @Override
                public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Record, Boolean> p) {
                    return new SimpleBooleanProperty(p.getValue() != null);
                }
            });

        col_action.setCellFactory(
            new Callback<TableColumn<Record, Boolean>, TableCell<Record, Boolean>>() {

                @Override
                public TableCell<Record, Boolean> call(TableColumn<Record, Boolean> p) {
                    return new ButtonCell(tableView);
                }

            });
        tableView.getColumns().add(col_action);

        tableView.setItems(data);

        Group root = new Group();
        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.getChildren().addAll(btnNew, tableView);
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public class SubRecord {

        private SimpleStringProperty fieldSubRecordName;
        private SimpleIntegerProperty fieldSubRecordValue;

        SubRecord(String sn, int sv) {
            this.fieldSubRecordName = new SimpleStringProperty(sn);
            this.fieldSubRecordValue = new SimpleIntegerProperty(sv);
        }

        public String getFieldSubRecordName() {
            return fieldSubRecordName.get();
        }

        public int getFieldSubRecordValue() {
            return fieldSubRecordValue.get();
        }

    }

    //Define the button cell
    private class ButtonCell extends TableCell<Record, Boolean> {

        final Button cellButton = new Button("Action");

        ButtonCell(final TableView tblView) {

            cellButton.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent t) {
                    int selectdIndex = getTableRow().getIndex();

                    //Create a new table show details of the selected item
                    Record selectedRecord = (Record) tblView.getItems().get(selectdIndex);
                    ObservableList<SubRecord> subDataList
                            = FXCollections.observableArrayList(
                                    new SubRecord("ID", selectedRecord.getId()),
                                    new SubRecord("Monday", selectedRecord.getValue_0()),
                                    new SubRecord("Tuesday", selectedRecord.getValue_1()),
                                    new SubRecord("Wednesday", selectedRecord.getValue_2()),
                                    new SubRecord("Thursday", selectedRecord.getValue_3()),
                                    new SubRecord("Friday", selectedRecord.getValue_4()));

                    TableColumn columnfield = new TableColumn("Field");
                    columnfield.setCellValueFactory(
                            new PropertyValueFactory<Record, String>("fieldSubRecordName"));

                    TableColumn columnValue = new TableColumn("Value");
                    columnValue.setCellValueFactory(
                            new PropertyValueFactory<SubRecord, Integer>("fieldSubRecordValue"));

                    TableView<SubRecord> subTableView = new TableView<>();
                    subTableView.setItems(subDataList);
                    subTableView.getColumns().addAll(columnfield, columnValue);

                    Stage myDialog = new Stage();
                    myDialog.initModality(Modality.WINDOW_MODAL);

                    Scene myDialogScene = new Scene(VBoxBuilder.create()
                            .children(subTableView)
                            .alignment(Pos.CENTER)
                            .padding(new Insets(10))
                            .build());

                    myDialog.setScene(myDialogScene);
                    myDialog.show();
                }
            });
        }

        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            super.updateItem(t, empty);
            if (!empty) {
                setGraphic(cellButton);
            }
        }
    }

    EventHandler<ActionEvent> btnNewHandler
        = new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {

                //generate new Record with random number
                int newId = data.size();
                Record newRec = new Record(
                    newId,
                    random.nextInt(100),
                    random.nextInt(100),
                    random.nextInt(100),
                    random.nextInt(100),
                    random.nextInt(100));
                data.add(newRec);
            }
        };

    class EditingCell extends TableCell<XYChart.Data, Number> {

        private TextField textField;

        public EditingCell() {
        }

        @Override
        public void startEdit() {

            super.startEdit();

            if (textField == null) {
                createTextField();
            }

            setGraphic(textField);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            textField.selectAll();
        }

        @Override
        public void cancelEdit() {
            super.cancelEdit();

            setText(String.valueOf(getItem()));
            setContentDisplay(ContentDisplay.TEXT_ONLY);
        }

        @Override
        public void updateItem(Number 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(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
            textField.setOnKeyPressed(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();
        }
    }

}

Thursday, August 7, 2014

Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients

In Pro JavaFX 8 expert authors show you how to use the JavaFX platform to create rich-client Java applications. You'll discover how you can use this powerful Java-based UI platform, which is capable of handling large-scale data-driven business applications for PC as well as now mobile and embedded devices.

Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients

Covering the JavaFX API, development tools, and best practices, this book provides code examples that explore the exciting new features provided with JavaFX 8 which comes as part of Oracle's new Java (SE) 8 release. This book also contains engaging tutorials that cover virtually every facet of JavaFX development and reference materials on JavaFX that augment the JavaFX API documentation.

After reading and using this book, you'll have the authoritative knowledge that should give you an edge in your next JavaFX-based application projects for your job or your clients.

What you’ll learn

  • How to get started with JavaFX, including downloading the SDK and available tools
  • How to express user interfaces with SceneBuilder and FXML 
  • How to use property binding to keep the UI easily in sync with the model
  • How to use the rich set of JavaFX UI controls, charts, shapes, effects, transformations, and animations to create stunning, responsive, user interfaces
  • How to use the powerful JavaFX layout classes to define the user interface in a cross-platform fashion
  • How to leverage the observable collection classes to observe changes in, and bind to, Java collections
  • How to use the JavaFX media classes to play audio and video
  • How to interact with external application services to create an enterprise application with JavaFX
  • How to use the JavaFX API with alternative languages such as Scala and Groovy
  • How to use Java on embedded, mobile, and tablet devices

Who this book is for
Application developers, graphic designers, and IT decision makers. Not only does this book contain comprehensive technical information for developers and designers, it builds a compelling case for choosing JavaFX.

Table of Contents
1. Getting a Jump Start in JavaFX 8
2. Creating a User Interface in JavaFX 8
3. Using SceneBuilder to create a User Interface
4. Properties and Bindings
5. Building Dynamic UI Layouts in JavaFX
6. Using the JavaFX UI Controls
7.Collections and Concurrency
8. Creating Charts in JavaFX
9. Using the media classes
10. JavaFX 3D
11. Accessing Web Services
12. Java on Embedded, Mobile and Tablet
13. JavaFX languages and markup

Friday, August 1, 2014

JavaFX 8: Introduction by Example, 2nd edition

JavaFX 8: Introduction by Example shows you how to use your existing Java skills to create graphically exciting client applications with the JavaFX 8 platform. The book is a new and much improved edition of JavaFX 2.0: Introduction by Example, taking you through a series of engaging, fun-to-work examples that bring you up to speed on the major facets of the platform. It will help you to create applications that look good, are fun to use, and that take advantage of the medium to present data of all types in ways that engage the user and lead to increased productivity.

Entirely example-based, JavaFX 8: Introduction by Example begins with the fundamentals of installing the software and creating a simple interface. From there, you'll move in progressive steps through the process of developing applications using JavaFX’s standard drawing primitives. You'll then explore images, animations, media, and web. This new edition incorporates the changes resulting from the switch to Java 8 SDK. It covers advanced topics such as custom controls, JavaFX 3D, gesture devices, and embedded systems.  Best of all, the book is full of working code that you can adapt and extend to all your future projects.

  • Entirely example-based
  • Filled with fun and practical code examples
  • Covers all that's new in Java 8 relating to JavaFX such as Lambda expressions and Streams
  • Covers gesture devices, 3D display, embedded systems, and other advanced topics

What you’ll learn
  • Install JavaFX 8 and configure your environment
  • Work with touch-based interfaces such as in Windows 8
  • Interpret gesture-based events the Leap Motion Controller and similar hardware
  • Integrate JavaFX with embedded systems such as Arduino and Raspberry Pi
  • Develop modern GUI implementations of business forms
  • Work with shapes, color, text, and animation
  • Add audio and video to your projects
  • Create custom controls using SVG and Canvas
  • Learn to style a user-interface via CSS
  • Communicate bidirectionally using Java and Javascript with HTML5

Who this book is for

JavaFX 8: Introduction by Example is for Java developers who are interested in developing rich, client-side applications to run on PCs, phones, tablets, Arduino controllers, the Raspberry Pi, and more. Whether enterprise developer or hobbyist, anyone wanting to develop a polished user-interface from Java will find much to like in this book.

Table of Contents
1. Getting started
2. JavaFX Fundamentals
3. Java 8 Lambda Expressions
4. Layout & UI Controls
5. Graphics with JavaFX
6. Custom Controls
7. Media with JavaFX
8. JavaFX on the Web
9. JavaFX 3D
10. JavaFX and Arduino
11. JavaFX on the Raspberry Pi
12. Gesture-based Interfaces
13. Appendix A. References

Tuesday, July 8, 2014

Java 8 and JavaFX

Stuart Marks shows you how to effectively use Lambda expressions, Streams, Date & Time, etc to make your life easier.

Sunday, September 22, 2013

Getting Started with JavaFX 3D Graphics

The tutorial, Getting Started with JavaFX 3D Graphics, contains information about the JavaFX 3D graphics functionality available in JavaFX 8.

- Overview
- 3D Shapes
- Camera
- Subscene
- Lights
- Materials
- Picking
- Building a 3D Sample Application

It is assumed that you have an intermediate level of Java and JavaFX knowledge. Download JDK 8 Developer Preview release from http://jdk8.java.net/download.html.

Wednesday, April 3, 2013

JavaFX 3D Preview

JavaFX 3D Preview

Introduction to the 3D features in JavaFX 8.0: including meshes, lights, materials, textures, perspective camera node, and picking.

Thursday, March 7, 2013

JavaFX 3D Early Access Available


Container terminal monitoring with 3D JavaFX
This applications was jointly created by Navis (CargoTec), Oracle, and Canoo.

The video has been presented at the 2012 JavaOne conference in San Francisco as part of the Oracle strategy keynote

Download the latest JDK™ 8 Early Access Releases, currently 8 Build b79.

This page contains the list of 3D features schedule for JavaFX 8.0.