Java Reference
In-Depth Information
Building Your GUI Application with JavaFX
Problem
You want to build GUI applications with less work than writing Swing code.
Solution
JavaFX provides one alternative.
Discussion
JavaFX is a GUI package that ships with some releases of Java SE 7 and probably all re-
leases of Java SE 8. It is simpler to use, and also provides its own “standard” drag-and-drop
GUI builder (which is a separate download). Here is a “Hello, world” program in JavaFX
that simply prints to the standard output when a button is pressed:
import
import
javafx.application.Application
javafx.application.Application
;
import
import
javafx.event.ActionEvent
javafx.event.ActionEvent
;
import
import
javafx.event.EventHandler
javafx.event.EventHandler
;
import
import
javafx.scene.Scene
javafx.scene.Scene
;
import
import
javafx.scene.control.Button
javafx.scene.control.Button
;
import
import
javafx.scene.layout.StackPane
javafx.scene.layout.StackPane
;
import
import
javafx.stage.Stage
javafx.stage.Stage
;
public
public class
class
HelloFx
HelloFx
extends
extends
Application
{
@Override
public
public
void
void
start
(
Stage stage
) {
stage
.
setTitle
(
"JavaFX Hello!"
);
Button btn
=
new
new
Button
();
btn
.
setText
(
"Run Greeting"
);
btn
.
setOnAction
(
new
new
EventHandler
<
ActionEvent
>() {
@Override
public
public
void
void
handle
(
ActionEvent e
) {
System
.
out
.
println
(
"Hello from JavaFX"
);
}
});
StackPane rootPane
=
new
new
StackPane
();
rootPane
.
getChildren
().
add
(
btn
);