A simple JavaFX tutorial through simple snippets.
Example 1: ImageviewReady
Here are the code:
Step 1: Create Project
- Open your favorite Java IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following java files:
ImageViewExample.java
- In your editor or IDE, create a file known as
ImageViewExample.java
. - Then add the following code:
(a). ImageViewExample.java
First, go ahead and add the following imports:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
First, go ahead and add the following imports:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
We will need to extend our class using the extend
keyword. By doing that our class
can make use of inheritance to derive properties and functions defined in the parent class
.
public class ImageViewExample extends Application {
Our class
will have the following methods:
void main(String[] args)
void start(Stage primaryStage)
Every Java Program must have a main method. This is the entry point of all Java applications include JavaFX. Add a main()
method and inside it invoke the launch()
function.
public static void main(String[] args) {
Here is the full code:
package com.jenkov.javafx.imageview;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ImageViewExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
FileInputStream input = null;
try {
input = new FileInputStream("assets/media/abstract-5719221_640.jpg");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Image image = new Image(input);
ImageView imageView = new ImageView(image);
VBox vBox = new VBox(imageView);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Download
Download the code using the below links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |