Tuesday, April 30, 2013

Get current method name using Thread.currentThread().getStackTrace()

To get the stack trace elements in StackTraceElement[] form, call Thread.currentThread().getStackTrace(). The second element, [1], is the your method call getStackTrace(); [0] is getStackTrace(). Then call its getMethodName() method to get the name of your method.

Example to print the stack trace elements, and the name of the current method.

Get current method name
Get current method name


package javafxapplication1;

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

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXApplication1 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                method_01();
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private void method_01(){
        method_02();
    }
    
    private void method_02(){
        
        StackTraceElement[] stackTraceElementArray = 
                Thread.currentThread().getStackTrace();
        
        for(int i = stackTraceElementArray.length-1; i >= 0; i--){
            System.out.println(i + ":" + stackTraceElementArray[i].getMethodName());
        }
        
        String me = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("It's: " + me);
    }
}


Sunday, April 28, 2013

Introduction to Java Development with OpenCV



OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.

As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for Android development. The guide, Introduction to Java Development, will help you to create your first Java (or Scala) application using OpenCV, use Eclipse, Apache Ant or the Simple Build Tool (SBT) to build the application.


Tuesday, April 23, 2013

JavaFX Scene Builder Tutorial updated wth Using Scene Builder with NetBeans, Eclipse and IntelliJ

JavaFX Scene Builder (Scene Builder) enables you to quickly design JavaFX application user interfaces by dragging a UI component from a library of UI components and dropping it into a content view area. The FXML code for the UI layout that you create in the tool is automatically generated in the background. To learn more about Scene Builder's features, see to JavaFX Scene Builder User Guide.

Scene Builder can be used as a standalone design tool, but it can also be used in conjunction with Java IDEs, so that you can use the IDE to write, build, and run the controller source code that you use with your application's user interface.

The tutorial of Using JavaFX Scene Builder with Java IDEs in JavaFX Documentation updated with information about how to configure the NetBeans, Eclipse, or IntelliJ IDEs to use with Scene Builder.


Monday, April 22, 2013

Search int in an Array

To search a int in an array, we can use the code:

Arrays.asList(<Array of Integer>).indexOf(<target int>)

Where Arrays.asList(<Array of Integer>) returns a fixed-size list backed by the specified array. indexOf(<target int>) returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Please notice that <Array of Integer> can be Integer[], not int[]; because int is a primitive types, a special data types built into the language; they are not objects created from a class.

Example:

package javatestarray;

import java.util.Arrays;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestArray {
    
    final static int[] Array_int = {1, 2, 3, 4, 5};
    final static Integer[] Array_Integer = {1, 2, 3, 4, 5};

    public static void main(String[] args) {
        
        int indexIn_Array_int = Arrays.asList(Array_int).indexOf(3);
        System.out.println("indexIn_Array_int = " + indexIn_Array_int);
        //not work! -1 will be returned.
        
        int indexIn_Array_Integer = Arrays.asList(Array_Integer).indexOf(3);
        System.out.println("indexIn_Array_Integer = " + indexIn_Array_Integer);
        //2 will be returned
    }
}


Wednesday, April 17, 2013

Java SE 7, SE 6 and SE Embedded 7 update released

Oracle has released three updates to Java:
  • Java SE 7 Update 21
    This release contains new features and fixes for security vulnerabilities, including a new Server JRE, JRE Installer linked with Uninstall Applet on Windows platform, changes to Security Dialogs and more. Oracle strongly recommends that all Java SE 7 users upgrade to this release.
  • Java SE 6 Update 45
    This release contains fixes for security vulnerabilities.
  • Java SE Embedded 7 Update 21
    This release is based on Java Development Kit 7 Update 21 (JDK 7u21) and provides specific features and support for embedded systems.
Source: https://blogs.oracle.com/java/entry/java_se_7_update_21

Tuesday, April 16, 2013

Save Canvas to PNG file

Example to save canvas to file of PNG format using FileChooser.

Example to save canvas to file of PNG format using FileChooser
Example to save canvas to file of PNG format using FileChooser


package javafx_drawoncanvas;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
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.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

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

    @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) {
                graphicsContext.beginPath();
                graphicsContext.moveTo(event.getX(), event.getY());
                graphicsContext.setStroke(colorPicker.getValue());
                graphicsContext.stroke();
            }
        });
        
        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.setStroke(colorPicker.getValue());
                graphicsContext.stroke();
            }
        });

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

            @Override
            public void handle(MouseEvent event) {

            }
        });

        Group root = new Group();
        
        Button buttonSave = new Button("Save");
        buttonSave.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                FileChooser fileChooser = new FileChooser();
                
                //Set extension filter
                FileChooser.ExtensionFilter extFilter = 
                        new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
                fileChooser.getExtensionFilters().add(extFilter);
              
                //Show save file dialog
                File file = fileChooser.showSaveDialog(primaryStage);
                
                if(file != null){
                    try {
                        WritableImage writableImage = new WritableImage(CANVAS_WIDTH, CANVAS_HEIGHT);
                        canvas.snapshot(null, writableImage);
                        RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
                        ImageIO.write(renderedImage, "png", file);
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_DrawOnCanvas.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            
        });
        
        HBox hBox = new HBox();
        hBox.getChildren().addAll(colorPicker, buttonSave);

        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBox, 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){
        
        colorPicker = new ColorPicker();
        
        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.setFill(colorPicker.getValue());
        gc.setStroke(colorPicker.getValue());
        gc.setLineWidth(1);
    }
    
}


Monday, April 15, 2013

Free draw on Canvas, with ColorPicker

ColorPicker is added on the last example of "Free draw on JavaFX Canvas".

Free draw on Canvas, with ColorPicker.
Free draw on Canvas, with ColorPicker.


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.control.ColorPicker;
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 {
    
    ColorPicker colorPicker;

    @Override
    public void start(Stage primaryStage) {

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

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.beginPath();
                graphicsContext.moveTo(event.getX(), event.getY());
                graphicsContext.setStroke(colorPicker.getValue());
                graphicsContext.stroke();
            }
        });
        
        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.setStroke(colorPicker.getValue());
                graphicsContext.stroke();
            }
        });

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

            @Override
            public void handle(MouseEvent event) {

            }
        });

        Group root = new Group();
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(colorPicker, 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){
        
        colorPicker = new ColorPicker();
        
        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.setFill(colorPicker.getValue());
        gc.setStroke(colorPicker.getValue());
        gc.setLineWidth(1);
    }
    
}


Next:
- Save Canvas to PNG file


Thursday, April 11, 2013

Embed JavaFX inside Swing JFrame

This example demonstrate how to embed JavaFX components (example of MediaPlay) in Swing JFrame.

Embed JavaFX MediaPlayer inside Swing JFrame
Embed JavaFX MediaPlayer inside Swing JFrame


package javafx_insidejframe;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_insideJFrame{
    
    private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";
    
    private static void initFxLater(JFXPanel panel){
        Group root = new Group();
        Scene scene = new Scene(root, 540, 210);
        
        // create media player
        Media media = new Media(MEDIA_URL);
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setAutoPlay(true);
        
        // create mediaView and add media player to the viewer
        MediaView mediaView = new MediaView(mediaPlayer);
        ((Group)scene.getRoot()).getChildren().add(mediaView);
        
        panel.setScene(scene);
    }
    
    private static void initSwingLater(){
        JFrame jFrame = new JFrame("- JFrame -");
        jFrame.setSize(540, 210);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        final JFXPanel jFXPanel = new JFXPanel();
        jFrame.add(jFXPanel);
        
        Platform.runLater(new Runnable(){

            @Override
            public void run() {
                initFxLater(jFXPanel);
            }
        });
        
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                initSwingLater();
            }
            
        });
    }
}


Wednesday, April 10, 2013

Free draw on JavaFX Canvas

Example to free draw on JavaFX Canvas, by mouse events.

Free draw on JavaFX Canvas
Free draw on JavaFX Canvas


package javafx_drawoncanvas;

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

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

    @Override
    public void start(Stage primaryStage) {

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

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.beginPath();
                graphicsContext.moveTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });
        
        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });

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

            @Override
            public void handle(MouseEvent event) {

            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(canvas);
        Scene scene = new Scene(root, 400, 400);
        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.setFill(Color.RED);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(1);
        
    }
    
}


Next:
- Free draw on Canvas, with ColorPicker


Friday, April 5, 2013

JavaFX: draw on Canvas

Simple example to draw something on JavaFX 2 Canvas:

draw on JavaFX 2 Canvas
draw on JavaFX 2 Canvas


package javafx_drawoncanvas;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

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

        Canvas canvas = new Canvas(300, 250);
        GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
        
        drawSomething(graphicsContext);
        
        StackPane root = new StackPane();
        root.getChildren().add(canvas);
        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 void drawSomething(GraphicsContext gc){
        double canvasWidth = gc.getCanvas().getWidth();
        double canvasHeight = gc.getCanvas().getHeight();
        
        gc.setFill(Color.RED);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(3);

        gc.fillRect(
                canvasWidth/4,      //x of the upper left corner
                canvasHeight/4,     //y of the upper left corner
                canvasWidth/2,      //width of the rectangle
                canvasHeight/2);    //height of the rectangle
        
        gc.strokeOval(
                canvasWidth/2,      //x of the upper left bound of the oval
                canvasHeight/2,     //y of the upper left bound of the oval
                canvasWidth/2,      //width at the center of the oval
                canvasHeight/2);    //height at the center of the oval
        
    }
    
}


Thursday, April 4, 2013

Display multi images in JavaFX TitledPanes

Last post demonstrate simple example of "JavaFX TitledPane". This post show how to load multi images in TitledPane within Accordion.

Display multi images in JavaFX 2 TitledPanes
Display multi images in JavaFX 2 TitledPanes


package javafx_titledpane;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TitledPane extends Application {
    
    File filesJpg[];
    Image images[];
    ImageView imageViews[];
    BufferedImage bufferedImage[];
    TitledPane titledPanes[];
    
    @Override
    public void start(final Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Open a New Window");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                openDirectoryChooser(primaryStage);
            }
        });

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

        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 void openDirectoryChooser(Stage parent) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File selectedDirectory =
                directoryChooser.showDialog(parent);

        if (selectedDirectory != null) {
            FilenameFilter filterJpg = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".jpg");
                }
            };

            filesJpg = selectedDirectory.listFiles(filterJpg);
            openTitledPane();
        }
    }
    
    private void openTitledPane(){
        int numOfJpg = filesJpg.length;
        images = new Image[numOfJpg];
        bufferedImage = new BufferedImage[numOfJpg];
        imageViews = new ImageView[numOfJpg];
        titledPanes = new TitledPane[numOfJpg];

        for (int i = 0; i < numOfJpg; i++) { 
            try {
                File file = filesJpg[i];
                
                bufferedImage[i] = ImageIO.read(file);
                images[i] = SwingFXUtils.toFXImage(bufferedImage[i], null);
                imageViews[i] = new ImageView();
                imageViews[i].setImage(images[i]);
                imageViews[i].setFitWidth(400);
                imageViews[i].setPreserveRatio(true);
                imageViews[i].setSmooth(true);
                imageViews[i].setCache(true); 
                titledPanes[i] = new TitledPane(String.valueOf(i), imageViews[i]);
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_TitledPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
        
        Accordion accordion = new Accordion();
        accordion.getPanes().addAll(titledPanes);
        
        Stage titledPaneStage = new Stage();
        titledPaneStage.setTitle("TitledPane");
        Scene scene = new Scene(new Group(), 400, 400);
        Group root = (Group)scene.getRoot();
        root.getChildren().add(accordion);
        titledPaneStage.setScene(scene);
        titledPaneStage.show();
    }
}




JavaFX TitledPane

javafx.scene.control.TitledPane is a panel with a title that can be opened and closed.

The panel in a TitledPane can be any Node such as UI controls or groups of nodes added to a layout container.

It is not recommended to set the MinHeight, PrefHeight, or MaxHeight for this control. Unexpected behavior will occur because the TitledPane's height changes when it is opened or closed

Example:

TitledPane
TitledPane


package javafx_titledpane;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TitledPane extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        TitledPane titledPane = new TitledPane();
        titledPane.setText("My icon");
        
        Image image = new Image("http://goo.gl/kYEQl");
        ImageView imageView = new ImageView();
        imageView.setImage(image);
        titledPane.setContent(imageView);
        
        StackPane root = new StackPane();
        root.getChildren().add(titledPane);
        
        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);
    }
}


Next:
- Display multi images in JavaFX TitledPanes


Wednesday, April 3, 2013

JavaFX 3D Preview

JavaFX 3D Preview

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

Tuesday, April 2, 2013

Display images on JavaFX Pagination Control

Last post demonstrate a basic example of using Pagination Control of JavaFX. Now, it's modified to display images on Pagination.

Display images on JavaFX Pagination Control
Display images on JavaFX Pagination Control


package javafx_pagination;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Pagination;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.imageio.ImageIO;

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

    private Pagination pagination;
    File filesJpg[];

    @Override
    public void start(final Stage primaryStage) {

        Button btn = new Button();
        btn.setText("Open a New Window");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                openDirectoryChooser(primaryStage);
            }
        });

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

        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 void openDirectoryChooser(Stage parent) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File selectedDirectory =
                directoryChooser.showDialog(parent);

        if (selectedDirectory != null) {
            FilenameFilter filterJpg = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".jpg");
                }
            };

            filesJpg = selectedDirectory.listFiles(filterJpg);
            openPageWindow();
        }
    }

    private void openPageWindow() {
        int numOfPage = filesJpg.length;

        Stage pageStage = new Stage();
        pagination = new Pagination(numOfPage);
        pagination.setPageFactory(new Callback<Integer, Node>() {
            @Override
            public Node call(Integer pageIndex) {
                return createPage(pageIndex);
            }
        });

        AnchorPane anchor = new AnchorPane();
        AnchorPane.setTopAnchor(pagination, 10.0);
        AnchorPane.setRightAnchor(pagination, 10.0);
        AnchorPane.setBottomAnchor(pagination, 10.0);
        AnchorPane.setLeftAnchor(pagination, 10.0);
        anchor.getChildren().add(pagination);

        Scene scene = new Scene(anchor, 400, 300);

        pageStage.setTitle("Image View Pages");
        pageStage.setScene(scene);
        pageStage.show();
    }

    public VBox createPage(int index) {

        ImageView imageView = new ImageView();

        File file = filesJpg[index];
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            Image image = SwingFXUtils.toFXImage(bufferedImage, null);
            imageView.setImage(image);
            imageView.setFitWidth(400);
            imageView.setPreserveRatio(true);
            imageView.setSmooth(true);
            imageView.setCache(true);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_Pagination.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        VBox pageBox = new VBox();
        pageBox.getChildren().add(imageView);
        return pageBox;
    }
}




JavaFX Pagination

javafx.scene.control.Pagination is a Pagination control is used for navigation between pages of a single content, which has been divided into smaller parts.

Example:
JavaFX Pagination
JavaFX Pagination


package javafx_pagination;

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

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

    private Pagination pagination;
    final static int numOfPage = 5;

    public VBox createPage(int pageIndex) {
        VBox pageBox = new VBox();
        Label pageLabel = new Label("Page " + (pageIndex+1));
        pageBox.getChildren().add(pageLabel);
        return pageBox;
    }

    @Override
    public void start(Stage primaryStage) {

        pagination = new Pagination(numOfPage);
        pagination.setPageFactory(new Callback<Integer, Node>() {
            @Override
            public Node call(Integer pageIndex) {
                return createPage(pageIndex);
            }
        });

        AnchorPane anchor = new AnchorPane();
        AnchorPane.setTopAnchor(pagination, 10.0);
        AnchorPane.setRightAnchor(pagination, 10.0);
        AnchorPane.setBottomAnchor(pagination, 10.0);
        AnchorPane.setLeftAnchor(pagination, 10.0);
        anchor.getChildren().add(pagination);

        Scene scene = new Scene(anchor, 400, 300);

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

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


Next:
- Display images on JavaFX Pagination Control