Wednesday, May 29, 2013

Simple example of JavaFX ComboBox

Simple example of JavaFX ComboBox
Simple example of JavaFX ComboBox


package javafxcombobox;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXComboBox extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        final ComboBox comboBox = new ComboBox();
        comboBox.getItems().addAll(
                "Item 1",
                "Item 2",
                "Item 3",
                "Item 4");
        comboBox.setValue("Item 1");
        
        final Label label = new Label();
        
        Button btn = new Button();
        btn.setText("Read comboBox");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                label.setText("selectd: " + comboBox.getValue());
            }
        });

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.setSpacing(5);
        vBox.getChildren().addAll(label, comboBox, btn);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


Next: JavaFX ComboBox for custom object

Thursday, May 23, 2013

Join this FREE Virtual Developer Day: Java

Join this FREE virtual event where you will learn about:
  • Improved developer productivity and HTML5 applications
  • What's new in Java that helps you begin programming on a wide range of embedded devices
  • Language improvements in Java SE to accelerate application development Watch informative tutorials that you can repeat at your own pace to improve your Java programming expertise, as well as engage in live chat sessions with technical experts.
Agenda of Virtual Developer Day: Java
Agenda of Virtual Developer Day: Java

Americas/Canada - Wednesday June 19, 2013
9:00 a.m. - 1:00 p.m. PDT / 12:00 p.m. - 4:00 p.m. EDT / 1:00 p.m. - 5:00 p.m. BRT

EMEA/Africa/Middle East - Tuesday June 25th, 2013
9:00:00 a.m. - 1:00pm BST / 10:00:00 a.m. - 2:00 p.m.CEST /

1:30:00 p.m. - 5:30:00 p.m. IST / 12:00:00 p.m. - 4:00 p.m. MSK /

08:00:00 a.m. - 12:00 p.m. Corresponding UTC (GMT)

Register: https://oracle.6connex.com/portal/java2013/login?langR=en_US&mcc=netbneansblog

Sunday, May 19, 2013

Android development arrive IntelliJ

EARLY ACCESS PREVIEW of Android Studio is available now. Android Studio is a new Android development environment based on IntelliJ IDEA. Similar to Eclipse with the ADT Plugin, Android Studio provides integrated Android developer tools for development and debugging.

Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs.

Saturday, May 18, 2013

OpenJDK Tests

Meet the OpenJDK Tests


Engineer Alan Bateman of the JDK team walks you through the tests available in OpenJDK, including where the tests live, what the tests do at a high level, and how they are run.

Thursday, May 16, 2013

Update ObservableList for TableView, in UI thread and background thread.

In the code example "Detect mouse click on JavaFX TableView and get the details of the clicked item", the content were pre-inserted in start() method. This example show how to add records into ObservableList for TableView. Also show how to do it in FX Application Thread (or UI thread) and in background thread.

Update ObservableList for TableView, in UI thread and background thread.
Update ObservableList for TableView, in UI thread and background thread.


  • To keep track of the record id, introduce a class variable, trackId, in Record class.
  • Output Platform.isFxApplicationThread() in constructor of Record; such that we can know the thread of the operation.
  • Add TextFields for user to enter fields of new records.
  • Add buttons to add record in UI thread and in background thread.

package javafx_testtableview;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
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.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    public static class Record {

        private static int trackId;
        private final SimpleIntegerProperty id;
        private final SimpleStringProperty name;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Record(String name, String lastName, String email) {
            
            System.out.println("Platform.isFxApplicationThread(): "
                        + Platform.isFxApplicationThread());
            
            this.id = new SimpleIntegerProperty(trackId);
            this.name = new SimpleStringProperty(name);
            this.lastName = new SimpleStringProperty(lastName);
            this.email = new SimpleStringProperty(email);
            trackId++;
        }

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

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

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

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

        public String getLastName() {
            return this.lastName.get();
        }

        public void setLastName(String lastName) {
            this.lastName.set(lastName);
        }

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

        public void setEmail(String email) {
            this.email.set(email);
        }
    }
    private TableView<Record> tableView = new TableView<>();
    private final ObservableList<Record> recordList = FXCollections.observableArrayList();

    private void prepareRecordList() {
        recordList.add(new Record("William", "Austin", "xxx@xxx.xxx"));
        recordList.add(new Record("Chris", "redfield", "yyy@yyy.yyy"));
        recordList.add(new Record("Java", "Buddy", "javabuddy@abc.yyy"));
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(new Group());
        primaryStage.setTitle("http://java-buddy.blogspot.com/");
        primaryStage.setWidth(400);
        primaryStage.setHeight(500);

        prepareRecordList();

        tableView.setEditable(false);

        Callback<TableColumn, TableCell> integerCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyIntegerTableCell cell = new MyIntegerTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        Callback<TableColumn, TableCell> stringCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyStringTableCell cell = new MyStringTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        TableColumn colId = new TableColumn("ID");
        colId.setCellValueFactory(
                new PropertyValueFactory<Record, String>("id"));
        colId.setCellFactory(integerCellFactory);

        TableColumn colName = new TableColumn("Name");
        colName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("name"));
        colName.setCellFactory(stringCellFactory);

        TableColumn colLastName = new TableColumn("Last Name");
        colLastName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("lastName"));
        colLastName.setCellFactory(stringCellFactory);

        TableColumn colEmail = new TableColumn("Email");
        colEmail.setCellValueFactory(
                new PropertyValueFactory<Record, String>("email"));
        colEmail.setCellFactory(stringCellFactory);

        tableView.setItems(recordList);
        tableView.getColumns().addAll(colId, colName, colLastName, colEmail);

        final VBox vbox = new VBox();

        Label label_name = new Label("Name");
        final TextField textField_name = new TextField();
        HBox hBox_name = new HBox();
        hBox_name.setSpacing(10);
        hBox_name.getChildren().addAll(label_name, textField_name);

        Label label_lastname = new Label("Last Name");
        final TextField textField_lastname = new TextField();
        HBox hBox_lastname = new HBox();
        hBox_lastname.setSpacing(10);
        hBox_lastname.getChildren().addAll(label_lastname, textField_lastname);

        Label label_email = new Label("email");
        final TextField textField_email = new TextField();
        HBox hBox_email = new HBox();
        hBox_email.setSpacing(10);
        hBox_email.getChildren().addAll(label_email, textField_email);

        Button button_Add = new Button("Add record");
        button_Add.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {

                //update recordList in UI thread
                recordList.add(new Record(
                        textField_name.getText(),
                        textField_lastname.getText(),
                        textField_email.getText()));

                textField_name.clear();
                textField_lastname.clear();
                textField_email.clear();
            }
        });

        Button button_AddBackGround = new Button("Add record in BACKGROUND");
        button_AddBackGround.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {

                final String bufferName = textField_name.getText();
                final String bufferLastName = textField_lastname.getText();
                final String bufferEmail = textField_email.getText();

                new Thread() {
                    public void run() {

                        //update recordList in Background thread
                        recordList.add(new Record(
                                bufferName,
                                bufferLastName,
                                bufferEmail));
                    };
                }.start();
                
                textField_name.clear();
                textField_lastname.clear();
                textField_email.clear();
            }
        });

        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(hBox_name, hBox_lastname, hBox_email,
                button_Add, button_AddBackGround, tableView);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    class MyIntegerTableCell extends TableCell<Record, Integer> {

        @Override
        public void updateItem(Integer item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyStringTableCell extends TableCell<Record, String> {

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyEventHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent t) {
            TableCell c = (TableCell) t.getSource();
            int index = c.getIndex();

            try {
                Record item = recordList.get(index);
                System.out.println("id = " + item.getId());
                System.out.println("name = " + item.getName());
                System.out.println("lastName = " + item.getLastName());
                System.out.println("email = " + item.getEmail());
            } catch (IndexOutOfBoundsException exception) {
                //...
            }

        }
    }
}


Class variables (static) of class

Class variables is a variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Wednesday, May 15, 2013

FREE online ebook: Java Enterprise Performance

Java Enterprise Performance
Java Enterprise Performance

Performance is a topic of increasing importance for anyone who uses applications to support their business activities. Today performance engineers and architects as well as operations people have to ensure that complex application landscapes work seamlessly and problems are resolved fast and with minimal effort.

This book contains over 70 years of application performance knowledge. We, the authors have worked in this field building large scale applications and more recently application performance solutions. In addition we have developed numerous training courses, work closely with IT practitioners implementing application performance management solutions and processes, and we are regular speakers at software conference on performance-related topics.

Our goal is to provide a reference book for people like us, who are passionate about application performance and work daily on improving it. We found that while there are a lot of books about performance, a definitive reference text for day-to-day performance management is not available. We want to provide exactly this reference, where you can lookup information and quickly find the answers to your problems.

Read it online: http://javabook.compuware.com/content/start.aspx

Monday, May 13, 2013

Hide empty cell of TableView with CSS

Similar to the post "Apply style sheet on ListView to hide empty cells", we can create our custom css to set a specific color for all empty.

Hide empty cell of TableView with CSS
Hide empty cell of TableView with CSS


Modify from last article "Detect mouse click on JavaFX TableView and get the details of the clicked item".

Create javafx_testtableview/style_tableview.css file, copy the code from Example 26-3 Setting Color for Empty Rows in a Table View of Customization of UI Controls.
.table-row-cell:empty {
    -fx-background-color: lightyellow;
}
 
.table-row-cell:empty .table-cell {
    -fx-border-width: 0px;
}


Apply css file on the TabletView, by calling:

tableView.getStylesheets().add("javafx_testtableview/style_tableview");

Also modify handle(MouseEvent t) of MyEventHandler to check IndexOutOfBoundsException on recordList.get(index).

package javafx_testtableview;

import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    public static class Record {

        private final SimpleIntegerProperty id;
        private final SimpleStringProperty name;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Record(int id, String name, String lastName, String email) {
            this.id = new SimpleIntegerProperty(id);
            this.name = new SimpleStringProperty(name);
            this.lastName = new SimpleStringProperty(lastName);
            this.email = new SimpleStringProperty(email);
        }

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

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

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

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

        public String getLastName() {
            return this.lastName.get();
        }

        public void setLastName(String lastName) {
            this.lastName.set(lastName);
        }

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

        public void setEmail(String email) {
            this.email.set(email);
        }
    }
    private TableView<Record> tableView = new TableView<>();
    private final ObservableList<Record> recordList = FXCollections.observableArrayList();

    private void prepareRecordList() {
        recordList.add(new Record(12, "William", "Austin", "xxx@xxx.xxx"));
        recordList.add(new Record(15, "Chris", "redfield", "yyy@yyy.yyy"));
        recordList.add(new Record(1, "Java", "Buddy", "javabuddy@abc.yyy"));
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(new Group());
        primaryStage.setTitle("http://java-buddy.blogspot.com/");
        primaryStage.setWidth(400);
        primaryStage.setHeight(500);

        prepareRecordList();

        tableView.setEditable(false);

        Callback<TableColumn, TableCell> integerCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyIntegerTableCell cell = new MyIntegerTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        Callback<TableColumn, TableCell> stringCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyStringTableCell cell = new MyStringTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        TableColumn colId = new TableColumn("ID");
        colId.setCellValueFactory(
                new PropertyValueFactory<Record, String>("id"));
        colId.setCellFactory(integerCellFactory);

        TableColumn colName = new TableColumn("Name");
        colName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("name"));
        colName.setCellFactory(stringCellFactory);

        TableColumn colLastName = new TableColumn("Last Name");
        colLastName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("lastName"));
        colLastName.setCellFactory(stringCellFactory);

        TableColumn colEmail = new TableColumn("Email");
        colEmail.setCellValueFactory(
                new PropertyValueFactory<Record, String>("email"));
        colEmail.setCellFactory(stringCellFactory);

        tableView.setItems(recordList);
        tableView.getColumns().addAll(colId, colName, colLastName, colEmail);

        tableView.getStylesheets().add("javafx_testtableview/style_tableview");

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().add(tableView);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    class MyIntegerTableCell extends TableCell<Record, Integer> {

        @Override
        public void updateItem(Integer item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyStringTableCell extends TableCell<Record, String> {

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyEventHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent t) {
            TableCell c = (TableCell) t.getSource();
            int index = c.getIndex();

            try {
                Record item = recordList.get(index);
                System.out.println("id = " + item.getId());
                System.out.println("name = " + item.getName());
                System.out.println("lastName = " + item.getLastName());
                System.out.println("email = " + item.getEmail());
            } catch (IndexOutOfBoundsException exception) {
                //...
            }

        }
    }
}


Sunday, May 12, 2013

Detect mouse click on JavaFX TableView and get the details of the clicked item

The example demonstrate how to detect mouse click event on JavaFX TableView by implement CellFactory, to get the details of the clicked item.

package javafx_testtableview;

import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    public static class Record {

        private final SimpleIntegerProperty id;
        private final SimpleStringProperty name;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Record(int id, String name, String lastName, String email) {
            this.id = new SimpleIntegerProperty(id);
            this.name = new SimpleStringProperty(name);
            this.lastName = new SimpleStringProperty(lastName);
            this.email = new SimpleStringProperty(email);
        }

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

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

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

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

        public String getLastName() {
            return this.lastName.get();
        }

        public void setLastName(String lastName) {
            this.lastName.set(lastName);
        }

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

        public void setEmail(String email) {
            this.email.set(email);
        }
    }
    private TableView<Record> tableView = new TableView<>();
    private final ObservableList<Record> recordList = FXCollections.observableArrayList();

    private void prepareRecordList() {
        recordList.add(new Record(12, "William", "Austin", "xxx@xxx.xxx"));
        recordList.add(new Record(15, "Chris", "redfield", "yyy@yyy.yyy"));
        recordList.add(new Record(1, "Java", "Buddy", "javabuddy@abc.yyy"));
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(new Group());
        primaryStage.setTitle("http://java-buddy.blogspot.com/");
        primaryStage.setWidth(400);
        primaryStage.setHeight(500);

        prepareRecordList();

        tableView.setEditable(false);

        Callback<TableColumn, TableCell> integerCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyIntegerTableCell cell = new MyIntegerTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        Callback<TableColumn, TableCell> stringCellFactory =
                new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                MyStringTableCell cell = new MyStringTableCell();
                cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
                return cell;
            }
        };

        TableColumn colId = new TableColumn("ID");
        colId.setCellValueFactory(
                new PropertyValueFactory<Record, String>("id"));
        colId.setCellFactory(integerCellFactory);

        TableColumn colName = new TableColumn("Name");
        colName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("name"));
        colName.setCellFactory(stringCellFactory);

        TableColumn colLastName = new TableColumn("Last Name");
        colLastName.setCellValueFactory(
                new PropertyValueFactory<Record, String>("lastName"));
        colLastName.setCellFactory(stringCellFactory);

        TableColumn colEmail = new TableColumn("Email");
        colEmail.setCellValueFactory(
                new PropertyValueFactory<Record, String>("email"));
        colEmail.setCellFactory(stringCellFactory);

        tableView.setItems(recordList);
        tableView.getColumns().addAll(colId, colName, colLastName, colEmail);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().add(tableView);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    class MyIntegerTableCell extends TableCell<Record, Integer> {

        @Override
        public void updateItem(Integer item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyStringTableCell extends TableCell<Record, String> {

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? null : getString());
            setGraphic(null);
        }

        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
    }

    class MyEventHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent t) {
            TableCell c = (TableCell) t.getSource();
            int index = c.getIndex();
            System.out.println("id = " + recordList.get(index).getId());
            System.out.println("name = " + recordList.get(index).getName());
            System.out.println("lastName = " + recordList.get(index).getLastName());
            System.out.println("email = " + recordList.get(index).getEmail());
        }
    }
}


Detect mouse click on JavaFX TableView and get the details of the clicked item
Detect mouse click on JavaFX TableView and get the details of the clicked item


Next:
- Hide empty cell of TableView with CSS.
- Update ObservableList for TableView, in UI thread and background thread.


Thursday, May 9, 2013

Apply style sheet on ListView to hide empty cells

The default style of ListView will fill all cells, include empty cells, as shown in last article. You can create your own style sheets to override the styles in the default style sheet and to add your own styles. Typically style sheets that you create have an extension of .css and are located in the same directory as the main class for your JavaFX application.

In the case of the following file structure, using the code:

listView.getStylesheets().add("javafx_listview/style_listview");


To hide empty list cell, edit style_listview.css.

.list-cell:empty {
    visibility:hidden;
}


Full Java code:

package javafx_listview;

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    class MyObject {

        String day;
        int number;
        Color color;

        MyObject(String d, int n, Color c) {
            day = d;
            number = n;
            color = c;
        }

        String getDay() {
            return day;
        }

        int getNumber() {
            return number;
        }
        
        Color getColor(){
            return color;
        }
    }
    List<MyObject> myList;

    //Create dummy list of MyObject
    private void prepareMyList() {
        myList = new ArrayList<>();
        myList.add(new MyObject("Sunday", 50, Color.RED));
        myList.add(new MyObject("Monday", 60, Color.GREEN));
        myList.add(new MyObject("Tuesday", 20, Color.BLUE));
        myList.add(new MyObject("Wednesday", 90, Color.VIOLET));
        myList.add(new MyObject("Thursday", 30, Color.BLUEVIOLET));
        myList.add(new MyObject("Friday", 62, Color.AZURE));
        myList.add(new MyObject("Saturday", 65, Color.GOLD));

    }

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("http://java-buddy.blogspot.com/");

        prepareMyList();
        ListView<MyObject> listView = new ListView<>();
        ObservableList<MyObject> myObservableList = FXCollections.observableList(myList);
        listView.setItems(myObservableList);
        
        listView.getStylesheets().add("javafx_listview/style_listview");

        listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>() {
            @Override
            public ListCell<MyObject> call(ListView<MyObject> p) {

                ListCell<MyObject> cell = new ListCell<MyObject>() {
                    @Override
                    protected void updateItem(MyObject t, boolean bln) {
                        super.updateItem(t, bln);
                        
                        Rectangle rect = new Rectangle(100, 20);
                        if (t != null) {
                            setText(t.getDay() + ":" + t.getNumber());
                            Color col = t.getColor();
                            setTextFill(col);
                        }
                    }
                };

                return cell;
            }
        });


        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Output:

Apply style sheet on ListView to hide empty cells
Apply style sheet on ListView to hide empty cells


Related:
- Hide empty cell of TableView with CSS


Wednesday, May 8, 2013

Customized ListView

This code demonstrate how to implement customized ListView with different color on cells.

Customized ListView
Customized ListView


package javafx_listview;

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    class MyObject {

        String day;
        int number;
        Color color;

        MyObject(String d, int n, Color c) {
            day = d;
            number = n;
            color = c;
        }

        String getDay() {
            return day;
        }

        int getNumber() {
            return number;
        }
        
        Color getColor(){
            return color;
        }
    }
    List<MyObject> myList;

    //Create dummy list of MyObject
    private void prepareMyList() {
        myList = new ArrayList<>();
        myList.add(new MyObject("Sunday", 50, Color.RED));
        myList.add(new MyObject("Monday", 60, Color.GREEN));
        myList.add(new MyObject("Tuesday", 20, Color.BLUE));
        myList.add(new MyObject("Wednesday", 90, Color.VIOLET));
        myList.add(new MyObject("Thursday", 30, Color.BLUEVIOLET));
        myList.add(new MyObject("Friday", 62, Color.AZURE));
        myList.add(new MyObject("Saturday", 65, Color.GOLD));

    }

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("http://java-buddy.blogspot.com/");

        prepareMyList();
        ListView<MyObject> listView = new ListView<>();
        ObservableList<MyObject> myObservableList = FXCollections.observableList(myList);
        listView.setItems(myObservableList);

        listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>() {
            @Override
            public ListCell<MyObject> call(ListView<MyObject> p) {

                ListCell<MyObject> cell = new ListCell<MyObject>() {
                    @Override
                    protected void updateItem(MyObject t, boolean bln) {
                        super.updateItem(t, bln);
                        
                        Rectangle rect = new Rectangle(100, 20);
                        if (t != null) {
                            setText(t.getDay() + ":" + t.getNumber());
                            Color col = t.getColor();
                            setTextFill(col);
                        }
                    }
                };

                return cell;
            }
        });


        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Monday, May 6, 2013

JDK™ 8 Early Access Releases updated

JDK™ 8 Early Access Releases 8 Build b88 available here: http://jdk8.java.net/download.html.

Remark: please check comment by Carlos De Luna, B88 doesn't work on Netbeans currently!

Sort List of custom object

Last example display un-sorted List of custom object in JavaFX ListView. In order to sort custom object, we have to implement our Comparator.

Example:

package javafx_listview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    class MyObject {

        String day;
        int number;

        MyObject(String d, int n) {
            day = d;
            number = n;
        }

        String getDay() {
            return day;
        }

        int getNumber() {
            return number;
        }
    }
    List<MyObject> myList;

    //Create dummy list of MyObject
    private void prepareMyList() {
        myList = new ArrayList<>();
        myList.add(new MyObject("Sunday", 50));
        myList.add(new MyObject("Monday", 60));
        myList.add(new MyObject("Tuesday", 20));
        myList.add(new MyObject("Wednesday", 90));
        myList.add(new MyObject("Thursday", 30));
        myList.add(new MyObject("Friday", 62));
        myList.add(new MyObject("Saturday", 65));

        //sort myList
        Collections.sort(myList, comparatorMyObject_byDay);
    }
    
    //Comparator for String, by Day
    Comparator<? super MyObject> comparatorMyObject_byDay = new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.getDay().compareToIgnoreCase(o2.getDay());
        }
    };
    
    //Comparator for int, by Number
    Comparator<? super MyObject> comparatorMyObject_byNumber = new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.getNumber() - o2.getNumber();
        }
    };

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("http://java-buddy.blogspot.com/");

        prepareMyList();
        ListView<MyObject> listView = new ListView<>();
        ObservableList<MyObject> myObservableList = FXCollections.observableList(myList);
        listView.setItems(myObservableList);

        listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>() {
            @Override
            public ListCell<MyObject> call(ListView<MyObject> p) {

                ListCell<MyObject> cell = new ListCell<MyObject>() {
                    @Override
                    protected void updateItem(MyObject t, boolean bln) {
                        super.updateItem(t, bln);
                        if (t != null) {
                            setText(t.getDay() + ":" + t.getNumber());
                        }
                    }
                };

                return cell;
            }
        });


        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Sort List of custom object
Sort List of custom object


Sunday, May 5, 2013

Implement JavaFX ListView for custom object

This example demonstrate how to implement ListView of custom object.

JavaFX ListView for custom object
JavaFX ListView for custom object

Here we define a custom class, MyObject. And a List of object of MyObject class, myList. We have to generate ObservableList<myobject> from ArrayList<myobject> by calling FXCollections.observableList(myList). Also have to sets a new cell factory to use in the ListView, by calling setCellFactory() method.

Here is the example code:

package javafx_listview;

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ListView extends Application {
    
    class MyObject{
        String day;
        int number;
        
        MyObject(String d, int n){
            day = d;
            number = n;
        }
        
        String getDay(){
            return day;
        }
        
        int getNumber(){
            return number;
        }
    }
    
    List<MyObject> myList;
    
    //Create dummy list of MyObject
    private void prepareMyList(){
        myList = new ArrayList<>();
        myList.add(new MyObject("Sunday", 50));
        myList.add(new MyObject("Monday", 60));
        myList.add(new MyObject("Tuesday", 20));
        myList.add(new MyObject("Wednesday", 90));
        myList.add(new MyObject("Thursday", 30));
        myList.add(new MyObject("Friday", 62));
        myList.add(new MyObject("Saturday", 65));
    }

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("http://java-buddy.blogspot.com/");

        prepareMyList();
        ListView<MyObject> listView = new ListView<>();
        ObservableList<MyObject> myObservableList = FXCollections.observableList(myList);
        listView.setItems(myObservableList);
        
        listView.setCellFactory(new Callback<ListView<MyObject>, ListCell<MyObject>>(){

            @Override
            public ListCell<MyObject> call(ListView<MyObject> p) {
                
                ListCell<MyObject> cell = new ListCell<MyObject>(){

                    @Override
                    protected void updateItem(MyObject t, boolean bln) {
                        super.updateItem(t, bln);
                        if (t != null) {
                            setText(t.getDay() + ":" + t.getNumber());
                        }
                    }

                };
                
                return cell;
            }
        });


        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Next:
- Sort List of custom object
- Customized ListView


Related: Implement ListView using JavaFX

Draw scaled image on JavaFX Canvas, with GraphicsContext.drawImage(image, x, y, w, h)

The method GraphicsContext.drawImage(image, x, y, w, h) draws an image into the given destination rectangle of the canvas. The Image is scaled to fit into the destination rectagnle. Alternatively, the method GraphicsContext.drawImage(image, x, y) draw unscaled image on canvas.

This example show how to draw scaled image on JavaFX canvas, on rectangle assigned by mouse pressed and released events.

Draw scaled image on JavaFX Canvas
Draw scaled image on JavaFX Canvas


package javafx_drawoncanvas;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_DrawOnCanvas extends Application {
    
    final static int CANVAS_WIDTH = 400;
    final static int CANVAS_HEIGHT = 400;

    double x0, y0, x1, y1;
    Image image;

    @Override
    public void start(final Stage primaryStage) {

        final Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
        final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
        initDraw(graphicsContext);
        
        canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                
                x0 = event.getX();
                y0 = event.getY();

            }
        });
        
        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {

            }
        });

        canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                
                x1 = event.getX();
                y1 = event.getY();
                
                double x = (x0 > x1) ? x1 : x0;
                double y = (y0 > y1) ? y1 : y0;
                double w = (x0 > x1) ? x0-x1 : x1-x0;
                double h = (y0 > y1) ? y0-y1 : y1-y0;
                
                graphicsContext.drawImage(image, x, y, w, h);
            }
        });

        Group root = new Group();
        VBox vBox = new VBox();
        vBox.getChildren().addAll(canvas);
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 400, 425);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private void initDraw(GraphicsContext gc){

        double canvasWidth = gc.getCanvas().getWidth();
        double canvasHeight = gc.getCanvas().getHeight();
        
        gc.setFill(Color.LIGHTGRAY);
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(5);

        gc.fill();
        gc.strokeRect(
                0,              //x of the upper left corner
                0,              //y of the upper left corner
                canvasWidth,    //width of the rectangle
                canvasHeight);  //height of the rectangle

        gc.setLineWidth(1);
        
        image = new Image(getClass().getResourceAsStream("duke_44x80.png"));
    }
    
}


Thursday, May 2, 2013