Saturday, August 31, 2013

Set background color of JavaFX ListView cells, with CSS

The old post show how to "Hide empty cell of TableView with CSS". This example apply similar approach, to set background color for various cells, empty, hover, selected.

Set background color of JavaFX ListView cells
Set background color of JavaFX ListView cells

Create javafx_testtableview/style_tableview.css file.
.table-row-cell:empty {
    -fx-background-color: khaki;
    -fx-border-color: grey
}

.table-row-cell:hover{
    -fx-background-color: blanchedalmond;
}

.table-row-cell:selected{
    -fx-background-color: chocolate;
}


Java code.
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"));
        recordList.add(new Record(2, "Eric", "Buddy", "ericbuddy@abc.yyy"));
        recordList.add(new Record(3, "Peter", "handsome", "peter@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(400);
 
        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) {
                //...
            }
 
        }
    }
}

Friday, August 30, 2013

JavaFX example: bind more than one value with NumberBinding

This example show to to bind the value of sliderSum to the sum of slider1 and slider2 values with NumberBinding.

bind more than one value with NumberBinding
Bind more than one value with NumberBinding

package javafx_numberbinding;

import javafx.application.Application;
import javafx.beans.binding.NumberBinding;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_NumberBinding extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        Slider slider1 = new Slider(0, 100, 0);
        Slider slider2 = new Slider(0, 50, 0);
        Slider sliderBind1 = new Slider(0, 100, 0);
        Slider sliderBind2 = new Slider(0, 50, 0);
        Slider sliderSum = new Slider(0, 150, 0);
        
        sliderBind1.valueProperty().bind(slider1.valueProperty());
        sliderBind2.valueProperty().bind(slider2.valueProperty());
        
        NumberBinding numberSum = slider1.valueProperty().add(slider2.valueProperty());
        sliderSum.valueProperty().bind(numberSum);
        
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.setSpacing(5);
        vBox.getChildren().addAll(
                slider1, 
                slider2,
                sliderBind1,
                sliderBind2,
                sliderSum);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}


Sunday, August 25, 2013

Implement custom Properties for bind() and ChangeListener()

In the post of "JavaFX example of Service", the UI elements progressBar and labelCount are bind to build-in properties, progressProperty and messageProperty, of Service. Now I want to update progressBar and labelCount in 5 second; we can create our custom Properties, process5sec and Message5sec, such that we can bind them to UI elements or addListener() to trace the changing for them.

Implement custom Properties for bind() and ChangeListener()
Implement custom Properties for bind() and ChangeListener()

package javafx_service;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
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.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

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

    MyService myService;

    @Override
    public void start(Stage primaryStage) {

        final ProgressBar progressBar = new ProgressBar();
        final Label labelCount = new Label();
        final Label labelState = new Label();
        final Label labelSucceeded = new Label();

        myService = new MyService();

        myService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnSucceeded");
            }
        });

        myService.setOnRunning(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnRunning");
            }
        });

        myService.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnFailed");
            }
        });

        myService.process5secProperty().addListener(new ChangeListener(){

            @Override
            public void changed(ObservableValue ov, Object t, Object t1) {
                
                double p = (double)(((Integer)t1).intValue());
                progressBar.setProgress(p/50);
            }
        });
        
        labelCount.textProperty().bind(myService.Message5sec);

        Button btnStart = new Button("Start Service");
        btnStart.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                myService.start();
            }
        });

        Button btnReadTaskState = new Button("Read Service State");
        btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                labelState.setText(myService.getState().toString());
            }
        });

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.setSpacing(5);
        vBox.getChildren().addAll(
                progressBar,
                labelCount,
                btnStart,
                btnReadTaskState,
                labelState,
                labelSucceeded);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    private class MyService extends Service<Void> {

        private final IntegerProperty process5sec = new SimpleIntegerProperty();

        public int getProcess5sec() {
            return process5sec.get();
        }

        public void setProcess5sec(int value) {
            process5sec.set(value);
        }

        public IntegerProperty process5secProperty() {
            return process5sec;
        }
        private final StringProperty Message5sec = new SimpleStringProperty();

        public String getMessage5sec() {
            return Message5sec.get();
        }

        public void setMessage5sec(String value) {
            Message5sec.set(value);
        }

        public StringProperty Message5secProperty() {
            return Message5sec;
        }

        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    int max = 50;
                    for (int i = 1; i <= max; i++) {
                        if (isCancelled()) {
                            break;
                        }

                        if (i % 5 == 0) {
                            final int i5sec = i;
                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    setProcess5sec(i5sec);
                                    setMessage5sec(String.valueOf(i5sec));    
                                }
                            });
                        }

                        Thread.sleep(100);
                    }
                    return null;
                }
            };
        }
    }
}



Friday, August 23, 2013

JavaFX example: Modality

javafx.stage.Modality defines the possible modality types for a Stage.


package javafx_modality;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;

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

    @Override
    public void start(Stage primaryStage) {
        
        /*
         * initModality() much be called prior to making the stage visible. 
         * The modality is one of: Modality.NONE, Modality.WINDOW_MODAL, 
         * or Modality.APPLICATION_MODAL.
         */

        //NONE
        Button btnNONE = new Button();
        btnNONE.setText("Open NONE dialog");
        btnNONE.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Stage dialogNONE = new Stage();
                dialogNONE.initModality(Modality.NONE);

                Scene sceneNONE = new Scene(VBoxBuilder.create()
                        .children(
                            new Text("NONE dialog"), 
                            new Text("Defines a top-level window that is not "
                            + "modal and does not block any other window."))
                        .alignment(Pos.CENTER)
                        .padding(new Insets(10))
                        .build());

                dialogNONE.setTitle("NONE dialog");
                dialogNONE.setScene(sceneNONE);
                dialogNONE.show();
            }
        });
        
        //APPLICATION_MODAL
        Button btnAPPLICATION_MODAL = new Button();
        btnAPPLICATION_MODAL.setText("Open APPLICATION_MODAL dialog");
        btnAPPLICATION_MODAL.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Stage dialogAPPLICATION_MODAL = new Stage();
                dialogAPPLICATION_MODAL.initModality(Modality.APPLICATION_MODAL);

                Scene sceneAPPLICATION_MODAL = new Scene(VBoxBuilder.create()
                        .children(
                            new Text("APPLICATION_MODAL dialog"), 
                            new Text("Defines a modal window that blocks events "
                            + "from being delivered to any other application window."))
                        .alignment(Pos.CENTER)
                        .padding(new Insets(10))
                        .build());

                dialogAPPLICATION_MODAL.setTitle("APPLICATION_MODAL dialog");
                dialogAPPLICATION_MODAL.setScene(sceneAPPLICATION_MODAL);
                dialogAPPLICATION_MODAL.show();
            }
        });
        
        //WINDOW_MODAL
        Button btnWINDOW_MODAL = new Button();
        btnWINDOW_MODAL.setText("Open WINDOW_MODAL dialog");
        btnWINDOW_MODAL.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Stage dialogWINDOW_MODAL = new Stage();
                dialogWINDOW_MODAL.initModality(Modality.WINDOW_MODAL);

                Scene sceneWINDOW_MODAL = new Scene(VBoxBuilder.create()
                        .children(
                            new Text("WINDOW_MODAL dialog"), 
                            new Text("Defines a modal window that block events "
                            + "from being delivered to its entire owner window "
                            + "hierarchy."))
                        .alignment(Pos.CENTER)
                        .padding(new Insets(10))
                        .build());

                dialogWINDOW_MODAL.setTitle("WINDOW_MODAL dialog");
                dialogWINDOW_MODAL.setScene(sceneWINDOW_MODAL);
                dialogWINDOW_MODAL.show();
            }
        });
        
        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        vBox.setSpacing(10);
        vBox.getChildren().addAll(
                btnNONE, 
                btnAPPLICATION_MODAL, 
                btnWINDOW_MODAL);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


Wednesday, August 21, 2013

An Introduction to Network Programming with Java: Java 7 Compatible


An Introduction to Network Programming with Java: Java 7 Compatible

Since the second edition of this text, the use of the Internet and networks generally has continued to expand at a phenomenal rate. This has led to both an increase in demand for network software and to improvements in the technology used to run such networks, with the latter naturally leading to changes in the former. During this time, the Java libraries have been updated to keep up with the new developments in network technology, so that the Java programming language continues to be one of the mainstays of network software development.

In providing a very readable text that avoids getting immersed in low-level technical details, while still providing a useful, practical guide to network programming for both undergraduates and busy IT professionals, this third edition continues the trend of its predecessors. To retain its currency, the text has been updated to reflect changes that have taken place in Java's network technology over the past seven years (including the release of Java 7), whilst retaining its notable features of numerous code examples, screenshots and end-of-chapter exercises.

Tuesday, August 20, 2013

JavaFX example: Service

JavaFX example: Service
JavaFX example: Service


package javafx_service;

import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
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.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

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

    MyService myService;

    @Override
    public void start(Stage primaryStage) {

        final ProgressBar progressBar = new ProgressBar();
        final Label labelCount = new Label();
        final Label labelState = new Label();
        final Label labelSucceeded = new Label();

        myService = new MyService();

        myService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnSucceeded");
            }
        });

        myService.setOnRunning(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnRunning");
            }
        });

        myService.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                labelSucceeded.setText("OnFailed");
            }
        });

        progressBar.progressProperty().bind(myService.progressProperty());
        labelCount.textProperty().bind(myService.messageProperty());

        Button btnStart = new Button("Start Service");
        btnStart.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                myService.start();
            }
        });

        Button btnReadTaskState = new Button("Read Service State");
        btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                labelState.setText(myService.getState().toString());
            }
        });

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.setSpacing(5);
        vBox.getChildren().addAll(
                progressBar,
                labelCount,
                btnStart,
                btnReadTaskState,
                labelState,
                labelSucceeded);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    private class MyService extends Service<Void> {

        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    int max = 50;
                    for (int i = 1; i <= max; i++) {
                        if (isCancelled()) {
                            break;
                        }

                        updateProgress(i, max);
                        updateMessage(String.valueOf(i));

                        Thread.sleep(100);
                    }
                    return null;
                }
            };
        }
    }
}


Related:
- Implement custom Properties for bind() and ChangeListener()

Monday, August 19, 2013

JavaFX example: Task

JavaFX example: Task
JavaFX example: Task


package javafx_task;

import javafx.application.Application;
import javafx.concurrent.Task;
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.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

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

    @Override
    public void start(Stage primaryStage) {

        final Task task;
        task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                int max = 50;
                for (int i = 1; i <= max; i++) {
                    if (isCancelled()) {
                        break;
                    }
                    updateProgress(i, max);
                    updateMessage(String.valueOf(i));

                    Thread.sleep(100);
                }
                return null;
            }
        };

        ProgressBar progressBar = new ProgressBar();
        progressBar.setProgress(0);
        progressBar.progressProperty().bind(task.progressProperty());
        
        Label labelCount = new Label();
        labelCount.textProperty().bind(task.messageProperty());
        
        final Label labelState = new Label();
        
        Button btnStart = new Button("Start Task");
        btnStart.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                new Thread(task).start();
            }
        });
        
        Button btnReadTaskState = new Button("Read Task State");
        btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                labelState.setText(task.getState().toString());
            }
        });
                      

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.setSpacing(5);
        vBox.getChildren().addAll(
                progressBar, 
                labelCount,
                btnStart,
                btnReadTaskState, 
                labelState);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

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




Saturday, August 17, 2013

JavaFX example: ToggleGroup

JavaFX example: ToggleGroup
JavaFX example: ToggleGroup


package javafx_togglegroup;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ToggleGroup extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        ToggleButton toggleButton1 = new ToggleButton("Button 1");
        ToggleButton toggleButton2 = new ToggleButton("Button 2");
        ToggleButton toggleButton3 = new ToggleButton("Button 3");
        
        ToggleGroup toggleGroup = new ToggleGroup();
        toggleButton1.setToggleGroup(toggleGroup);
        toggleButton2.setToggleGroup(toggleGroup);
        toggleButton3.setToggleGroup(toggleGroup);
         
        HBox hBox = new HBox();
        hBox.getChildren().addAll(toggleButton1, toggleButton2, toggleButton3);
        
        Group root = new Group();
        root.getChildren().add(hBox);
         
        Scene scene = new Scene(root, 300, 250);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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




Friday, August 16, 2013

Simple example of using JavaFX ToolBar

Simple example of JavaFX ToolBar
Simple example of JavaFX ToolBar


package javafx_toolbar;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ToolBar extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Button toolButton1 = new Button("Tool 1");
        toolButton1.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                System.out.println("Tool 1 clicked!");
            }
        });
        
        ToolBar toolBar = new ToolBar();
        toolBar.getItems().add(toolButton1);
        toolBar.getItems().add(new Button("Tool Opt2"));
        toolBar.getItems().add(new Button("Tool Opt3"));
        toolBar.setPrefWidth(300);
        
        Group root = new Group();
        root.getChildren().add(toolBar);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


Thursday, August 15, 2013

Introducing Java EE 7: A Look at What's New


Introducing Java EE 7:  A Look at What’s New guides you through the new features and enhancements in each of the technologies comprising the Java EE platform.  Readers of this book will not have to wade through introductory material or information covering features that have been part of the EE platform for years.  Instead, developers can pick this book up and read it to brush up on those features that have changed or have been added for the EE 7 release.  This handy reference helps you move forward from Java EE 6 to the new EE 7 platform quickly and easily.

Java is a mature programming language that has been refined over the years into a productive language widely used in enterprise application development.  Although the language contains frameworks and methodologies that have been used for years, it is important to make use of the most current features available in the language in order to achieve the best results.  Introducing Java EE 7:  A Look at What’s New covers the solutions using the most current Java Enterprise technologies, including EJB 3.2, JSF 2.2, and JAX-RS 2.0.  Build a streamlined and reliable application that uses the latest in Java technologies, and develop it much faster than you did with the older technologies.  Rejuvenate your Java expertise to use the freshest capabilities, or perhaps learn Java Enterprise development for the first time and discover one of the most widely used and most powerful technologies available for application development today.  Get up and running quickly with the new features of EE 7!
  • Designed to get you up and running quickly with the newly released Java EE 7
  • Includes real world examples of how to use new and updated features.
  • Demonstrates the latest productivity enhancements in the platform

What you’ll learn

  • Develop using the latest in Java EE 7 technologies
  • Deploy the most current features in Java Servlets
  • Make use of HTML5 in your Java Enterprise applications
  • Create enterprise database applications using the latest features in EJB
  • Improve application code through Context Dependency Injection (CDI)
  • Exploit the power of RESTful web services

Who this book is for


Introducing Java EE 7: A Look at What’s New is intended for developers already familiar with the basic concepts of Java Enterprise Edition development.  The book jumps right into covering new features in Java EE 7, and gets down into code from the very beginning.  The book is organized to be a handy reference for those who need information quickly on a particular topic while transitioning from Java EE 6 to Java EE 7, but it can also be read front to back.

Table of Contents

  1. Part I: Java Web Tier - New Servlet Features
  2. Part I: Java Web Tier - JavaServer  Faces and Facelets
  3. Part I: Java Web Tier - Expression Language
  4. Part II: Business Logic and Data - Object-Relational Mapping using JPA
  5. Part II: Business Logic and Data -  Business Logic using EJB
  6. Part II: Business Logic and Data - Validating Data
  7. Part II: Business Logic and Data - Contexts and Dependency Injection
  8. Part III: Web Services and HTML - Building RESTful Web Services
  9. Part III: Web Services and HTML - WebSockets and JSON
  10. Part IV: Under the Covers - New Java Message Service Features
  11. Part IV: Under the Covers - Batch Applications, Caching, and Concurrency
  12. Part IV: Under the Covers - Developing Java EE 7 Applications Using Netbeans
June 26, 2013  1430258489  978-1430258483 1


Tuesday, August 13, 2013

Embed Google PageSpeed Insights in JavaFX WebView

Google's PageSpeed Insights is a tool that helps developers optimize their web pages by analyzing the pages and generating tailored suggestions to make the pages faster. You can use the PageSpeed Insights API to programmatically generate PageSpeed scores and suggestions.

Using Insights API, it's easy to embed the result to JavaFX application with WenView. This example demonstrate how to do it.

Embed Google PageSpeed Insights in JavaFX WebView
Embed Google PageSpeed Insights in JavaFX WebView
To acquire an API key, visit the APIs Console. In the Services pane, activate the PageSpeed Insights API; if the Terms of Service appear, read and accept them.

Next, go to the API Access pane. The API key is near the bottom of that pane, in the section titled "Simple API Access."

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

Create HTML file, PageSpeedTest.html, to be embedded in WebView, with Javascript code of Insights API. Basically, it copy the example code from PageSpeed Insights Developer's Guide (v1) with little bit modification. You have to insert your API key in API_KEY.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script>
            // Specify your actual API key here:
            var API_KEY = 'insert your API key here';

            // Specify the URL you want PageSpeed results for here:
            var URL_TO_GET_RESULTS_FOR = 'http://java-buddy.blogspot.com/';
        </script>

        <script>
            var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
            var CHART_API_URL = 'http://chart.apis.google.com/chart?';

            // Object that will hold the callbacks that process results from the
            // PageSpeed Insights API.
            var callbacks = {};

            // Invokes the PageSpeed Insights API. The response will contain
            // JavaScript that invokes our callback with the PageSpeed results.
            function runPagespeed() {

                alert('runPagespeed()');
                document.getElementById('testedurl').innerHTML = URL_TO_GET_RESULTS_FOR;

                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.async = true;
                var query = [
                    'url=' + URL_TO_GET_RESULTS_FOR,
                    'callback=runPagespeedCallbacks',
                    'key=' + API_KEY
                ].join('&');
                s.src = API_URL + query;
                document.head.insertBefore(s, null);
            }

            // Our JSONP callback. Checks for errors, then invokes our callback handlers.
            function runPagespeedCallbacks(result) {

                alert('runPagespeedCallbacks(result)');

                if (result.error) {

                    alert('result.error');

                    var errors = result.error.errors;
                    for (var i = 0, len = errors.length; i < len; ++i) {
                        if (errors[i].reason === 'badRequest' && API_KEY === 'yourAPIKey') {
                            alert('Please specify your Google API key in the API_KEY variable.');
                        } else {
                            // NOTE: your real production app should use a better
                            // mechanism than alert() to communicate the error to the user.
                            alert(errors[i].message);
                        }
                    }
                    return;
                }

                // Dispatch to each function on the callbacks object.
                for (var fn in callbacks) {
                    var f = callbacks[fn];
                    if (typeof f === 'function') {
                        callbacks[fn](result);
                    }
                }

                alert('runPagespeedCallbacks(result) finished!');
            }

        </script>

        <script>
            callbacks.displayPageSpeedScore = function(result) {
                var score = result.score;
                // Construct the query to send to the Google Chart Tools.
                var query = [
                    'chtt=Page+Speed+score:+' + score,
                    'chs=180x100',
                    'cht=gom',
                    'chd=t:' + score,
                    'chxt=x,y',
                    'chxl=0:|' + score
                ].join('&');
                var i = document.createElement('img');
                i.src = CHART_API_URL + query;
                document.body.insertBefore(i, null);
            };
        </script>

        <script>
            callbacks.displayTopPageSpeedSuggestions = function(result) {
                var results = [];
                var ruleResults = result.formattedResults.ruleResults;
                for (var i in ruleResults) {
                    var ruleResult = ruleResults[i];
                    // Don't display lower-impact suggestions.
                    if (ruleResult.ruleImpact < 3.0)
                        continue;
                    results.push({name: ruleResult.localizedRuleName,
                        impact: ruleResult.ruleImpact});
                }
                results.sort(sortByImpact);
                var ul = document.createElement('ul');
                for (var i = 0, len = results.length; i < len; ++i) {
                    var r = document.createElement('li');
                    r.innerHTML = results[i].name;
                    ul.insertBefore(r, null);
                }
                if (ul.hasChildNodes()) {
                    document.body.insertBefore(ul, null);
                } else {
                    var div = document.createElement('div');
                    div.innerHTML = 'No high impact suggestions. Good job!';
                    document.body.insertBefore(div, null);
                }
            };

            // Helper function that sorts results in order of impact.
            function sortByImpact(a, b) {
                return b.impact - a.impact;
            }
        </script>

        <script>
            var RESOURCE_TYPE_INFO = [
                {label: 'JavaScript', field: 'javascriptResponseBytes', color: 'e2192c'},
                {label: 'Images', field: 'imageResponseBytes', color: 'f3ed4a'},
                {label: 'CSS', field: 'cssResponseBytes', color: 'ff7008'},
                {label: 'HTML', field: 'htmlResponseBytes', color: '43c121'},
                {label: 'Flash', field: 'flashResponseBytes', color: 'f8ce44'},
                {label: 'Text', field: 'textResponseBytes', color: 'ad6bc5'},
                {label: 'Other', field: 'otherResponseBytes', color: '1051e8'}
            ];

            callbacks.displayResourceSizeBreakdown = function(result) {
                var stats = result.pageStats;
                var labels = [];
                var data = [];
                var colors = [];
                var totalBytes = 0;
                var largestSingleCategory = 0;
                for (var i = 0, len = RESOURCE_TYPE_INFO.length; i < len; ++i) {
                    var label = RESOURCE_TYPE_INFO[i].label;
                    var field = RESOURCE_TYPE_INFO[i].field;
                    var color = RESOURCE_TYPE_INFO[i].color;
                    if (field in stats) {
                        var val = Number(stats[field]);
                        totalBytes += val;
                        if (val > largestSingleCategory)
                            largestSingleCategory = val;
                        labels.push(label);
                        data.push(val);
                        colors.push(color);
                    }
                }
                // Construct the query to send to the Google Chart Tools.
                var query = [
                    'chs=300x140',
                    'cht=p3',
                    'chts=' + ['000000', 16].join(','),
                    'chco=' + colors.join('|'),
                    'chd=t:' + data.join(','),
                    'chdl=' + labels.join('|'),
                    'chdls=000000,14',
                    'chp=1.6',
                    'chds=0,' + largestSingleCategory
                ].join('&');
                var i = document.createElement('img');
                i.src = 'http://chart.apis.google.com/chart?' + query;
                document.body.insertBefore(i, null);
            };
        </script>

    </head>
    <body onload="runPagespeed();">
        <div>Java-Buddy: Google Page Speed Insights test</div>
        <p id="testedurl">
    </body>

</html>



Main JavaFX code.
package javafx_pagespeedinsights;

import java.net.URL;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

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

    private Scene scene;
    MyBrowser myBrowser;

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

        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 640, 500);

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

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

    class MyBrowser extends Region {

        HBox toolbar;
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        public MyBrowser() {

            final URL PageSpeedTest = getClass().getResource("PageSpeedTest.html");
            webEngine.load(PageSpeedTest.toExternalForm());
            
            webEngine.setOnAlert(new EventHandler<WebEvent<String>>(){

                @Override
                public void handle(WebEvent<String> t) {
                    System.out.println(t.getData());
                }

            });

            getChildren().add(webView);

        }
    }
}


Java Magazine July/August 2013

Java Magazine issue July/August 2013 is available now, read on line: http://www.oraclejavamagazine-digital.com/javamagazine/july_august_2013


Saturday, August 10, 2013

Java EE 7 Recipes: A Problem-Solution Approach



Java EE 7 Recipes takes an example-based approach in showing how to program Enterprise Java applications in many different scenarios. Be it a small-business web application, or an enterprise database application, Java EE 7 Recipes provides effective and proven solutions to accomplish just about any task that you may encounter. You can feel confident using the reliable solutions that are demonstrated in this book in your personal or corporate environment.

The solutions in Java EE 7 Recipes are built using the most current Java Enterprise specifications, including EJB 3.2, JSF 2.2, Expression Language 3.0, Servlet 3.1, and JMS 2.0. While older technologies and frameworks exist, it is important to be forward-looking and take advantage of all that the latest technologies offer. Rejuvenate your Java expertise to use the freshest capabilities, or perhaps learn Java Enterprise development for the first time and discover one of the most widely used and most powerful platforms available for application development today. Let Java EE 7 Recipes show you the way by showing how to build streamlined and reliable applications much faster and easier than ever before by making effective use of the latest frameworks and features on offer in the Java EE 7 release.
  • Shows off the most current Java Enterprise Edition technologies.
  • Provides solutions to creating sophisticated user interfaces.
  • Demonstrates proven solutions for effective database access.

Table of Contents

  1. Introduction to Servlets
  2. JavaServer Pages
  3. The Basics of JavaServer Faces
  4. Facelets
  5. JavaServer Faces Standard Components
  6. Advanced JavaServer Faces and Ajax
  7. JDBC
  8. Object-Relational Mapping
  9. Enterprise JavaBeans
  10. The Query API and JPQL
  11. Oracle's Glashfish
  12. Contexts and Dependency Injection
  13. Java Message Service
  14. Authentication and Security
  15. Java Web Services
  16. Enterprise Solutions Using Alternative Programming Languages
  17. WebSockets and JSON-P
  18. JavaFX in the Enterprise
  19. Concurrency and Batch Applications

Monday, August 5, 2013

Learning Java, 4th Edition



Learning Java, 4e covers the latest enhancements to the most popular programming language in the world.

About the Author

Patrick Niemeyer became involved with Oak (Java's predecessor) while working at Southwestern Bell Technology Resources. He is an independent consultant and author in the areas of networking and distributed applications. Pat is the author of BeanShell, a popular Java scripting language, as well as various other free goodies on the Net. Most recently, Pat has been developing enterprise architecture for A.G. Edwards. He currently lives in the Central West End area of St. Louis with various creatures.

Dan Leuck is the CEO of Ikayzo, a Tokyo and Honolulu-based interactive design and software development firm with customers including Sony, Oracle, Nomura, PIMCO and the federal government. He previously served as Senior Vice President of Research and Development for Tokyo-based ValueCommerce, Asia's largest online marketing company, Global Head of Development for London-based LastMinute.com, Europe's largest B2C website, and President of the US division of DML. Daniel has extensive experience managing teams of 150+ developers in five countries. He has served on numerous advisory boards and panels for companies such as Macromedia and Sun Microsystems. Daniel is active in the Java community, is a contributor to BeanShell, the project lead for SDL, and sits on numerous Java Community Process expert groups.

Sunday, August 4, 2013

Java 7 Pocket Guide, 2nd Edition


When you need quick answers for developing or debugging Java programs, this pocket guide provides a handy reference to the standard features of the Java programming language and its platform. You’ll find helpful programming examples, tables, figures, and lists, as well as supplemental information about topics including the Java Scripting API, third-party tools, and the basics of the Unified Modeling Language (UML).
Updated for new features through Java SE 7, this little book is an ideal companion, whether you’re in the office, in the lab, or on the road.
  • Quickly find Java language details, such as naming conventions, fundamental types, and object-oriented programming elements
  • Get details on the Java SE 7 platform, including development basics, memory management, concurrency, and generics
  • Browse through basic information on NIO 2.0, the G1 Garbage Collector, and Project Coin (JSR-334) features
  • Get supplemental references to development, CM, and test tools; libraries; IDEs; and Java-related scripting languages
  • Find information to help you prepare for the Oracle Certified Associate Java SE 7 Programmer I exam

Friday, August 2, 2013

JavaFX example: communication between windows

This example demonstrate how to communication between JavaFX windows.

JavaFX example: communication between windows
JavaFX example: communication between windows


package javafx_windowcomm;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_WindowComm extends Application {
    
    SubWindow subWindow;
    Label mainMsg;
    
    @Override
    public void start(Stage primaryStage) {
        
        StackPane root = new StackPane();
        
        mainMsg = new Label();
        
        final TextField mainTextField = new TextField();
        Button mainSendButton = new Button("Send to sub-Window");
        mainSendButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                subWindow.setMsg(mainTextField.getText());
            }
        });
        
        VBox mainVBox = new VBox();
        mainVBox.getChildren().addAll(mainMsg, mainTextField, mainSendButton);
        root.getChildren().add(mainVBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        subWindow = new SubWindow(this);
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    public void setMainMsg(String msg){
        mainMsg.setText(msg);
    }
    
    class SubWindow extends Stage{
        JavaFX_WindowComm parent;
        Label labelID;
        Label messageIn;
        TextField subTextField;
        Button subSendButton;
        Stage subStage;

        private SubWindow(JavaFX_WindowComm aThis) {
            parent = aThis;
            
            subStage = new Stage();
            Group subRoot = new Group();
            Scene scene = new Scene(subRoot, 300, 200);
            subStage.setScene(scene);
            subStage.show();
        
            VBox vBox = new VBox();
        
            labelID = new Label();
            labelID.setText(subStage.toString());
            
            messageIn = new Label();
            subTextField = new TextField();
            
            subSendButton = new Button("Send to main Window");
            subSendButton.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent t) {
                    setMainMsg(subTextField.getText());
                }

            });
                 
            vBox.getChildren().addAll(labelID, messageIn, subTextField, subSendButton);
            subRoot.getChildren().add(vBox);
        }
        
        public void setMsg(String msg){
            messageIn.setText(msg);
        }
        
    }
}



Thursday, August 1, 2013

JavaFX Interactive Menu Demo on Raspberry Pi


A demo of JavaFX on Raspberry Pi, created to show what can be done with JavaFX in the area of interactive TV menus on a low power embedded device. For more details about the demo see this blog post about it http://fxexperience.com/2013/08/javafx-hd-menus-on-raspberrypi/

ORACLE TEAM USA Taps Real-Time Mobile Data with Oracle

With more than 300 sensors on board, ORACLE TEAM USA relies on Oracle Database and Oracle Application Express to deliver mobile, real-time data, vital to the team's success.