We’ve prepared these code snippets to help you learn JavaFX.
Here are the code snippets:
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:
ContextMenuExample.java
- In your editor or IDE, create a file known as
ContextMenuExample.java
. - Then add the following code:
(a). ContextMenuExample.java
We will need to add a bunch of imports in our class:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
The next step is to extend our class
as shown below:
public class ContextMenuExample extends Application {
Our class
will have the following methods:
void main(String[] args)
void start(Stage primaryStage)
The next step is to define our main()
method a shown below:
public static void main(String[] args) {
Here is the full code:
package com.jenkov.javafx.contextmenu;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ContextMenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem1 = new MenuItem("Choice 1");
MenuItem menuItem2 = new MenuItem("Choice 2");
MenuItem menuItem3 = new MenuItem("Choice 3");
menuItem3.setOnAction((event) -> {
System.out.println("Choice 3 clicked!");
});
contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3);
TextArea textArea = new TextArea();
textArea.setContextMenu(contextMenu);
VBox vBox = new VBox(textArea);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.setTitle("JavaFX App");
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 |