javafx官方文档学习之一Application与Stage,Scene初探

本文介绍如何使用JavaFX创建简单的应用程序,包括如何设置舞台、场景和UI元素,以及事件处理机制。通过一个简单的HelloWorld示例,深入理解JavaFX的基本概念和应用流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的博文小站:http://www.xby1993.net,所有文章均为同步发布。

转载请注明作者,出处。

自jdk7u6之后javafx已经嵌入在jre之中

2 javafx UI设计工具JavaFX Scene Builder.

Oracle支持的javafx额外UI库,现在只支持jdk8:controlsfx

3 HelloWord解析:

package helloworld;
 
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
 
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

  • The main class for a JavaFX application extends the javafx.application.Applicationclass. The start() method is the main entry point for all JavaFX applications.

  • A JavaFX application defines the user interface container by means of a stage and a scene. The JavaFX Stage class is the top-level JavaFX container. The JavaFX Scene class is the container for all content. Example 1-1 creates the stage and scene and makes the scene visible in a given pixel size.

  • In JavaFX, the content of the scene is represented as a hierarchical scene graph of nodes. In this example, the root node is a StackPane object, which is a resizable layout node. This means that the root node's size tracks the scene's size and changes when the stage is resized by a user.

  • The root node contains one child node, a button control with text, plus an event handler to print a message when the button is pressed.

  • The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file. However, it is useful to include the main() method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main() method.

总结一下Application是javafx程序的入口点,就是Main类要继承Application类,然后覆盖其start方法,而start方法用于展示stage舞台,stage舞台是一个类似于Swing中的JWindow的顶级容器,代表一个窗口。它用于容纳场景Scene,场景Scene是一个类似于Swing的JFrame的容器。但是却是以树的形式组织的,每一个子组件就是它的一个节点。其根节点一般是Pane面板如以上的:StackPane.它是一个根节点容器。可以容纳子节点。各子节点挂载在其上。

主要实现步骤:Stage(即start方法的参数,一般考系统传入)设置场景-场景Scene包装面板根节点-面板Pane根节点挂载子节点-子节点。

注意:根节点的大小是随着Scene自适应的。

main()方法并不是必须有的,一般javafx程序是将javafx packager Tool嵌入到jar文件,

但是为了便于调试,还是写出来为好。

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

从这个HelloWorld程序中可以看出事件处理机制与Swing相差不大。

Figure 1-1 Hello World Scene Graph


下面分析一下Application类:


Life-cycle:生命周期:

Application是一个javafx程序的入口类,是一个抽象类,必须子类化,它的start方法为抽象方法,必须覆盖

而init()和stop()方法则为空实现。


javafx运行时在程序启动时将会按顺序依次进行如下步骤:

  1. Constructs an instance of the specified Application class

  2. Calls the init() method

  3. Calls the start(javafx.stage.Stage) method

  4. Waits for the application to finish, which happens when either of the following occur:

  • the application calls Platform.exit()

  • the last window has been closed and the implicitExit attribute on Platform is true

Calls the stop() method


参数:

    Application parameters are available by calling the getParameters() method from the init() method, or any time after the init method has been called.

    Application可以通过getParameters()方法在init()方法内获取参数,或者在init()调用之后的任何方法中获取。


Threading线程:

    关于:Launch Thread启动线程和Application线程的区别

    Lacunch Thread启动线程是javafx运行时触发的,它会负责构造Application对象和调用Application对象的init()方法,这意味着主State主场景是在launcher Thread线程中被构造的,(因为它是init方法的参数)故而我们可以不用管它,直接拿来用就可以了。但是launch Thread并不是UI线程。它的工作也就只是上面所说的。

    Application Thread:相当于Swing中的UI事件分派线程EDT:

        JavaFX creates an application thread for running the application start method, processing input events, and running animation timelines. Creation of JavaFX Scene and Stage objects as well as modification of scene graph operations to live objects (those objects already attached to a scene) must be done on the JavaFX application thread.

HostServicesgetHostServices()

Gets the HostServices provider for this application.

Application.ParametersgetParameters()

Retrieves the parameters for this Application, including any arguments passed on the command line and any parameters specified in a JNLP file for an applet or WebStart application.

voidinit()

The application initialization method.

static voidlaunch(java.lang.Class<? extends Application> appClass, java.lang.String... args)

Launch a standalone application.

static voidlaunch(java.lang.String... args)

Launch a standalone application.

voidnotifyPreloader(Preloader.PreloaderNotification info)

Notifies the preloader with an application-generated notification.

abstract voidstart(Stage primaryStage)

The main entry point for all JavaFX applications.

voidstop()

This method is called when the application should stop, and provides a convenient place to prepare for application exit and destroy resources.

    


The following example will illustrate a simple JavaFX application.

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class MyApp extends Application {
    public void start(Stage stage) {
        Circle circ = new Circle(40, 40, 30);
        Group root = new Group(circ);
        Scene scene = new Scene(root, 400, 300);

        stage.setTitle("My JavaFX Application");
        stage.setScene(scene);
        stage.show();
    }
}

解析Stage类
    Stage是Window类的子类,Window对象中有获取窗口焦点位置,设置监听窗口打开隐藏关闭显示事件的方法。有设置窗口到屏幕中央。等相关方法。
    
    The JavaFX Stage class is the top level JavaFX container. The  Additional Stage objects may be constructed by the application.and  
    Stage的Style风格样式
A stage has one of the following styles:
StageStyle.DECORATED - a stage with a solid white background and platform decorations.
StageStyle.UNDECORATED - a stage with a solid white background and no decorations.
StageStyle.TRANSPARENT - a stage with a transparent background and no decorations.
StageStyle.UTILITY - a stage with a solid white background and minimal platform decorations.
构造器如下:
Constructor and Description
Stage()Creates a new instance of decorated Stage.    
Stage(StageStyle style)Creates a new instance of Stage.    
显然可以通过构造器指定样式。

Stage的展现模式:

Modality

A stage has one of the following modalities:

  • Modality.NONE - a stage that does not block any other window.

  • Modality.WINDOW_MODAL - a stage that blocks input events from being delivered to all windows from its owner (parent) to its root. Its root is the closest ancestor window without an owner.

  • Modality.APPLICATION_MODAL - a stage that blocks input events from being delivered to all windows from the same application, except for those from its child hierarchy.

类似于对话框形式的模式与非模式。

When a window is blocked by a modal stage its Z-order relative to its ancestors is preserved, and it receives no input events and no window activation events, but continues to animate and render normally. Note that showing a modal stage does not necessarily block the caller. The show() method returns immediately regardless of the modality of the stage. Use theshowAndWait() method if you need to block the caller until the modal stage is hidden (closed). The modality must be initialized before the stage is made visible.

模式形式的Stage会阻塞输入事件input event和窗口活动事件,但是并不阻塞画面的渲染和变化。

也不会阻塞它的调用者,调用者show()之后会立即返回。也可以采用阻塞形式showAndWait().但是要注意:模式形式的Stage必须在调用show之前完成所有初始化工作。


import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 

public class HelloWorld extends Application {

    @Override public void start(Stage stage) {
        Scene scene = new Scene(new Group(new Text(25, 25, "Hello World!"))); 

        stage.setTitle("Welcome to JavaFX!"); 
        stage.setScene(scene); 
        stage.sizeToScene(); 
        stage.show(); 
    }

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

Scene解析:

    

public class Sceneextends java.lang.Object
implements EventTarget

The JavaFX Scene class is the container for all content in a scene graph. The background of the scene is filled as specified by the fill property.

The application must specify the root Node for the scene graph by setting the root property. If a Group is used as the root, the contents of the scene graph will be clipped by the scene's width and height and changes to the scene's size (if user resizes the stage) will not alter the layout of the scene graph. If a resizable node (layout Region or Control is set as the root, then the root's size will track the scene's size, causing the contents to be relayed out as necessary.

The scene's size may be initialized by the application during construction. If no size is specified, the scene will automatically compute its initial size based on the preferred size of its content.

Scene objects must be constructed and modified on the JavaFX Application Thread.

Scene中包含各类UI事件的设置监听器的方法。如mouse,key,drag,touch,swipe,zoom,scroll等。

Example:


import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;

Group root = new Group();
Scene s = new Scene(root, 300, 300, Color.BLACK);

Rectangle r = new Rectangle(25,25,250,250);
r.setFill(Color.BLUE);

root.getChildren().add(r);

    
一个感觉:与android类库确实有点相似。

参考:http://docs.oracle.com/javafx/2/get_started/hello_world.htm


转载于:https://my.oschina.net/xby1993/blog/182535

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值