Thursday, January 31, 2013

Go mobile with Java Magazine!

Java Magazine is an essential source of knowledge about Java technology, the Java programming language, and Java-based applications for people who rely on them in their professional careers, or who aspire to.

MAGAZINE FEATURES:
  • Current and past issues of Java Magazine, absolutely free!
  • Text-formatted articles designed for maximum mobile readability.
  • Download each issue, then return any time for offline reading.
  • Search the archive of available issues.
  • Bookmark your favorite articles.
  • Share your comments with other readers.
Issues will be available for download on a bimonthly basis.

Java Magazine on Android

Link:

Tuesday, January 29, 2013

Example of Collections.binarySearch(), in List of Date

Collections.binarySearch() searches the specified list for the specified object using the binary search algorithm. Details refer to the Java doc.

Example:

package javaapplication1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        
        Comparator<Date> comparator = new Comparator<Date>() {

            @Override
            public int compare(Date o1, Date o2) {
                return o1.compareTo(o2);
            }
        };
        
        List<Date> myList = new ArrayList<>();
        myList.add(new Date(2015-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 02));
        myList.add(new Date(2012-1900, 10, 01));
        myList.add(new Date(2012-1900, 11, 01));
        myList.add(new Date(2015-1900, 01, 10));
        
        Collections.sort(myList, comparator);
        
        //Print all the elements in the List
        for(int i = 0; i < myList.size(); i++){
            System.out.println(myList.get(i).toString());
        }
        
        //find the closest element from the List
        Date target = new Date(2013-1900, 01, 02);
        int index = Collections.binarySearch(
                myList, 
                target, 
                comparator);
        System.out.println("closest to " + target.toString() + " : " + index);
        
        target = new Date(2013-1900, 01, 03);
        index = Collections.binarySearch(
                myList, 
                target, 
                comparator);
        System.out.println("closest to " + target.toString() + " : " + index);
        
        target = new Date(2012-1900, 10, 02);
        index = Collections.binarySearch(
                myList, 
                target, 
                comparator);
        System.out.println("closest to " + target.toString() + " : " + index);
    }

}

Example of Collections.binarySearch()
Example of Collections.binarySearch()


Sort List of Date

Example to sort a List of Date object using Collections.sort().

package javaapplication1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaApplication1 {
     
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        List<Date> myList = new ArrayList<>();
        myList.add(new Date(2015-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 01));
        myList.add(new Date(2013-1900, 01, 02));
        myList.add(new Date(2012-1900, 10, 01));
        myList.add(new Date(2012-1900, 11, 01));
        myList.add(new Date(2015-1900, 01, 10));
        
        Collections.sort(myList, new Comparator<Date>(){

            @Override
            public int compare(Date o1, Date o2) {
                return o1.compareTo(o2);
            }
        });
        
        for(int i = 0; i < myList.size(); i++){
            System.out.println(myList.get(i).toString());
        }

    }
    
}

Sort List of Date object
Sort List of Date object


Monday, January 28, 2013

NetBeans IDE 7.3 Release Candidate Now Available




The NetBeans Team announce the Release Candidate build of NetBeans IDE 7.3.

NetBeans IDE 7.3 provides new support for the latest HTML5, JavaScript, and CSS standards, as well as enhancements to support for Groovy, PHP and many other features.

Source: NetBeans.org Community News

Saturday, January 26, 2013

Get file info using java.nio.file.Path and java.nio.file.Files

The previous post describe how to "Get file info using java.io.File", this one have similar function using java.nio.file.Path and java.nio.file.Files.

Please note that JavaFX FileChooser return a java.io.File object. To obtain coresponding java.nio.file.Path object, call its toPath() method.

package javafx_niofile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_NIOFile extends Application {
    
    Label label;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button();
        btnLoad.setText("Load File");
        btnLoad.setOnAction(btnLoadEventListener);
        
        label = new Label();
        
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label);
        
        Scene scene = new Scene(rootBox, 400, 350);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
  
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
              
            //Set extension filter
            FileChooser.ExtensionFilter extFilter 
                    = new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*");
            fileChooser.getExtensionFilters().add(extFilter);
               
            //Show open file dialog, return a java.io.File object
            File file = fileChooser.showOpenDialog(null);
            
            //obtain a java.nio.file.Path object 
            Path path = file.toPath();
            
            String fileInfo = "Path = " + path.toString() + "\n\n";
            
            fileInfo += "FileSystem: " + path.getFileSystem() + "\n\n";
            
            fileInfo += "FileName = " + path.getFileName() + "\n"
                    + "Parent = " + path.getParent() + "\n\n"
                    + "isExecutable(): " + Files.isExecutable(path) + "\n"
                    + "isReadable(): " + Files.isReadable(path) + "\n"
                    + "isWritable(): " + Files.isWritable(path) + "\n";
            try {
                fileInfo += "getLastModifiedTime(): " + Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS) + "\n"
                        + "size(): " + Files.size(path) + "\n";
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_NIOFile.class.getName()).log(Level.SEVERE, null, ex);
            }

            label.setText(fileInfo);

        }
    };
    
}

Get file info using java.nio.file.Path and java.nio.file.Files
Get file info using java.nio.file.Path and java.nio.file.Files


Related:
- Access subpath of java.nio.file.Path

Friday, January 25, 2013

Get file content type

This example show some methods to get content type of file:

Get file content type
Get file content type


package javafx_fileops;

import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.activation.MimetypesFileTypeMap;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_FileOps extends Application {
    
    Label label;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button();
        btnLoad.setText("Load File");
        btnLoad.setOnAction(btnLoadEventListener);
        
        label = new Label();
        
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label);
        
        Scene scene = new Scene(rootBox, 400, 350);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
  
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
              
            //Set extension filter
            FileChooser.ExtensionFilter extFilter 
                    = new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*");
            fileChooser.getExtensionFilters().add(extFilter);
               
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            String fileInfo = 
                    "AbsoluteFile: " + file.getAbsoluteFile() + " of " + file.getAbsoluteFile().getClass() + "\n\n"
                    + "toPath(): " + file.toPath() + " of " + file.toPath().getClass() + "\n";
            
            try {
                fileInfo += "by Files.probeContentType(): " + Files.probeContentType(file.toPath()) + "\n";
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_FileOps.class.getName()).log(Level.SEVERE, null, ex);
            }

            fileInfo += "\n";
            fileInfo +=  "getName(): " + file.getName() + " of " + file.getName().getClass() + "\n"
                    + "by URLConnection.guessContentTypeFromName(): " 
                    + URLConnection.guessContentTypeFromName(file.getName()) 
                    + "\n";
            
            fileInfo += "by URLConnection.getFileNameMap().getContentTypeFor(): " 
                    + URLConnection.getFileNameMap().getContentTypeFor(file.getName())
                    + "\n";
            
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            fileInfo += "\n";
            fileInfo += "by MimetypesFileTypeMap().getContentType(): " 
                    + mimeTypesMap.getContentType(file) + "\n";
            
            label.setText(fileInfo);
        }
    };
}


Thursday, January 24, 2013

Get file info using java.io.File

Get file info
Get file info


package javafx_fileops;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_FileOps extends Application {
    
    Label label;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button();
        btnLoad.setText("Load File");
        btnLoad.setOnAction(btnLoadEventListener);
        
        label = new Label();
        
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label);
        
        Scene scene = new Scene(rootBox, 400, 350);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
  
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
              
            //Set extension filter
            FileChooser.ExtensionFilter extFilter 
                    = new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*");
            fileChooser.getExtensionFilters().add(extFilter);
               
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            String fileInfo = 
                    "AbsoluteFile: " + file.getAbsoluteFile() + " of " + file.getAbsoluteFile().getClass() + "\n"
                    + "ParentFile: " + file.getParentFile()  + " of " + file.getParentFile().getClass() + "\n"
                    + "AbsolutePath: " + file.getAbsolutePath() + "\n"
                    + "Path: " + file.getPath() + "\n"
                    + "Name: " + file.getName() + "\n"
                    + "Parent: " + file.getParent() + "\n"
                    + "canExecute- " + file.canExecute() + "\n"
                    + "canRead- " + file.canRead() + "\n"
                    + "canWrite- " + file.canWrite() + "\n"
                    + "isAbsolute- " + file.isAbsolute() + "\n"
                    + "isDirectory- " + file.isDirectory() + "\n"
                    + "isFile- " + file.isFile() + "\n"
                    + "isHidden- " + file.isHidden() + "\n"
                    + "lastModified: " + (new Date(file.lastModified())).toString() + "\n"
                    + "length: " + file.length() + "\n"
                    + "URI: " + file.toURI()  + " of " + file.toURI().getClass() + "\n";
            try {
                fileInfo += "\n";
                fileInfo += "CanonicalFile: " + file.getCanonicalFile() + " of " + file.getCanonicalFile().getClass() + "\n";
                fileInfo += "CanonicalPath: " + file.getCanonicalPath() + "\n";
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_FileOps.class.getName()).log(Level.SEVERE, null, ex);
            }

            label.setText(fileInfo);
        }
    };
}


Related: Get file info using java.nio.file.Path and java.nio.file.Files

Wednesday, January 23, 2013

Apply GaussianBlur and BoxBlur on ImageView

This example demonstrate how to apply GaussianBlur and BoxBlur on ImageView.

GaussianBlur and BoxBlur on ImageView
GaussianBlur and BoxBlur on ImageView


package javafx_imageprocessing;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.BoxBlur;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageProcessing extends Application {
    
    ImageView imageView_Source, imageView_GaussianBlur, imageView_BoxBlur;
    Slider sliderWidth, sliderHeight, sliderIterations;
    
    @Override
    public void start(Stage primaryStage) {
        
        Image image = new Image("http://goo.gl/kYEQl");
        imageView_Source = new ImageView();
        imageView_Source.setImage(image);

        imageView_BoxBlur = new ImageView();
        imageView_BoxBlur.setImage(image);
        
        imageView_GaussianBlur = new ImageView();
        imageView_GaussianBlur.setImage(image);
        
        HBox hBoxImage = new HBox();
        hBoxImage.getChildren().addAll(imageView_Source, 
                imageView_GaussianBlur, imageView_BoxBlur);
        
        sliderWidth = SliderBuilder.create()
                .prefWidth(300)
                .min(0.0)   //min
                .max(255.0) //max
                .value(5.0) //default
                .majorTickUnit(50)
                .showTickMarks(true)
                .showTickLabels(true)
                .tooltip(new Tooltip("Width"))
                .build();
        
        sliderHeight = SliderBuilder.create()
                .prefWidth(300)
                .min(0.0)   //min
                .max(255.0) //max
                .value(5.0) //default
                .majorTickUnit(50)
                .showTickMarks(true)
                .showTickLabels(true)
                .tooltip(new Tooltip("Height"))
                .build();
        
        sliderIterations = SliderBuilder.create()
                .prefWidth(300)
                .min(0.0)   //min
                .max(3.0)   //max
                .value(1.0) //default
                .majorTickUnit(1)
                .showTickMarks(true)
                .showTickLabels(true)
                .tooltip(new Tooltip("Iterations"))
                .build();

        Button btnProcess = new Button("Process...");
        btnProcess.setOnAction(btnProcessEventListener);
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                sliderWidth, sliderHeight, sliderIterations, 
                hBoxImage, btnProcess);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 350, 330);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        updateEffect();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnProcessEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            updateEffect();
        }
    };
    
    private void updateEffect(){
        //Apply GaussianBlur
        GaussianBlur gaussianBlur = new GaussianBlur();
        imageView_GaussianBlur.setEffect(gaussianBlur);
        
        //Apply BoxBlur
        Double valueWidth = sliderWidth.valueProperty().doubleValue(); 
        Double valueHeight = sliderHeight.valueProperty().doubleValue();
        int valueIterations = sliderIterations.valueProperty().intValue();
        BoxBlur boxBlur = new BoxBlur();
        boxBlur.setWidth(valueWidth);
        boxBlur.setHeight(valueHeight);
        boxBlur.setIterations(valueIterations);
        imageView_BoxBlur.setEffect(boxBlur);
    }
}


Tuesday, January 22, 2013

Apply effect of Glow on ImageView

javafx.scene.effect.Glow is a high-level effect that makes the input image appear to glow, based on a configurable threshold.

Apply effect of Glow on ImageView

package javafx_imageprocessing;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.Glow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageProcessing extends Application {
    
    ImageView imageView_Source, imageView_Target;
    Slider sliderLevel;
    
    @Override
    public void start(Stage primaryStage) {
        
        Image image = new Image("http://goo.gl/kYEQl");
        imageView_Source = new ImageView();
        imageView_Source.setImage(image);

        imageView_Target = new ImageView();
        imageView_Target.setImage(image);
        
        HBox hBoxImage = new HBox();
        hBoxImage.getChildren().addAll(imageView_Source, imageView_Target);
        
        sliderLevel = SliderBuilder.create()
                .prefWidth(300)
                .min(0)
                .max(1)
                .majorTickUnit(0.2)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(0.3)
                .tooltip(new Tooltip("Level"))
                .build();

        Button btnProcess = new Button("Process...");
        btnProcess.setOnAction(btnProcessEventListener);
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBoxImage, 
                sliderLevel, 
                btnProcess);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 350, 330);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        updateEffect();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnProcessEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            updateEffect();
        }
    };
    
    private void updateEffect(){
        Double valueLevel = sliderLevel.valueProperty().doubleValue(); 
        Glow glow = new Glow(valueLevel);
        imageView_Target.setEffect(glow);
    }
}


Set effect on ImageView with ColorAdjust

javafx.scene.effect.ColorAdjust is effect that allows for per-pixel adjustments of hue, saturation, brightness, and contrast.

Set effect on ImageView with ColorAdjust
Set effect on ImageView with ColorAdjust

package javafx_imageprocessing;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageProcessing extends Application {
    
    ImageView imageView_Source, imageView_Target;
    Slider sliderContrast, sliderHue, sliderBrightness, sliderSaturation;
    
    @Override
    public void start(Stage primaryStage) {
        
        Image image = new Image("http://goo.gl/kYEQl");
        imageView_Source = new ImageView();
        imageView_Source.setImage(image);

        imageView_Target = new ImageView();
        imageView_Target.setImage(image);
        
        HBox hBoxImage = new HBox();
        hBoxImage.getChildren().addAll(imageView_Source, imageView_Target);
        
        sliderContrast = SliderBuilder.create()
                .prefWidth(300)
                .min(-1)
                .max(1)
                .majorTickUnit(0.2)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(0)
                .tooltip(new Tooltip("Contrast"))
                .build();
        
        sliderHue = SliderBuilder.create()
                .prefWidth(300)
                .min(-1)
                .max(1)
                .majorTickUnit(0.2)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(0)
                .tooltip(new Tooltip("Hue"))
                .build();
        
        sliderBrightness = SliderBuilder.create()
                .prefWidth(300)
                .min(-1)
                .max(1)
                .majorTickUnit(0.2)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(0)
                .tooltip(new Tooltip("Brightness"))
                .build();
        
        sliderSaturation = SliderBuilder.create()
                .prefWidth(300)
                .min(-1)
                .max(1)
                .majorTickUnit(0.2)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(0)
                .tooltip(new Tooltip("Saturation"))
                .build();
        
        Button btnProcess = new Button("Process...");
        btnProcess.setOnAction(btnProcessEventListener);
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBoxImage, 
                sliderContrast, 
                sliderHue, 
                sliderBrightness,
                sliderSaturation,
                btnProcess);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 350, 330);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        updateEffect();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnProcessEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            updateEffect();
        }
    };
    
    private void updateEffect(){
        Double valueContrast = sliderContrast.valueProperty().doubleValue(); 
        Double valueHue = sliderHue.valueProperty().doubleValue();
        Double valueBrightness = sliderBrightness.valueProperty().doubleValue();
        Double valueSaturation = sliderSaturation.valueProperty().doubleValue();
        
        ColorAdjust colorAdjust = new ColorAdjust();
        colorAdjust.setContrast(valueContrast);
        colorAdjust.setHue(valueHue);
        colorAdjust.setBrightness(valueBrightness);
        colorAdjust.setSaturation(valueSaturation);
        
        imageView_Target.setEffect(colorAdjust);
    }
}


Related: Create and adjust Color using hue, saturation, brightness


Monday, January 21, 2013

Get width and height of resized imageView

The post "Get width and height of javafx.scene.image.Image" demonstrate how to get width and height of Image by calling Image's getWidth() and getHeight() methods. Another post "Set fitWidth and fitHeight properties dynamically" demonstrate how to set ImageView auto-fit by calling ImageView's setFitWidth() and setFitHeight(). After auto-fited, we cannot get width and height by calling Image's getWidth() and getHeight() methods. Both of them return the original values, not the scaled values.

javafx.scene.image.ImageView provide getBoundsInLocal() and getBoundsInParent() methods to return the rectangular bounds of this Node.
  • getBoundsInLocal(): Gets the value of the property boundsInLocal.

    The rectangular bounds of this Node in the node's untransformed local coordinate space. For nodes that extend Shape, the local bounds will also include space required for a non-zero stroke that may fall outside the shape's geometry that is defined by position and size attributes. The local bounds will also include any clipping set with clip as well as effects set with effect.

  • getBoundsInParent(): Gets the value of the property boundsInParent.

    The rectangular bounds of this Node which include its transforms. boundsInParent is calculated by taking the local bounds (defined by boundsInLocal) and applying the transform created by setting the following additional variables:
    - transforms ObservableList
    - scaleX, scaleY
    - rotate
    - layoutX, layoutY
    - translateX, translateY


Via the rectangular bounds, we can get the re-sized width and height by calling getWidth() and get Height() methods.

Get width and height of resized image


Get width and height of resized image

package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    ScrollPane scrollPane;
    
    Boolean autoFix = true;
    
    Image myImage;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
        Button btnAutoFix = new Button("Auto Fix");
        btnAutoFix.setOnAction(btnAutoFixEventListener);
        Button btnNoFix = new Button("No Fix");
        btnNoFix.setOnAction(btnNoFixEventListener);
         
        label = new Label();
        myImageView = new ImageView();
        scrollPane = new ScrollPane();
        scrollPane.setPrefSize(400, 400);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setContent(myImageView);
        
        HBox buttonBox = new HBox();
        buttonBox.getChildren().addAll(btnLoad, btnAutoFix, btnNoFix);
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(buttonBox, scrollPane, label);
        
        Scene scene = new Scene(rootBox, 400, 500);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                myImage = SwingFXUtils.toFXImage(bufferedImage, null);

                setFix();

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

        }
    };
    
    EventHandler<ActionEvent> btnAutoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = true;
            setFix();
        }
        
    };
    
    EventHandler<ActionEvent> btnNoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = false;
            setFix();
        }
        
    };
    
    private void setFix(){
        if(autoFix){
            myImageView.setFitWidth(400);
            myImageView.setFitHeight(400);
        }else{
            myImageView.setFitWidth(0);
            myImageView.setFitHeight(0);
        }
        
        myImageView.setPreserveRatio(true);
        myImageView.setSmooth(true);
        myImageView.setCache(true);
        
        myImageView.setImage(myImage);
        
        scrollPane.setContent(null);
        scrollPane.setContent(myImageView);
        
        //int boundWidth = (int)myImageView.getBoundsInLocal().getWidth();
        //int boundHeight = (int)myImageView.getBoundsInLocal().getHeight();
        int boundWidth = (int)myImageView.getBoundsInParent().getWidth();
        int boundHeight = (int)myImageView.getBoundsInParent().getHeight();

        label.setText("width: " + boundWidth
                + " x height: " + boundHeight);
    }
}


Saturday, January 19, 2013

Apply SepiaTone on ImageView

javafx.scene.effect.SepiaTone is a filter that produces a sepia tone effect, similar to antique photographs. To apply SepiaTone on a ImageView, simple call setEffect(new SepiaTone()) method of ImageView.

Apply SepiaTone on ImageView
Apply SepiaTone on ImageView


Modify from last post "Set fitWidth and fitHeight properties dynamically, with scroll bar".
package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    ScrollPane scrollPane;
    
    Boolean autoFix = true;
    
    Image myImage;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
        Button btnAutoFix = new Button("Auto Fix");
        btnAutoFix.setOnAction(btnAutoFixEventListener);
        Button btnNoFix = new Button("No Fix");
        btnNoFix.setOnAction(btnNoFixEventListener);
         
        label = new Label();
        myImageView = new ImageView();
        scrollPane = new ScrollPane();
        scrollPane.setPrefSize(400, 400);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setContent(myImageView);
        
        HBox buttonBox = new HBox();
        buttonBox.getChildren().addAll(btnLoad, btnAutoFix, btnNoFix);
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(buttonBox, label, scrollPane);
        
        Scene scene = new Scene(rootBox, 500, 500);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                myImage = SwingFXUtils.toFXImage(bufferedImage, null);

                setFix();

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

        }
    };
    
    EventHandler<ActionEvent> btnAutoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = true;
            setFix();
        }
        
    };
    
    EventHandler<ActionEvent> btnNoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = false;
            setFix();
        }
        
    };
    
    private void setFix(){
        if(autoFix){
            myImageView.setFitWidth(400);
            myImageView.setFitHeight(400);
        }else{
            myImageView.setFitWidth(0);
            myImageView.setFitHeight(0);
        }
        
        myImageView.setPreserveRatio(true);
        myImageView.setSmooth(true);
        myImageView.setCache(true);
        
        myImageView.setImage(myImage);
        
        scrollPane.setContent(null);
        scrollPane.setContent(myImageView);
        
        myImageView.setEffect(new SepiaTone());
    }
}


Ask for help:

The application fail caused by java.lang.NullPointerException, when load large image (ex. 4032 x 3024 JPG from DSLR). The error log list below. Please advise.

java.lang.NullPointerException
 at com.sun.scenario.effect.impl.sw.sse.SSESepiaTonePeer.filter(SSESepiaTonePeer.java:100)
 at com.sun.scenario.effect.CoreEffect.filterImageDatas(CoreEffect.java:103)
 at com.sun.scenario.effect.SepiaTone.filterImageDatas(SepiaTone.java:34)
 at com.sun.scenario.effect.FilterEffect.filter(FilterEffect.java:178)
 at com.sun.scenario.effect.impl.prism.PrEffectHelper.render(PrEffectHelper.java:156)
 at com.sun.javafx.sg.prism.NGNode$EffectFilter.render(NGNode.java:748)
 at com.sun.javafx.sg.prism.NGNode.renderEffect(NGNode.java:494)
 at com.sun.javafx.sg.prism.NGNode$CacheFilter.impl_createImageData(NGNode.java:689)
 at com.sun.javafx.sg.BaseCacheFilter.render(BaseCacheFilter.java:134)
 at com.sun.javafx.sg.prism.NGNode$CacheFilter.render(NGNode.java:660)
 at com.sun.javafx.sg.prism.NGNode.renderCached(NGNode.java:487)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:183)
 at com.sun.javafx.sg.prism.NGImageView.doRender(NGImageView.java:97)
 at com.sun.javafx.sg.prism.NGImageView.doRender(NGImageView.java:20)
 at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
 at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
 at com.sun.javafx.sg.prism.NGRegion.renderContent(NGRegion.java:420)
 at com.sun.javafx.sg.prism.NGNode.renderForClip(NGNode.java:429)
 at com.sun.javafx.sg.prism.NGNode.renderRectClip(NGNode.java:320)
 at com.sun.javafx.sg.prism.NGNode.renderClip(NGNode.java:346)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:179)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
 at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
 at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
 at com.sun.javafx.sg.prism.NGRegion.renderContent(NGRegion.java:420)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:187)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
 at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
 at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:187)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
 at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
 at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
 at com.sun.javafx.sg.prism.NGRegion.renderContent(NGRegion.java:420)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:187)
 at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
 at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
 at com.sun.javafx.tk.quantum.ViewPainter.doPaint(ViewPainter.java:117)
 at com.sun.javafx.tk.quantum.AbstractPainter.paintImpl(AbstractPainter.java:175)
 at com.sun.javafx.tk.quantum.PresentingPainter.run(PresentingPainter.java:73)
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
 at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
 at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
 at com.sun.prism.render.RenderJob.run(RenderJob.java:37)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:98)
 at java.lang.Thread.run(Thread.java:722)
 


Set fitWidth and fitHeight properties dynamically, with scroll bar.

Just a little bit modification on last example "Set fitWidth and fitHeight properties dynamically", to add ScrollBar if need.

with ScrollBar


package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    ScrollPane scrollPane;
    
    Boolean autoFix = true;
    
    Image myImage;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
        Button btnAutoFix = new Button("Auto Fix");
        btnAutoFix.setOnAction(btnAutoFixEventListener);
        Button btnNoFix = new Button("No Fix");
        btnNoFix.setOnAction(btnNoFixEventListener);
         
        label = new Label();
        myImageView = new ImageView();
        scrollPane = new ScrollPane();
        scrollPane.setPrefSize(400, 400);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setContent(myImageView);
        
        HBox buttonBox = new HBox();
        buttonBox.getChildren().addAll(btnLoad, btnAutoFix, btnNoFix);
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(buttonBox, label, scrollPane);
        
        Scene scene = new Scene(rootBox, 500, 500);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                myImage = SwingFXUtils.toFXImage(bufferedImage, null);

                setFix();

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

        }
    };
    
    EventHandler<ActionEvent> btnAutoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = true;
            setFix();
        }
        
    };
    
    EventHandler<ActionEvent> btnNoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = false;
            setFix();
        }
        
    };
    
    private void setFix(){
        if(autoFix){
            myImageView.setFitWidth(400);
            myImageView.setFitHeight(400);
        }else{
            myImageView.setFitWidth(0);
            myImageView.setFitHeight(0);
        }
        
        myImageView.setPreserveRatio(true);
        myImageView.setSmooth(true);
        myImageView.setCache(true);
        
        myImageView.setImage(myImage);
        
        scrollPane.setContent(null);
        scrollPane.setContent(myImageView);
        
        //myImageView.setEffect(new SepiaTone());
    }
}


Set fitWidth and fitHeight properties dynamically

The article "Auto fit JavaFX 2 ImageView" demonstrate how to set ImageView auto-fix by setting fitWidth and fitHeight properties. To remove the auto-fix function, we can call setFitWidth() and setFitHeight(), then the intrinsic height of the image will be used as the fitHeight. Such that we can set/remove auto-fix at run-time.

Set fitWidth and fitHeight properties dynamically


package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    Boolean autoFix = true;
    
    Image myImage;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
        Button btnAutoFix = new Button("Auto Fix");
        btnAutoFix.setOnAction(btnAutoFixEventListener);
        Button btnNoFix = new Button("No Fix");
        btnNoFix.setOnAction(btnNoFixEventListener);
         
        label = new Label();
        myImageView = new ImageView();
        
        HBox buttonBox = new HBox();
        buttonBox.getChildren().addAll(btnLoad, btnAutoFix, btnNoFix);
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(buttonBox, label, myImageView);
        
        Scene scene = new Scene(rootBox, 500, 500);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                myImage = SwingFXUtils.toFXImage(bufferedImage, null);
                myImageView.setImage(myImage);

                setFix();

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

        }
    };
    
    EventHandler<ActionEvent> btnAutoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = true;
            setFix();
        }
        
    };
    
    EventHandler<ActionEvent> btnNoFixEventListener
    = new EventHandler<ActionEvent>(){

        @Override
        public void handle(ActionEvent t) {
            autoFix = false;
            setFix();
        }
        
    };
    
    private void setFix(){
        if(autoFix){
            myImageView.setFitWidth(400);
            myImageView.setFitHeight(400);
        }else{
            myImageView.setFitWidth(0);
            myImageView.setFitHeight(0);
        }
        
        myImageView.setPreserveRatio(true);
        myImageView.setSmooth(true);
        myImageView.setCache(true);
    }
}



Next: Set fitWidth and fitHeight properties dynamically, with scroll bar.

Friday, January 18, 2013

bind widthProperty and heightProperty of Image

The former article described how to "Get width and height of a Image" by calling getWidth() and getHeight() methods. Alternative, we can bind the textProperty of label with widthProperty and heightProperty of Image. Please notice that image cannot be null in this case, otherwise java.lang.NullPointerException will be thrown.

bind widthProperty and heightProperty of Image
bind widthProperty and heightProperty of Image

package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
         
        label = new Label();
        myImageView = new ImageView();
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label, myImageView);
         
        Scene scene = new Scene(rootBox, 300, 300);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);

                myImageView.setImage(image);                
                label.textProperty().bind(
                        image.widthProperty().asString()
                        .concat(" : ")
                        .concat(image.heightProperty().asString()));

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

        }
    };
}


Thursday, January 17, 2013

Caused by: javafx.fxml.LoadException: ... is not a valid type.

It's a tips to include custom control(UI element) in FXML.

It's the FXML from the example "Embed WebView in FXML, to load OpenLayers with OpenStreetMap".

<?xml version="1.0" encoding="UTF-8"?>
 
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafxml_web.*?>
 
<AnchorPane id="AnchorPane" prefHeight="500" prefWidth="660" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxml_web.Sample">
    <children>
        <MyBrowser id="mybrowser" layoutX="10" layoutY="10" prefHeight="460" prefWidth="620" fx:id="mybrowser" />
    </children>
</AnchorPane>


Where MyBrowser is a custom class defined in my package, javafxml_web. So, the statement <?import javafxml_web.*?> have to be added. Otherwise error will be reported, Caused by: javafx.fxml.LoadException: MyBrowser is not a valid type.

US-CERT updated Java flaw affected system add OpenJDK and IcedTea

US-CERT (http://www.us-cert.gov/cas/techalerts/TA13-010A.html) updated to add OpenJDK and IcedTea in Systems Affected list.

US-CERT updated Java flaw affected system add OpenJDK and IcedTea
US-CERT updated Java flaw affected system add OpenJDK and IcedTea


And also state the solution of udating Java 7 Update 11:

Solution

Update Java

Oracle Security Alert CVE-2013-0422 states that Java 7 Update 11 (7u11) addresses this (CVE-2013-0422) and a different but equally severe vulnerability (CVE-2012-3174). Java 7 Update 11 sets the default Java security settings to "High" so that users will be prompted before running unsigned or self-signed Java applets.

Get width and height of javafx.scene.image.Image

To get width and height of javafx.scene.image.Image, simple call its getWidth() and getHeight() methods.

Get width and height of javafx.scene.image.Image
Get width and height of javafx.scene.image.Image


package javafxpixel;

import java.awt.image.BufferedImage;
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.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXPixel extends Application {
    
    Label label;
    ImageView myImageView;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
         
        label = new Label();
        myImageView = new ImageView();
 
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label, myImageView);
         
        Scene scene = new Scene(rootBox, 300, 300);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
            FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
            fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
              
            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);

            BufferedImage bufferedImage;
            try {
                bufferedImage = ImageIO.read(file);
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);
                label.setText("width: " + (int)image.getWidth()
                        + " x height: " + (int)image.getHeight());
                myImageView.setImage(image);
            } catch (IOException ex) {
                Logger.getLogger(JavaFXPixel.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };
}


Related:
- bind widthProperty and heightProperty of Image
- Get width and height of resized imageView


Wednesday, January 16, 2013

Install Netbeans IDE 7.2 on release version Windows 8

TO download Netbeans, visit http://netbeans.org/, click the Download button.


Scroll download the select the download option. Java SE in my case.


Run the download file, netbeans-7.2.1-ml-javase-windows.exe.


Click Next to start installation.


Accept the terms in the license agreement, and click Next.


Accept the terms t install JUnit, and click Next.


Select the location to install. The installer will search te installed JDK if exist. Next.


Review all the setting, and click Install.



Finish.



How to run Java Control Panel on Windows 8

To run Java Control Panel on Windows 8, search java in Settings.

Search Java Control Panel in Settings

Java Control Panel

Set PATH to JDK on Windows 8 (official version)

Last post described how to "Download and Install JDK 7 on Windows 8 (Official version)".

After downloaded and install JDK 7 on Windows 8, now open a Command Prompt window to run java or javac...!!!

you can optionally set PATH environment variable to JDK so that you can conveniently run the JDK executable files (javac.exe, java.exe, javadoc.exe, and so forth) from any directory without having to type the full path of the command.

To set path, search "Environment Variables" in "Settings", click "Edit the system environment variables".

Click "Environment Variables".

Select System variables of Path, and click Edit...

Add the location of the bin folder of the JDK installation, in my case it is "D:\Program Files\Java\jdk1.7.0_11\bin".

Now, you can close and re-open Command Prompt window, type java and javac to varify your setting.

Install JDK 7 on Windows 8 (Official version)

In this post, I describe how to download and install JDK 7 (Java SE 7u11 currently) on official Windows 8 (not Preview version).

Note: You must have administrative permissions in order to install the JDK on Microsoft Windows.
Note: Installers for JDK 7u6 and later install the JavaFX SDK and integrate it into the JDK installation directory.

Visit http://www.oracle.com/technetwork/java/javase/downloads/index.html, click the download Java Platform button.

Scroll down to check Accept License Agreement, select Java SE Development Kit 7u11, jdk-7u11-windows-i586.exe for Windows x86.

Run the downloaded installer.

Select optional features and location to install.


Select location to install jre.


Completed.

Next:
- Set PATH environment variable to JDK on Official Windows 8

Tuesday, January 15, 2013

Install JDK 7 and update-alternatives on Ubuntu 12.10

Download update JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html, click the DOWNLOAD Java Platform graph.




Scroll download to check the box of Accept License Agreement, and select the package to download. In this case, jdk-7u11-linux-i586.tar.gz for Linux x86 is selected.


Move the downloaded .tar.gz archive binary to the directory you want to install.

Open a Terminal, the the command to unpack the tarball and install the JDK:
$tar zxvf jdk-7u11-linux-i586.tar.gz

For example, if you download the .tar.gz is /home/you, your installed directory will be /home/you/jdk1.7.0_11.

Then, you have to update alternatives for javac and java:
$sudo update-alternatives --install /usr/bin/javac javac /home/you/jdk1.7.0_11/bin/javac 1
$sudo update-alternatives --install /usr/bin/java java /home/you/jdk1.7.0_11/bin/java 1

If you have more than one javac installed, you have to config your javac alternative
$sudo update-alternatives --config javac
$sudo update-alternatives --config java

Finally, delete the downloaded .tar.gz after then.