java.net member

Rechercher dans ce site

Les Images dans JavaFX (partie 1)

>> 20 April 2009

Les images en JavaFX sont présentées en utilisant "javafx.scene.image.Image", Cette classe sert a charger une image à partir d'un URL. La variable "url" désigne le URL de l'image. Pour ajouter une image dans une Scene, il faut l'envelopper dans une classe "ImageView"

On peut :

  • Modifier les dimensions d'une image en gardant ou non l'aspect ratio
  • Utiliser un filtre, en privilégiant la vitesse ou la qualité
  • Utiliser la même image dans différentes ImageView
  • Charger l'image en arrière plan
  • Afficher une vignette pendant le téléchargement


Note :
Dans une Scene on peut uniquement insérer des nœuds (nodes).
ImageView est un nœud, une sorte d'adaptateur, permettant d'insérer une image dans une Scene.

Note:
l'URL de image peut-être spécifier sous forme d'un URL complet, vers une ressource sur l'Internet, sur le disque dur, ou sous forme d'un chemin relatif. Il est pratique dans ce dernier cas d'utiliser la variable prédéfinie "__DIR__" pointant vers des classes compilées JavaFX, en mettant le/les images avec des classes compilées.

Attention !!!
En mettant le/les images avec des classes, il faut faire attention à ne pas les supprimer, en appelant "Clean Build Project". Pour éviter cela, il suffit de mettre le/les images avec les sources ".fx", NetBeans se charge de les transférer vers le dossier des classes compilées.


Insérer une image dans NetBeans
Un clic sur la palette -> Image (dans Basic Shapes) -> glissez tout en gardant le bouton de la souris vers un fichier .fx -> "Main.fx"



Des messages d'erreurs !

C'est normal. Un clic droit -> Fix Imports



Exemple :
L'url de image est un url local

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
ImageView {
image: Image {
url: "file:///home/kas/java-logo.png"
}
}

}
}



}

Exemple :
L'URL de l'image est un chemin relatif (l'image est avec les classes compilées)

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
ImageView {
image: Image {
url: "{__DIR__}java-logo.png"
}
}


}
}



}

Modifier les dimensions d'une image
Il est possible de redimensionner une image en changeant son hauteur, largeur, ou les deux en préservant ou non l'aspect ratio de l'image

Note :
Redimensionner une image en modifiant ses attributs width ou height ou les deux au niveau de la classe Image est une opération de "prescaling" effectuée pendant le téléchargement de l'image. En comparaison avec le changement de dimensions au niveau d'ImageView les calculs sont effectués une seul fois.



Exemple :
Modifier la largeur d'une image en demandant à JavaFX de modifier son hauteur pour garder le même aspect ratio de l'image

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
ImageView {
image: Image {
url: "{__DIR__}java-logo.png"
width:100
preserveRatio: true

}
}


}
}



}

Privilégier la qualité ou la vitesse pour modifier les dimensions
smooth: true permet d'avoir une meilleure qualité en sacrifiant la vitesse et vice-versa

Exemple

package javafximages;

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/



import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
ImageView {
image: Image {
url: "{__DIR__}java-logo.png"
width:100
preserveRatio: true
smooth: true //meilleure qualité

}
}


}
}



}

Télécharger une image en arrière plan
Il est possible de télécharger une image en arrière plan, afficher une vignette pendant ce téléchargement et avoir le pourcentage de la progression du téléchargement.

Attention !!!
Apparemment un bug bloque tout avant le téléchargement complet de l'image sur les plateformes Linux. L'exemple ici se compile sans problème, mais n'affiche rien dans l'attente de l'image !!! (mon système Fedora 10)

backgroundLoading: true //oui télécharge l'image en arrière plan (par défaut false)
progress le pourcentage du téléchargement
placeholder l'image affichée pendant le téléchargement (si backgroundLoading: true)


Exemple :

/*
* test3.fx
*
* Created on Apr 18, 2009, 5:26:30 PM
*/

package javafximages;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.ext.swing.SwingSlider;

/**
* @author Kaesar ALNIJRES
*/


var img= Image {
url: "file:///home/kas/java-logo.png"
backgroundLoading: true
height:600
preserveRatio:true
placeholder: Image {
url: "file:///home/kas/clock_48.png"

}}

var iv=ImageView {
image: img
//fitHeight:600
}
Stage {
title: "Télécharger l'image en arrière plan"
width: 800
height: 800
scene: Scene {
content:
[
VBox{
content:[iv]


}
]
}




}
// Utiliser bind pour afficher le pourcentage du téléchargement
var progress = bind iv.image.progress on replace {
println("Téléchargement {progress}%");
}

ImageView
Cette classe permet d'incorporer une image dans la Scene. Elle permet aussi de redimensionner l'image, l'associer à une viewport, etc.

Positionnez une image
L'image étant à l'intérieur d'une ImageView (ImageView hérite de javafx.scene.Node). Il est possible d'utiliser ses coordonnées x et y pour positionner l'image, selon les axes x et y.


Exemple :

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
ImageView {
x:200
y:100
image: Image {
url: "{__DIR__}java-logo.png"
width:100
preserveRatio: true


}
}


}
}


}



Afficher la même image par plusieurs ImageView
L'image est téléchargée une seule fois. Et si on utilise le prescaling elle est redimensionnée une seule fois.

Exemple :
Voyez plus loin un exemple optimisé

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/
var img=Image {
url: "{__DIR__}java-logo.png"
width:100
preserveRatio: true


}

var iv0=ImageView {

image:img
}

var iv1=ImageView {

image:img
}

var iv2=ImageView {

image:img
}

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
{
HBox{
content:
[iv0,iv1,iv2]
}



}
}



}



Exemple :

/*
* Main.fx
*
* Created on Apr 9, 2009, 8:09:12 PM
*/

package javafximages;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.Scene;
import javafx.stage.Stage;


/**
* @author Kaesar ALNIJRES
*/
var vignette=Image{
url:"{__DIR__}clock.png"
}

var img=Image {
url: "{__DIR__}java-logo.png"
width:100
preserveRatio: true
backgroundLoading:true
placeholder:vignette


}


def iv=for (i in [1..5])

ImageView
{
image:img
}

/*
=====ou========
var iv: ImageView[];

for(i in [1..5])
{
def imageView = ImageView
{
image:img
}
insert imageView into iv;
}
============
*/

Stage {
title: "Tester des images"
width: 400
height: 400
scene: Scene {
content:
[HBox{
content:
[iv]
}
]


}
}

Read more...

Run and Deploy JavaFX applets on Linux Fedora

>> 13 April 2009

Working with JavaFX applets using NetBeans is really straightforward -even- on Linux. The only two things to take care of are :

1.Installation of JavaFX plug-in
2.Installation of Sun's version of Java

Tested configurations :

Fedora 10 64bits
Firefox 3.0.8
NetBeans-6.5.1


Note :
When you launch your applet in Firefox, JavaFX run-time will be downloaded and installed automatically.


Note :
Installing the JavaFX plug-in in NetBeans was detailed in a previous article

http://java-javafx-iipt.blogspot.com/2009/03/javafx-111-netbeans-651-on-linux.html


Use JDK or JRE of Sun Mircosystems

Download the last release of Java as .bin files on Sun's web site

http://java.sun.com

Install .bin file/files if you have not already done this.

Note :
OpenJDK installed by default with Linux distributions has problems running applets

Note :
You can install more than one JDK and JRE on the same machine.

ATTENTION !!!
Do not uninstall or delete OpenJDK, other applications on your system need this.


$ chmod u+x jdk-6u13-linux-i586.bin

$ ./jdk-6u13-linux-i586.bin


Installing Java plug-in in Firefox

$ cd $HOME/.mozilla

Note :
.mozilla is the default Firefox configuration folder of the current user



Go to "plugins" folder
You can create this folder (if not found) in .mozilla


$ cd plugins





Link to libnpjp2.so in .mozilla/plugins

" libnpjp2.so" is the second generation plug-in. You can find it in JDK or JRE installation folder

JDK_install_folder/jre/lib/amd64/libnpjp2.so

Note :
In my example JDK is installed in $HOME ($HOME/jdk1.6.0_13_x86_64)

Note :
If you want to use the plug-in on a 32 bits Linux, replace "amd64" with "i386"


$ ln -s $HOME/jdk1.6.0_13_x86_64/jre/lib/amd64/libnpjp2.so




Create a JavaFX project in NetBeans

The following two links give you an idea about using JavaFX in NetBeans

http://java-javafx-iipt.blogspot.com/2009/02/javafx-dans-netbeans-65-ou-70m1-partie.html



http://java-javafx-iipt.blogspot.com/2009/02/utiliser-javafx-dans-netbeans-partie-2.html

Verify or configure Web Browser in NetBeans

Click on "Tools" -> Options



Edit

"No Proxy" is selected

click on "Edit"



Select Firefox

In Web Browsers -> Firefox

In Process -> Browse to or select your Firefox -> OK



Modify your project configuration to run and deploy applets

Right click on your project in NetBeans -> Properties



Run Options

Select "Run"
Select -> Browser (Configuration)
Select -> "Run in Browser" (Application Execution Model)

Wait ! Do not click on "OK" yet.



Application Options
Modify (if needed) applet's Width and Height -> OK




Clean and Build Project
Every time project's properties are modified -> right click on the project -> Clean and Build Project

Run the Applet
Right click on your project in NetBeans -> Run Project



Firefox is launched it began to download JavaFX run-time



Et voilà the applet is running in Firefox



Note :
If you encounter problems, this might be simply if Firefox is in "Offline" mode. In this case applet will not run.

File -> "Work Offline"




Uncheck " Work Offline "



Reload the page



How to deploy the applet on-line

-Edit projectName_browser.jnlp
In NetBeansProjects/projectName/dist

(my project's name is javafx-images. The file to edit is "/home/kas/NetBeansProjects/javafx-images/dist/ javafx-images_browser.jnlp")

-"codebase" tag must point to a server and a directory on this server

http://www.YourSite.com/AppletsFolder

-Create a folder for the applet on the server

-Copy the following files to the applet's folder (on the server) from NetBeansProjects/dist

NameOfApplication.html
NameOfApplication_browser.jnlp
NameOfApplication.jar

In my Example :

  • javafx-images.html
  • javafx-images.jar
  • javafx-images_browser.jnlp

Run the applet

http://www.YourSite.com/AppletsFolder/NameOfApplication.html

Read more...

Déployer des applets JavaFX sur Linux Fedora

Développer des applets JavaFX sur Linux ne pose pas de problèmes particuliers à part l'installation de JavaFX (SDK ou plug-in). Exécuter des applets sur Linux demande par contre un petit effort pour l'installation manuelle du plug-in de Java, spécialement sur des versions 64 bits de Linux. Les étapes décrites dans ce tutoriel sont testées sur Fedora 10, et Firefox 3.0.8 en utilisant NetBeans-6.5.1.


Note :
Quand vous lancez votre applet JavaFX run-time va être télécharger et installer automatiquement.


Installer le plug-in de JavaFX 1.1.1 de NetBeans-6.5.1 sur Linux

http://java-javafx-iipt.blogspot.com/2009/03/javafx-111-et-netbeans-651-sur-linux.html

Première chose, Utilisez Java de Sun
Téléchargez sur le site de Sun la dernière version de JDK ou JRE (fichier .bin à installation manuelle) et installez-la (si ce n'est pas déjà fait)

http://java.sun.com

Note :
Il faut absolument installer le JDK de Sun,OpenJDK fourni avec des distributions de Linux et installé par défaut ne permet pas d'exécuter correctement les applets.

Note :
Il est possible d'installer le JDK ou le JRE de Sun sans toucher la version de Java installée par défaut. Il est même possible d'installer plusieurs JDK ou JRE en parallèle.

Note:
Pour l'installation du JDK ou JRE :
$ chmod u+x fichier.bin
$ ./fichier.bin

ATTENTION !!!
Ne désinstallez rien et penser à télécharger des fichiers .bin de JDK ou JRE sur le site de SunMicrosystems


Installez le plug-in de Java
Allez dans le dossier .mozilla

C'est le dossier de configuration de l'utilisateur en-cours utilisé par Firefox et se trouve dans $HOME/.mozilla

Type dans un terminal (utilisateur ordinaire)

$ cd .mozilla




Changez de dossier pour aller dans plugins
Dans le dossier .mozilla se trouve normalement un dossier "plugins"

Note :
Si le dossier "plugins" n'existe pas il faut le créer (mkdir plugins)

$ cd plugins





Créez un lien vers libnpjp2.so à l'intérieur de .mozilla/plugins

Ce fichier est un plug-in Java deuxième génération selon Sun et se trouve dans le dossier d'installation de JDK ou JRE de Sun comme suite

Dossier_Installation_JDK/jre/lib/amd64/libnpjp2.so

Note :
Dans l'exemple j'ai installé le JDK dans mon dossier personnel ($HOME/jdk1.6.0_13_x86_64)

Note :
Pour utiliser le plug-in sur une plateforme Linux 32 bits, remplacez "amd64" par "i386"

$ ln -s $HOME/jdk1.6.0_13_x86_64/jre/lib/amd64/libnpjp2.so



Créez un projet JavaFX dans NetBeans

Visitez les deux liens suivants pour le développement JavaFX avec NetBeans

http://java-javafx-iipt.blogspot.com/2009/02/javafx-dans-netbeans-65-ou-70m1-partie.html

et

http://java-javafx-iipt.blogspot.com/2009/02/utiliser-javafx-dans-netbeans-partie-2.html

Configurez le navigateur Web dans NetBeans
Un clic sur "Tools" -> Options



Edit

Vérifiez que "No Proxy" est cochée
Un clic sur "Edit"



Sélectionnez votre version de Firefox
Dans Web Browsers -> Firefox

Dans Process -> Modifiez selon votre version Firefox ou sélectionnez avec Browse

Un clic sur OK



Configurez le projet pour exécuter et déployer l'applet

Un clic droit sur votre projet dans NetBeans -> Properties



Options de Run
Un clic sur "Run"
Sélectionnez dans la partie "Configuration" -> Browser
Sélectionnez dans la partie Application Execution Model -> "Run in Browser"

Attendez ! Ne cliquez pas sur "OK"



Options de Application
Modifiez si nécessaire les dimensions de l'applet (Width et Height)
Un clic sur "OK"



Exécutez l'applet

Important !!!
A chaque fois que vous modifiez les paramètres d'un projet avec " properties " -> un clic droit sur le projet -> Clean and Build Project

Un clic droit sur votre projet -> Run Project




Firefox télécharge et installe JavaFX run-time

Firefox s'ouvre et le run-time est téléchargé automatiquement.



Et voilà l'applet est lancé dans Firefox




Note :
En cas de problème, vérifiez avant tout que Firefox n'est pas en mode "Off Line"
Dans l'exemple File -> "Work Offline" est cochée, ceci bloque l'exécution de l'applet




Décochez la case " Work Offline "
Réactualisez la page





Déployer l'applet sur un site Web

Pour déployer l'applet sur un site rien n'est plus facile

  • Allez dans le dossier de projets de NetBeans -> le dossier de votre projet -> dist
(dans l'exemple /home/kas/NetBeansProjects/javafx-images/dist)

  • Editez le fichier Nom_application_browser.jnlp (dans l'exemple javafx-images_browser.jnlp" )

  • Le tag "codebase" désigne un URL complet avec le nom de dossier contenant l'applet :

http://www.nomVotreSite.com/dossierContenantApplet

  • Créez un dossier sur votre site pour l'applet

  • Copiez les fichiers suivants dans le dossier de l'applet à partir du dossier "dist" du projet :

Nom_Application.html
Nom_Application_browser.jnlp
Nom_Application.jar

J'ai donné le nom javafx-images à mon projet et les fichiers sont comme suite :

  • javafx-images.html
  • javafx-images.jar
  • javafx-images_browser.jnlp

Invoquez l'applet :

http://www.nomVotreSite.com/dossierContenantApplet/Nom_Application.html

Read more...

Execute Jar File of a JavaFX project on Linux, or How to Get Rid of ClassNotFoundException ? English

>> 02 April 2009

Deploying a JavaFX stand alone application as a jar file, in NetBeans is really straightforward. All steps are explained on javafx.com web site.

http://javafx.com/docs/tutorials/deployment/

The question here, is it possible to deploy a "normal" jar file and use it as we usually do for jars (ie: java -jar fileName.jar) ?

If you have such kind of questions, this tutorial is for you.

Note :
This tutorial is only a demo. Please read carefully JavaFX license before packaging or distributing any files.


Create a JavaFX project in NetBeans

We need a very simple JavaFX project (HelloWorld)

File -> New Project



Select JavaFX -> JavaFX Script Application -> Next



Enter a name for your project in "Project Name", leave all other options -> Click on Finish



The project is created and Main.fx is opened

Note :
The package name is "helloworld" and when you build the project, the produced class will be "Main.class"



Verify Execution Model

Right click on your project -> Properties -> Run

Select "Standard Execution" in "Application Execution Model" (Default)

Verify Main Class

Click on "OK"




Build the Project

Right click on the project -> Build Project



The Project is Built

Two folder are added inside "NetBeansProject" (default projects folder) in "HelloWorld" folder, these are "dist" and "build"

"build" has compiled classes of the project
"dist" has a jar file containing the compiled classes





Execute the Jar file from the Command Line

Change directory and go to "dist" inside "HelloWorld" project

(The indicated PATH is on my own computer, change as needed)

$cd /home/kas/NetBeansProjects/HelloWorld/dist




Locate JavaFX-SDK

If you installed NetBeans plug-in as mentioned in my previous post in this Blog

http://java-javafx-iipt.blogspot.com/2009/03/javafx-111-netbeans-651-on-linux.html

You will find a "javafx-sdk" folder in this location

$HOME/.netbeans/6.5/javafx-sdk



Running the Jar

Using export or an absolute path to run the produced jar file (HelloWorld.jar).

cp stands for the CLASSPATH

helloworld.Main is the main class with the package name

$ export PATH=$HOME/.netbeans/6.5/javafx-sdk/bin:$PATH

$ javafx -cp HelloWorld.jar helloworld.Main



Trying java -jar HelloWorld.jar

Running the jar file as mentioned before is fine. But it's somehow the source of many problems especially if you give the absolute path to your javafx-sdk !!!. And it's also unusual for Java Developers.

If you try to run the Jar using "java -jar HelloWorld.jar", you will get some error messages. The main messages is : ClassNotFoundException. The program exists with "Could not find the main class: helloworld.Main. Program will exit" message.

This is a well known Exception, when developing Java programs. Isn't it ?

This normally means in Java that the class that contains main method was not found, or the "Main-Class" section in MANIFEST.MF, in the jar file is missing or has errors.



The problem here is different, let take a look at "MANIFEST.MF" and jar's contents.

As you can see, "Main-Class" is in "META-INF/MANIFEST.MF", and has the correct class name with it's package. A new line is inserted to satisfy specification at the end of the file.




The Main.class also is in the jar in the correct location



What is the problem here ?

The answer is simple : Java can not locate JavaFX run-time in the CLASSPATH. It needs indication about this location.

Is there a simple workaround ?

Yes. Normally if you specify the path to JavaFX run-time in the classpath, you'll get no more errors. A better way is to let NetBeans do the work. Please follow...


Copy javafx-sdk folder to a place of your choice.

$ cp -a $HOME/.netbeans/6.5/javafx-sdk $HOME/javafx-sdk

Note :
You can use the copied folder if you want to play with JavaFX using the command line, compiler and interpreter. Or if you want to use "javafx -cp fileName.jar packageName.MainClass" as above.



Right click on the project name in NetBeans -> Select Properties




Select "Libraries" -> Click on "Add JAR/Folder"

Inside the javafx-sdk/lib folder (copied above)

There are two folder "desktop" and "share"

Select all jar files inside "desktop" -> OK

Repeat Add JAR/Folder, and select all jars in "share" -> OK

Uncheck "Build Projects on Classpath"

Click on OK when all jars are added





Right click on your project -> Clean and Build Project



That's All :)

You will find in the "dist" folder HelloWorld.jar file and "lib" folder packaged for you by NetBeans. This contains the needed JavaFX run-time.

MANIFEST.MF was also updated with the new CLASSPATH




Let's try it

$ java -jar HelloWorld.jar

Et voilà. Application is running, no more errors.

Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP