源本科技 | 码上会

JavaFX 飞机大战(常用 API)

2026/02/25
49
0

1. Stage (舞台)

Stage 是顶级窗口的抽象表示,它是 JavaFX 应用程序中的主要窗口。它可以包含一个或多个 Scene(场景),用于展示用户界面和交互。Stage 控制着窗口的显示、大小、位置以及其他窗口管理属性,是 JavaFX 应用程序与操作系统用户界面之间的桥梁。

常用方法

方法

说明

void show()

显示舞台,若舞台已经可见则不执行任何操作

void showAndWait()

显示舞台,并等待其关闭后再继续执行

void hide()

隐藏舞台

void close()

关闭舞台

void setTitle(String title)

设置舞台的标题

String getTitle()

获取舞台的标题

void setScene(Scene scene)

设置舞台的场景

Scene getScene()

获取当前舞台的场景

void setWidth(double width) / getWidth()

设置 / 获取舞台的宽度

void setHeight(double height) / getHeight()

设置 / 获取舞台的高度

void setX(double x) / getX()

设置 / 获取舞台的 X 坐标

void setY(double y) / getY()

设置 / 获取舞台的 Y 坐标

void setResizable(boolean resizable)

设置舞台是否可调整大小

boolean isResizable()

获取舞台是否可调整大小的状态

void setFullScreen(boolean value)

设置舞台是否全屏显示

void setIconified(boolean value)

设置舞台是否最小化

void setMaximized(boolean value)

设置舞台是否最大化

void setOpacity(double value)

设置舞台的透明度(0.0 到 1.0)

void setAlwaysOnTop(boolean value)

设置舞台是否总是置于其他窗口之上

void initModality(Modality modality)

设置舞台的模态类型(如应用模态、窗口模态等)

void initOwner(Window owner)

设置舞台的所有者窗口

代码示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class StageAPIExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 设置舞台的标题
        primaryStage.setTitle("JavaFX Stage API Example");

        // 创建一个按钮
        Button button = new Button("Click Me!");

        // 设置按钮的点击事件处理
        button.setOnAction(event -> {
            System.out.println("Button clicked!");
        });

        // 创建一个布局并将按钮添加到布局中
        StackPane root = new StackPane();
        root.getChildren().add(button);

        // 创建一个场景,并将布局添加到场景中
        Scene scene = new Scene(root, 300, 250);

        // 将场景设置到舞台上
        primaryStage.setScene(scene);

        // 设置舞台的宽度和高度
        primaryStage.setWidth(400);
        primaryStage.setHeight(300);

        // 设置舞台的位置(距屏幕左上角的偏移)
        primaryStage.setX(100);
        primaryStage.setY(100);

        // 设置舞台是否可调整大小
        primaryStage.setResizable(false);

        // 设置舞台是否显示在其他窗口之上
        primaryStage.setAlwaysOnTop(false);

        // 设置舞台的透明度(0.0 为完全透明,1.0 为完全不透明)
        primaryStage.setOpacity(0.9);

        // 显示舞台
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

2. Scene (场景)

Scene 是用户界面的容器,用于组织和呈现应用程序的可视化内容。每个 JavaFX 应用程序至少有一个场景,场景包含一个根节点(通常是布局或容器),根节点包含了应用程序的所有 UI 组件。Scene 提供了设置和管理 UI 组件的方法,并且可以响应用户输入(如键盘和鼠标事件)。

常用方法

方法

说明

void setRoot(Parent root)

设置场景的根节点

Parent getRoot()

获取场景的根节点

void setWidth/Height(double val)

设置场景的宽度 / 高度

void setFill(Paint value)

设置场景的背景填充色

void setCursor(Cursor cursor)

设置场景的光标类型

void setOnKeyPressed(...)

设置按键按下事件处理器

void setOnMouseClicked(...)

设置鼠标点击事件处理器

void setOnMouseMoved(...)

设置鼠标移动事件处理器

(其他鼠标 / 键盘事件类似)

...

代码示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.Cursor;

public class SceneAPIExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 创建一个按钮
        Button button = new Button("Click Me!");

        // 创建一个布局并将按钮添加到布局中
        StackPane root = new StackPane();
        root.getChildren().add(button);

        // 创建一个场景,并将布局添加到场景中,设置场景的宽度和高度
        Scene scene = new Scene(root, 300, 250);

        // 设置场景的背景填充色为灰色
        scene.setFill(Color.GRAY);

        // 设置场景的光标类型为手形
        scene.setCursor(Cursor.HAND);

        // 设置按键按下事件处理器
        scene.setOnKeyPressed(event -> {
            System.out.println("Key Pressed: " + event.getCode());
        });

        // 设置鼠标点击事件处理器
        scene.setOnMouseClicked(event -> {
            System.out.println("Mouse Clicked at: " + event.getX() + ", " + event.getY());
        });

        // 设置舞台的标题
        primaryStage.setTitle("JavaFX Scene API Example");

        // 将场景设置到舞台上
        primaryStage.setScene(scene);

        // 显示舞台
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

3. Pane (面板)

Pane 是一种布局容器,用于组织和排列应用程序界面中的可视化元素。Pane 类是所有布局容器的基类,提供了基本的布局功能,例如设置子节点的位置和大小。它允许开发者通过添加、移除和调整子节点的位置来灵活地设计和管理界面布局。

常用方法

方法

说明

setMin/Max/PrefWidth/Height

设置最小 / 最大 / 首选 宽度或高度

ObservableList<Node> getChildren()

获取 Pane 中的子节点列表

getChildren().addAll(...)

向 Pane 中添加多个子节点

getChildren().remove(...)

从 Pane 中移除指定的子节点

getChildren().clear()

清空 Pane 中所有子节点

setLayoutX/Y(double value)

设置 Pane 相对于其父节点的位置

setPadding(Insets insets)

设置 Pane 的内边距

setSpacing(double value)

设置 Pane 中子节点之间的间距 (部分子类支持)

代码示例

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class PaneAPIExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 创建一个 Pane
        Pane pane = new Pane();

        // 设置 Pane 的背景颜色
        pane.setStyle("-fx-background-color: lightblue;");

        // 创建按钮并设置其布局位置
        Button button1 = new Button("Button 1");
        button1.setLayoutX(50);
        button1.setLayoutY(50);

        Button button2 = new Button("Button 2");
        button2.setLayoutX(150);
        button2.setLayoutY(50);

        // 将按钮添加到 Pane 中
        pane.getChildren().addAll(button1, button2);

        // 设置 Pane 的内边距
        pane.setPadding(new Insets(20));

        // 创建一个场景并将 Pane 设置为根节点
        Scene scene = new Scene(pane, 300, 200);

        // 设置舞台的标题
        primaryStage.setTitle("JavaFX Pane API Example");

        // 将场景设置到舞台上
        primaryStage.setScene(scene);

        // 显示舞台
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

4. Control (控件)

Control 是一种用户界面元素,用于接收用户输入或显示应用程序的状态和内容(如按钮、复选框、文本框等)。Control 类提供了通用的属性和方法,使开发者能够定制和管理控件的外观、行为和布局。

常用方法

方法

说明

void setId(String value)

设置控件的唯一标识符

void setStyle(String value)

设置控件的 CSS 样式

void setTooltip(Tooltip value)

设置控件的工具提示

void setDisable(boolean value)

禁用或启用控件

void setVisible(boolean value)

设置控件是否可见

setPrefWidth/Height

设置控件的首选宽度 / 高度

setLayoutX/Y

设置控件的水平 / 垂直布局位置

setOnMouseClicked/KeyPressed

设置鼠标点击 / 按键按下事件处理器

代码示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ControlAPIExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 创建一个按钮
        Button button = new Button("Click Me!");

        // 设置按钮的唯一标识符
        button.setId("myButton");

        // 设置按钮的CSS样式
        button.setStyle("-fx-background-color: blue; -fx-text-fill: white;");

        // 创建一个布局并将按钮添加到布局中
        StackPane root = new StackPane();
        root.getChildren().add(button);

        // 创建一个场景并将布局设置为根节点
        Scene scene = new Scene(root, 300, 250);

        // 设置按钮的工具提示
        button.setTooltip(new Tooltip("Click this button"));

        // 设置按钮点击事件处理器
        button.setOnMouseClicked(event -> {
            System.out.println("Button clicked!");
        });

        // 设置舞台的标题
        primaryStage.setTitle("JavaFX Control API Example");

        // 将场景设置到舞台上
        primaryStage.setScene(scene);

        // 显示舞台
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

5. Node (节点)

Node 是场景图(Scene Graph)中的基本构建块,代表了界面上的可视化元素(如控件、形状、文本等)。每个 Node 都具有位置、大小和转换属性,可以被添加到 JavaFX 的场景图中,构成复杂的用户界面。

常用方法

方法

说明

setId / getStyle

设置 ID 或 CSS 样式

setTranslateX/Y

设置节点在水平 / 垂直方向的平移距离

setRotate(double value)

设置节点的旋转角度(度数)

setScaleX/Y(double value)

设置节点在水平 / 垂直方向的缩放比例

setVisible(boolean value)

设置节点是否可见

setOpacity(double value)

设置节点的不透明度(0.0-1.0)

(注:Control 和 Shape 等类都继承自 Node,因此也拥有这些方法)


6. MediaPlayer (媒体播放器)

MediaPlayer 用于播放音频和视频文件。它允许开发者加载、控制和管理多种媒体资源,包括播放、暂停、停止、调整音量等功能。

常用方法

方法

说明

play() / pause() / stop()

播放 / 暂停 / 停止媒体

setVolume(double volume)

设置媒体的音量

setRate(double rate)

设置媒体的播放速率

setCycleCount(int count)

设置媒体的循环次数

setOnReady/Playing/Paused

设置状态改变时的回调

setOnEndOfMedia

设置媒体播放结束时的回调

setAutoPlay(boolean value)

设置是否自动播放

dispose()

释放媒体资源

代码示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class MediaPlayerAPIExample extends Application {

    // 请替换为实际的媒体文件路径
    private static final String MEDIA_URL = "file:///path/to/your/media/file.mp4"; 

    @Override
    public void start(Stage primaryStage) {
        // 创建媒体对象
        Media media = new Media(MEDIA_URL);

        // 创建媒体播放器
        MediaPlayer mediaPlayer = new MediaPlayer(media);

        // 设置自动播放
        mediaPlayer.setAutoPlay(true);

        // 创建播放/暂停按钮
        Button playButton = new Button("Play");
        playButton.setOnAction(event -> {
            if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
                mediaPlayer.pause();
                playButton.setText("Play");
            } else {
                mediaPlayer.play();
                playButton.setText("Pause");
            }
        });

        // 创建停止按钮
        Button stopButton = new Button("Stop");
        stopButton.setOnAction(event -> {
            mediaPlayer.stop();
            playButton.setText("Play");
        });

        // 创建垂直布局,并将按钮添加到布局中
        VBox root = new VBox(10);
        root.getChildren().addAll(playButton, stopButton);

        // 创建一个场景并将布局设置为根节点
        Scene scene = new Scene(root, 200, 100);

        // 设置舞台的标题
        primaryStage.setTitle("JavaFX MediaPlayer API Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

7. 动画类 (Animation)

TranslateTransition (平移动画)

用于实现节点在水平和垂直方向上的平移动画效果。

关键方法: setNode, setFromX/Y, setToX/Y, setByX/Y, setDuration, setCycleCount, setAutoReverse, play().

示例:

import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TranslateTransitionExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        Rectangle rect = new Rectangle(100, 100, Color.BLUE);
        StackPane root = new StackPane();
        root.getChildren().add(rect);
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("TranslateTransition Example");
        primaryStage.setScene(scene);
        primaryStage.show();

        TranslateTransition translateTransition = new TranslateTransition(Duration.seconds(2), rect);
        translateTransition.setFromX(0); 
        translateTransition.setToX(200); 
        translateTransition.setCycleCount(TranslateTransition.INDEFINITE); 
        translateTransition.setAutoReverse(true); 
        
        translateTransition.play();
    }
    public static void main(String[] args) { launch(args); }
}

SequentialTransition (顺序动画)

用于按顺序播放多个动画效果。

关键方法: getChildren().addAll(...), setCycleCount, setAutoReverse, play().

示例:

import javafx.animation.FadeTransition;
import javafx.animation.SequentialTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class SequentialTransitionExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("JavaFX SequentialTransition Example");
        label.setOpacity(0);

        FadeTransition fadeIn = new FadeTransition(Duration.seconds(1), label);
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);

        FadeTransition fadeOut = new FadeTransition(Duration.seconds(1), label);
        fadeOut.setFromValue(1);
        fadeOut.setToValue(0);

        SequentialTransition sequentialTransition = new SequentialTransition();
        sequentialTransition.getChildren().addAll(fadeIn, fadeOut);
        sequentialTransition.setCycleCount(SequentialTransition.INDEFINITE);
        sequentialTransition.setAutoReverse(true);

        StackPane root = new StackPane();
        root.getChildren().add(label);
        Scene scene = new Scene(root, 400, 200);

        primaryStage.setTitle("SequentialTransition Example");
        primaryStage.setScene(scene);
        primaryStage.show();

        sequentialTransition.play();
    }
    public static void main(String[] args) { launch(args); }
}

Timeline (时间轴)

用于创建和管理基于关键帧的动画序列。

关键方法: getKeyFrames().addAll(...), setCycleCount, play().

示例:

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TimelineAPIExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Hello, JavaFX!");
        StackPane root = new StackPane();
        root.getChildren().add(label);
        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Timeline Example");
        primaryStage.setScene(scene);
        primaryStage.show();

        Timeline timeline = new Timeline();
        timeline.getKeyFrames().addAll(
                new KeyFrame(Duration.ZERO, e -> label.setText("Starting...")),
                new KeyFrame(Duration.seconds(1), e -> label.setText("Animation in progress...")),
                new KeyFrame(Duration.seconds(2), e -> label.setText("Animation finished!"))
        );

        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);
        timeline.play();
    }
    public static void main(String[] args) { launch(args); }
}

8. Event (事件)

Event 是指用户或系统操作引发的通知(如鼠标点击、键盘输入)。开发者可以捕获和处理这些事件以执行相应逻辑。

常见事件类及方法

事件类

常用方法

说明

MouseEvent

getX(), getY()

获取鼠标坐标

getButton()

获取触发事件的鼠标按钮

KeyEvent

getText()

获取按键对应的文本

getCode()

获取按键的 KeyCode (如 ENTER, A)

ActionEvent

consume()

标记事件已消费,阻止传播

WindowEvent

getEventType()

获取窗口事件类型 (如 CLOSE)

ScrollEvent

getDeltaX(), getDeltaY()

获取滚动量

DragEvent

acceptTransferModes(...)

接受拖放传输模式

代码示例 (KeyEvent)

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;

public class KeyEventExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Press a key");
        StackPane root = new StackPane();
        root.getChildren().add(label);
        Scene scene = new Scene(root, 300, 200);

        // 添加键盘事件处理器
        scene.setOnKeyPressed(event -> {
            String text = event.getText();
            KeyCode code = event.getCode();
            String message = "Key Pressed: " + text + ", KeyCode: " + code;
            System.out.println(message);
            label.setText(message);
        });

        primaryStage.setTitle("KeyEvent Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}