First JavaFX App
Creating a Basic JavaFX Application
Project Setup
## Create project directory
mkdir labex-javafx-demo
cd labex-javafx-demo
## Initialize Maven project
mvn archetype:generate \
-DgroupId=com.labex \
-DartifactId=javafx-demo \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
Application Structure
graph TD
A[Project Root] --> B[src/main/java]
B --> C[Main Application Class]
B --> D[Controller Classes]
A --> E[pom.xml]
Complete JavaFX Application Example
Main Application Class
package com.labex;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXDemoApp extends Application {
@Override
public void start(Stage primaryStage) {
// Create UI Components
Button clickButton = new Button("Click Me!");
VBox root = new VBox(10);
root.getChildren().add(clickButton);
// Configure Button Action
clickButton.setOnAction(event -> {
System.out.println("Button Clicked in LabEx JavaFX Demo!");
});
// Create and Configure Scene
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("LabEx JavaFX Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
UI Component Types
Component |
Description |
Use Case |
Button |
Interactive clickable element |
Triggering actions |
Label |
Display text |
Showing information |
TextField |
User text input |
Collecting user data |
CheckBox |
Binary selection |
Multiple choices |
ComboBox |
Dropdown selection |
Selecting from list |
Event Handling
Event Types
graph LR
A[JavaFX Events] --> B[Mouse Events]
A --> C[Keyboard Events]
A --> D[Window Events]
A --> E[Action Events]
Advanced Event Handling
// Lambda Expression Event Handling
button.setOnMouseClicked(event -> {
switch(event.getButton()) {
case PRIMARY:
System.out.println("Left Click");
break;
case SECONDARY:
System.out.println("Right Click");
break;
}
});
Styling JavaFX Applications
Inline CSS
button.setStyle(
"-fx-background-color: #3498db;" +
"-fx-text-fill: white;" +
"-fx-font-size: 14px;"
);
Maven Dependency Configuration
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17.0.2</version>
</dependency>
</dependencies>
Running the Application
## Compile the project
mvn clean compile
## Run JavaFX application
mvn javafx:run
Best Practices
- Separate UI and logic
- Use FXML for complex layouts
- Implement proper event handling
- Use CSS for styling
- Follow JavaFX lifecycle methods
By following these steps, you can create your first interactive JavaFX application in the LabEx development environment.