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

本文介绍了JavaFX的基础概念,包括Application作为程序入口的作用,Stage作为顶级容器的功能,以及Scene作为内容承载者的特性。文章通过HelloWorld示例解析了创建舞台和场景的步骤,强调了根节点大小的自适应性。此外,还提到了JavaFX的生命周期、线程模型、Stage的展现模式以及Scene的内容填充和尺寸调整。

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


我的个人站点:http://www.xby1993.net

转载请注明地址。作者:浮沉雄鹰。

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舞台,state舞台是一个类似于Swing中的JWindow的顶级容器,代表一个窗口。它用于容纳场景Scene,场景Scene是一个类似于Swing的JFrame的容器。但是却是以树的形式组织的,每一个子组件就是它的一个节点。其根节点一般是Pane面板如以上的:StackPane.它是一个根节点容器。可以容纳子节点。各子节点挂载在其上。

主要实现步骤:State(即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

Description of Figure 1-1 follows


下面分析一下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

  5. 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.

HostServices getHostServices()

Gets the HostServices provider for this application.

Application.Parameters getParameters()

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.

void init()

The application initialization method.

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

Launch a standalone application.

static void launch(java.lang.String... args)

Launch a standalone application.

void notifyPreloader(Preloader.PreloaderNotification info)

Notifies the preloader with an application-generated notification.

abstract void start(Stage primaryStage)

The main entry point for all JavaFX applications.

void stop()

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);
    }
}

Stage的一些方法:

void    close()Closes this Stage.    
ReadOnlyBooleanProperty    fullScreenProperty()Specifies whether this Stage should be a full-screen, undecorated window.    
ObservableList<Image>    getIcons()Gets the icon images to be used in the window decorations and when minimized.    
double    getMaxHeight()Gets the value of the property maxHeight.    
double    getMaxWidth()Gets the value of the property maxWidth.    
double    getMinHeight()Gets the value of the property minHeight.    
double    getMinWidth()Gets the value of the property minWidth.    
Modality    getModality()Retrieves the modality attribute for this stage.    
Window    getOwner()Retrieves the owner Window for this stage, or null for an unowned stage.    
StageStyle    getStyle()Retrieves the style attribute for this stage.    
java.lang.String    getTitle()Gets the value of the property title.    
ReadOnlyBooleanProperty    iconifiedProperty()Defines whether the Stage is iconified or not.    
void    initModality(Modality modality)Specifies the modality for this stage.    
void    initOwner(Window owner)Specifies the owner Window for this stage, or null for a top-level, unowned stage.    
void    initStyle(StageStyle style)Specifies the style for this stage.    
boolean    isFullScreen()Gets the value of the property fullScreen.    
boolean    isIconified()Gets the value of the property iconified.    
boolean    isResizable()Gets the value of the property resizable.    
DoubleProperty    maxHeightProperty()Defines the maximum height of this Stage.    
DoubleProperty    maxWidthProperty()Defines the maximum width of this Stage.    
DoubleProperty    minHeightProperty()Defines the minimum height of this Stage.    
DoubleProperty    minWidthProperty()Defines the minimum width of this Stage.    
BooleanProperty    resizableProperty()Defines whether the Stage is resizable or not by the user.    
void    setFullScreen(boolean value)Sets the value of the property fullScreen.    
void    setIconified(boolean value)Sets the value of the property iconified.    
void    setMaxHeight(double value)Sets the value of the property maxHeight.    
void    setMaxWidth(double value)Sets the value of the property maxWidth.    
void    setMinHeight(double value)Sets the value of the property minHeight.    
void    setMinWidth(double value)Sets the value of the property minWidth.    
void    setResizable(boolean value)Sets the value of the property resizable.    
void    setScene(Scene value)Specify the scene to be used on this stage.    
void    setTitle(java.lang.String value)Sets the value of the property title.    
void    show()Attempts to show this Window by setting visibility to true    
void    showAndWait()Shows this stage and waits for it to be hidden (closed) before returning to the caller.    
StringProperty    titleProperty()Defines the title of the Stage.    
void    toBack()Send the Window to the background.    
void    toFront()Bring the Window to the foreground.


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值