快速学习 JavaFX 进行 GUI 应用开发

JavaFX是Java的一个用于构建丰富图形用户界面的框架。通过JavaFX,开发者可以创建功能强大、交互性强且美观的桌面应用程序。

一、JavaFX简介

1. JavaFX的历史和现状

JavaFX最初作为Java的一部分发布,旨在替代Swing作为Java的主要GUI工具包。JavaFX提供了一组丰富的GUI控件、布局管理器和图形绘制功能,支持硬件加速和高性能的用户界面。

2. JavaFX的安装和配置

要使用JavaFX,首先需要在项目中配置JavaFX库。可以通过以下步骤完成:

  • 下载并安装JDK(Java Development Kit)。
  • 下载并配置JavaFX SDK。
  • 配置IDE(如IntelliJ IDEA、Eclipse)以使用JavaFX。

以IntelliJ IDEA为例,配置JavaFX步骤如下:

  1. 创建新的Java项目。
  2. 下载JavaFX SDK并解压。
  3. 配置项目依赖:打开项目结构(Project Structure),选择模块(Modules),添加JavaFX库路径。
  4. 配置运行参数:在运行配置中添加VM选项,如--module-path /path/to/javafx-sdk/lib --add-modules javafx.controls,javafx.fxml

二、JavaFX基础

1. JavaFX应用程序结构

JavaFX应用程序通常继承自javafx.application.Application类,必须重写start(Stage primaryStage)方法。以下是一个简单的JavaFX应用程序:

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

public class HelloWorld extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World");

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(event -> System.out.println("Hello World!"));

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
2. JavaFX中的Scene和Stage
  • Stage:JavaFX中的顶级容器,代表窗口。primaryStage是主窗口。
  • Scene:场景,包含所有的GUI组件。一个Stage可以包含一个或多个Scene,但一次只能显示一个Scene

三、JavaFX常用组件

JavaFX提供了丰富的UI控件,以下是一些常用组件:

1. 控件概述
  • Button:按钮,用于触发事件。
  • Label:标签,用于显示文本。
  • TextField:文本框,用于输入单行文本。
  • TextArea:文本区域,用于输入多行文本。
  • CheckBox:复选框,用于选择或取消选择。
  • RadioButton:单选按钮,一组单选按钮中只能选择一个。
  • ComboBox:组合框,下拉列表。
  • ListView:列表视图,显示可滚动的项目列表。
2. 使用示例

以下示例展示了如何使用这些控件:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class UIComponentsExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX UI Components");

        Label label = new Label("Label Example");
        Button button = new Button("Button Example");
        TextField textField = new TextField("TextField Example");
        TextArea textArea = new TextArea("TextArea Example");
        CheckBox checkBox = new CheckBox("CheckBox Example");
        RadioButton radioButton = new RadioButton("RadioButton Example");
        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.getItems().addAll("Option 1", "Option 2", "Option 3");
        ListView<String> listView = new ListView<>();
        listView.getItems().addAll("Item 1", "Item 2", "Item 3");

        VBox vbox = new VBox(label, button, textField, textArea, checkBox, radioButton, comboBox, listView);
        Scene scene = new Scene(vbox, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

四、布局管理

JavaFX提供了多种布局管理器,用于安排和组织控件的位置和大小。

1. 常见布局管理器
  • Pane:基本的布局管理器,没有特定布局规则。
  • HBox:水平布局,将子节点排列成一行。
  • VBox:垂直布局,将子节点排列成一列。
  • BorderPane:边界布局,分为顶部、底部、左边、右边和中心区域。
  • GridPane:网格布局,以行和列的形式排列子节点。
  • StackPane:堆叠布局,将子节点堆叠在一起。
  • FlowPane:流式布局,按行或列排列子节点。
  • AnchorPane:锚点布局,可以固定子节点到容器的特定边缘。
2. 布局示例

以下示例展示了如何使用这些布局管理器:

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

public class LayoutExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Layout Example");

        Button btn1 = new Button("Button 1");
        Button btn2 = new Button("Button 2");
        Button btn3 = new Button("Button 3");
        Button btn4 = new Button("Button 4");

        // HBox
        HBox hbox = new HBox(10, btn1, btn2);

        // VBox
        VBox vbox = new VBox(10, btn3, btn4);

        // BorderPane
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(new Button("Top"));
        borderPane.setBottom(new Button("Bottom"));
        borderPane.setLeft(new Button("Left"));
        borderPane.setRight(new Button("Right"));
        borderPane.setCenter(new Button("Center"));

        // GridPane
        GridPane gridPane = new GridPane();
        gridPane.add(new Button("Grid 1"), 0, 0);
        gridPane.add(new Button("Grid 2"), 1, 0);
        gridPane.add(new Button("Grid 3"), 0, 1);
        gridPane.add(new Button("Grid 4"), 1, 1);

        VBox mainVBox = new VBox(20, hbox, vbox, borderPane, gridPane);
        Scene scene = new Scene(mainVBox, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

五、事件处理

事件处理是JavaFX开发中的重要部分,用于响应用户的操作。

1. 事件模型

JavaFX的事件模型基于观察者模式。事件源是触发事件的对象,事件监听器是处理事件的对象。

2. 常见事件类型
  • ActionEvent:由按钮、菜单项等触发的操作事件。
  • MouseEvent:由鼠标操作触发的事件,如点击、移动、拖动等。
  • KeyEvent:由键盘操作触发的事件,如按键按下、释放等。
3. 事件处理示例

以下示例展示了如何处理按钮点击事件和鼠标事件:

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.input.MouseEvent;

public class EventHandlingExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Event Handling Example");

        Button btn = new Button("Click Me");
        btn.setOnAction(event -> System.out.println("Button clicked!"));

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        root.setOnMouseClicked(this::handleMouseClick);

        Scene scene = new Scene(root, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void handleMouseClick(MouseEvent event) {
        System.out.println("Mouse clicked at: " + event.getSceneX() + ", " + event.getSceneY());
    }

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

六、样式和皮肤

JavaFX支持使用CSS(层叠样式表)来定义控件的样式,允许开发者轻松地定制应用程序的外观。

1. 使用CSS样式

可以在外部CSS文件中定义样式,并在Java代码中加载:

/* styles.css */
.button {
    -fx-background-color: #ff0000;
    -fx-text-fill: #ffffff;
}

在Java代码中加载CSS文件:

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

public class CSSExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX CSS Example");

        Button btn = new Button("Styled Button");

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
2. 内联样式

也可以直接在Java代码中设置样式:

btn.setStyle("-fx-background-color: #ff0000; -fx-text-fill: #ffffff;");

七、动画和特效

JavaFX提供了丰富的动画和特效API,允许开发者创建动态和生动的用户界面。

1. 动画

JavaFX中的动画由Animation类及其子类(如TransitionTimeline等)实现。

以下示例展示了如何创建一个简单的动画:

import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimationExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Animation Example");

        Button btn = new Button("Animate Me");

        TranslateTransition translateTransition = new TranslateTransition(Duration.millis(2000), btn);
        translateTransition.setFromX(0);
        translateTransition.setToX(200);
        translateTransition.setCycleCount(TranslateTransition.INDEFINITE);
        translateTransition.setAutoReverse(true);

        btn.setOnAction(event -> translateTransition.play());

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
2. 特效

JavaFX中的特效由Effect类及其子类(如DropShadowBloomGaussianBlur等)实现。

以下示例展示了如何应用阴影效果:

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

public class EffectExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Effect Example");

        Button btn = new Button("Shadowed Button");
        DropShadow dropShadow = new DropShadow();
        dropShadow.setColor(Color.GRAY);
        dropShadow.setRadius(10);
        btn.setEffect(dropShadow);

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

八、FXML和Scene Builder

JavaFX支持使用FXML(XML格式)来描述用户界面。FXML文件可以通过JavaFX Scene Builder(可视化布局工具)创建和编辑。

1. FXML文件

以下是一个简单的FXML文件示例:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.StackPane?>

<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.Controller">
    <Button text="Click Me" fx:id="myButton" />
</StackPane>
2. 控制器类

FXML文件中的fx:controller属性指定了控制器类,该类用于处理界面逻辑:

package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Controller {
    @FXML
    private Button myButton;

    @FXML
    private void initialize() {
        myButton.setOnAction(event -> System.out.println("Button clicked!"));
    }
}
3. 加载FXML文件

在Java代码中加载FXML文件:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class FXMLExample extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("JavaFX FXML Example");

        Parent root = FXMLLoader.load(getClass().getResource("layout.fxml"));
        Scene scene = new Scene(root, 300, 250);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

黑马程序员免费预约咨询

  • 29
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值