Java - javafx入门(Java 8)

1. application的启动方式和生命周期

package top.onefine;

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
        System.out.println("Main" + Thread.currentThread());
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.show();
        primaryStage.setTitle("程序标题");
        System.out.println("运行程序!" + Thread.currentThread());  // Thread[JavaFX Application Thread,5,main]  ,UI线程
    }

    @Override
    public void init() throws Exception {
    
    
        super.init();
        System.out.println("打开程序!" + Thread.currentThread());  // Thread[JavaFX-Launcher,5,main]
    }

    @Override
    public void stop() throws Exception {
    
    
        super.stop();
        System.out.println("关闭程序!" + Thread.currentThread());  // Thread[JavaFX Application Thread,5,main]
    }
}
打开程序!Thread[JavaFX-Launcher,5,main]
运行程序!Thread[JavaFX Application Thread,5,main]
关闭程序!Thread[JavaFX Application Thread,5,main]
MainThread[main,5,main]

2. 初步认识stage窗口

package top.onefine;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.show();
        primaryStage.setTitle("条形码群读");
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
//        primaryStage.setIconified(true);  // 设置最小化
//        primaryStage.setMaximized(true);  // 设置最大化
//        primaryStage.close();  // 关闭,注意要在show()方法之后
//        primaryStage.setResizable(false);  // 设置不可改变窗口大小——固定窗口大小
//        primaryStage.setWidth(500);  // 设置默认宽高
//        primaryStage.setHeight(600);
//        primaryStage.setMaxWidth(600);  // 设置最大/最小宽高
//        primaryStage.setMinHeight(400);
//        primaryStage.setMaxHeight(700);
//        primaryStage.setMinHeight(500);
//        primaryStage.getMaxHeight();  // 获取宽高,注意要在show()方法后获取
//        primaryStage.getMaxWidth();
//        primaryStage.getMinHeight();
//        primaryStage.getMinWidth();

        // 设置高度变化监听,宽度同理
//        primaryStage.heightProperty().addListener(new ChangeListener<Number>() {
    
    
//            @Override
//            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
    
    
//                System.out.println(primaryStage.getHeight());
//            }
//        });

        // 设置全屏
//        primaryStage.setScene(new Scene(new Group()));
//        primaryStage.setFullScreen(true);

//        primaryStage.setOpacity(0.6);  // 设置透明度,取值为0~1。1不透明,0完全透明(看不到)
//        primaryStage.setAlwaysOnTop(true);  // 设置窗口置顶

        // 设置显示坐标
//        primaryStage.setX(0);
//        primaryStage.setY(0);

        // x/y轴监听器,x为例
//        primaryStage.xProperty().addListener(new ChangeListener<Number>() {
    
    
//            @Override
//            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
    
    
//                System.out.println(primaryStage.getX());  // 打印窗口x坐标
//            }
//        });

    }

}

3. 进一步认识stage窗口

package top.onefine;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        // 初始化窗口类型
        primaryStage.setTitle("类型");
//        primaryStage.initStyle(StageStyle.DECORATED);  // 白色背景,带装饰
//        primaryStage.initStyle(StageStyle.TRANSPARENT);  // 透明背景,不带装饰
//        primaryStage.initStyle(StageStyle.UNDECORATED);  // 白色背景,不带装饰
//        primaryStage.initStyle(StageStyle.UNIFIED);
//        primaryStage.initStyle(StageStyle.UTILITY);
        primaryStage.show();

//        Platform.exit();  // 关闭程序

    }

}

4. 模态

package top.onefine;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("类型");
        primaryStage.show();

        Stage s0 = new Stage();
        s0.setTitle("参照0");
        s0.show();

        // 方式一
//        Stage s1 = new Stage();
//        s1.setTitle("参照1");
//        s1.initModality(Modality.APPLICATION_MODAL);  // 模态框,注意主窗口不能设置模态框
//        s1.show();


        // 方式二
        Stage s2 = new Stage();
        s2.setTitle("参照2");
        s2.initOwner(s0);  // 窗口s2属于窗口s0,默认 其他窗口都属于primaryStage
        s2.initModality(Modality.APPLICATION_MODAL);  // 模态框,注意主窗口不能设置模态框
        s2.show();

        Stage s3 = new Stage();
        s3.setTitle("参照3");
        s3.show();

    }

}

5. platform类的使用

package top.onefine;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("Platform对象");
        primaryStage.show();

        Platform.runLater(new Runnable() {
    
      // 队列而非多线程
            @Override
            public void run() {
    
    
                System.out.println("run: " + Thread.currentThread());
            }
        });

        System.out.println("start: " + Thread.currentThread());

        /* 打印结果
        start: Thread[JavaFX Application Thread,5,main]
        run: Thread[JavaFX Application Thread,5,main]
         */
    }

}
package top.onefine;

import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("Platform对象");
        primaryStage.show();
//        Platform.setImplicitExit(false);  // 后台
//        Platform.exit();  // 关闭程序

        boolean bo = Platform.isSupported(ConditionalFeature.SCENE3D);// 检测是否支持3d
        System.out.println(bo ? "支持3d" : "不支持3d");
    }

}

6. screen类

package top.onefine;

import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
//        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        Screen screen = Screen.getPrimary();
        Rectangle2D rectangle2D_1 = screen.getBounds();  // 获得全部的屏幕宽高,包括用户不可见部分
        System.out.println("左上角x: " + rectangle2D_1.getMinX() + ", 左上角y: " + rectangle2D_1.getMinY());
        System.out.println("右下角x: " + rectangle2D_1.getMaxX() + ", 右下角y: " + rectangle2D_1.getMaxY());
        System.out.println("宽: " + rectangle2D_1.getWidth() + ", 高: " + rectangle2D_1.getHeight());

        Rectangle2D rectangle2D_2 = screen.getVisualBounds();// 获得用户可见部分的宽高
        System.out.println("左上角x: " + rectangle2D_2.getMinX() + ", 左上角y: " + rectangle2D_2.getMinY());
        System.out.println("右下角x: " + rectangle2D_2.getMaxX() + ", 右下角y: " + rectangle2D_2.getMaxY());
        System.out.println("宽: " + rectangle2D_2.getWidth() + ", 高: " + rectangle2D_2.getHeight());

        double dpi = screen.getDpi();// 获取屏幕dpi
        System.out.println(dpi);

        Platform.exit();
    }

}

结果:

右下角x: 1920.0, 右下角y: 1080.0: 1920.0,: 1080.0
左上角x: 0.0, 左上角y: 0.0
右下角x: 1920.0, 右下角y: 1042.0: 1920.0,: 1042.0
157.0

7. screen类补充

在这里插入图片描述

package top.onefine;

import com.sun.org.apache.xml.internal.security.Init;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

import java.net.URL;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");


        Button button = new Button("按钮");  // button属于node
        button.setPrefWidth(100);
        button.setPrefHeight(50);
//        button.setCursor(Cursor.WAIT);  // 设置Button中的图标
        URL resource = getClass().getClassLoader().getResource("camera.png");  // 加载类路径下的资源
        if (resource == null)
            throw new RuntimeException("文件找不到异常");

        button.setCursor(Cursor.cursor(resource.toString()));  // 设置图标为自定义
//        System.out.println(resource.toString());  // file:/D:/jetbrains/project/java/barCodeScanner/target/classes/camera.png
//        System.out.println(resource.getPath());  // /D:/jetbrains/project/java/barCodeScanner/target/classes/camera.png
//        System.out.println(resource.toExternalForm());  // file:/D:/jetbrains/project/java/barCodeScanner/target/classes/camera.png
        Group group = new Group();  // 无布局,只是容器
        group.getChildren().add(button);

        // 点击按钮弹出网页
        button.addEventFilter(MouseEvent.ANY, event -> {
    
    
            if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
    
    
                HostServices hostServices = getHostServices();
                hostServices.showDocument("www.onefine.top");
            }
        });


        Scene scene = new Scene(group);  // 场景
        scene.setCursor(Cursor.MOVE);  // 设置场景中的图标

        primaryStage.setScene(scene);


        primaryStage.show();
    }

}

8. Group容器的使用

package top.onefine;

import com.sun.org.apache.xml.internal.security.Init;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

import java.net.URL;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");

        Button b1 = new Button("按钮1");  // button属于node
        Button b2 = new Button("按钮2");
        Button b3 = new Button("按钮3");

        b1.setLayoutX(0);
        b2.setLayoutX(150);
        b3.setLayoutX(300);

        Group group = new Group();  // 容器
//        group.getChildren().add(b1);
//        group.getChildren().add(b2);
//        group.getChildren().add(b3);
        group.getChildren().addAll(b1, b2, b3);  // 添加b1, b2, b3

//        group.getChildren().remove(0);  // 移除b1
//        group.getChildren().clear(); // 全部清除
//        group.setAutoSizeChildren(false);  // 关闭自动设置子组件大小,子组件大小宽高就为0

//        group.setOpacity(0.5);  // 设置容器透明度,会影响所有子组件

//        boolean bo = group.contains(0, 0);// 判断容器的坐标(0, 0)位置是否有子组件
//        System.out.println(bo ? "有" : "没有");  // 注意:只能检测左上角位置

//        Object[] objects = group.getChildren().toArray();
//
//        for (Object object : objects) {
    
    
//            Button button = (Button) object;  // 修改的是对象引用
//            button.setPrefWidth(100);
//            button.setPrefHeight(50);
//        }

        // group绑定事件
        group.getChildren().addListener(new ListChangeListener<Node>() {
    
    
            @Override
            public void onChanged(Change<? extends Node> c) {
    
    
                System.out.println("当前子组件数量: " + c.getList().size());
            }
        });

        // b1添加单击事件
        b1.setOnAction(new EventHandler<ActionEvent>() {
    
    
            @Override
            public void handle(ActionEvent event) {
    
    
                Button button = new Button("新的button");
                button.setLayoutX(Math.random() * 1000);
                button.setLayoutY(Math.random() * 1000);
                group.getChildren().add(button);
            }
        });

        Scene scene = new Scene(group);  // 场景

        primaryStage.setScene(scene);


        primaryStage.show();
    }

}

9. Button按钮以及简单介绍设置背景颜色和外边框等问题

package top.onefine;

import com.sun.org.apache.xml.internal.security.Init;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.omg.CORBA.PRIVATE_MEMBER;

import java.net.URL;

public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");

        Button b1 = new Button("按钮1");  // button属于node
        Button b2 = new Button();
        b2.setText("按钮2");
        b2.setPrefWidth(100);  // 宽度
        b2.setPrefHeight(50);  // 高度
        b2.setFont(Font.font("sans-serif", 20));  // 设置字体及大小
        b2.setTextFill(Paint.valueOf("#FFFFFF"));  // 设置字体颜色

        // 设置颜色
        BackgroundFill bgf = new BackgroundFill(Paint.valueOf("#EE4000"), new CornerRadii(20), new Insets(10));  // 颜色, 圆角, 外边距new Insets(10, 10, 10, 10)
        Background bg = new Background(bgf);
        b2.setBackground(bg);

        BorderStroke bos = new BorderStroke(Paint.valueOf("#FFC125"), BorderStrokeStyle.SOLID, new CornerRadii(20), new BorderWidths(10));  // 颜色, 线条类型, 圆角, 粗细
        // 注:#FFC125代表颜色	RGB
        //		#FFC12500代表透明度,00完全透明,FF完全不透明	RGBA
        Border bo = new Border(bos);
        b2.setBorder(bo);

        Button b3 = new Button("按钮3");
		
		b3.setStyle(
                "-fx-background-color: #00FF00;" +  // 设置颜色
                "-fx-background-radius: 20;" +  // 设置圆角
                "-fx-text-fill: #FF0000;"  // 文字颜色
        );  // css方式设置颜色,圆角...

        b1.setLayoutX(0);
        b2.setLayoutX(150);
        b3.setLayoutX(300);
		
		// 绑定单击事件
        b1.setOnAction(new EventHandler<ActionEvent>() {
    
    
            @Override
            public void handle(ActionEvent event) {
    
    
                System.out.println("点击了按钮!");
                Button button = (Button) event.getSource();// 获取事件源
                button.setText("刚刚点击了");
            }
        });

        Group group = new Group();  // 容器
        group.getChildren().addAll(b1, b2, b3);  // 添加b1, b2, b3

        Scene scene = new Scene(group);  // 场景

        primaryStage.setScene(scene);


        primaryStage.show();
    }

}

在这里插入图片描述

参考:
Java平台标准版(Java SE)8:https://docs.oracle.com/javase/8/javase-clienttechnologies.htm
JavaFX CSS参考指南:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html

10. 双击事件和检测键盘按键

package top.onefine;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;


public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");

        Button b1 = new Button("按钮1");  // button属于node
        Button b2 = new Button("按钮2");
        Button b3 = new Button("按钮3");

        b1.setLayoutX(0);
        b2.setLayoutX(150);
        b3.setLayoutX(300);

        // 绑定单击事件
//        b1.setOnAction(new EventHandler<ActionEvent>() {
    
    
//            @Override
//            public void handle(ActionEvent event) {
    
    
                System.out.println("点击了按钮!");
//                Button button = (Button) event.getSource();// 获取事件源
//                button.setText("刚刚单击了");
//            }
//        });

        // 绑定双击事件
        b1.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
    
      // MouseEvent.MOUSE_CLICKED 鼠标点击  单击  单击
            @Override
            public void handle(MouseEvent event) {
    
    
//                System.out.println("鼠标点击了按钮!");
                // 点击两次时...双击...
//                if (event.getClickCount() == 2) {
    
    
//                    Button button = (Button) event.getSource();// 获取事件源
//                    button.setText("刚刚双击了");
//                }

                // 单击一次,获取鼠标点击左右中键名称
                if (event.getClickCount() == 1) {
    
    
                    Button button = (Button) event.getSource();// 获取事件源
                    button.setText("刚刚" + event.getButton().name() + "单击了");
                }

                // 鼠标左键双击
                if (event.getClickCount() == 2 && event.getButton().name().equals(MouseButton.PRIMARY.name())/*("PRIMARY")*/) {
    
    
                    Button button = (Button) event.getSource();// 获取事件源
                    button.setText("鼠标左键双击了");
                }
            }
        });

        // 绑定键盘按键按下事件监听
        b2.setOnKeyPressed(new EventHandler<KeyEvent>() {
    
    
            @Override
            public void handle(KeyEvent event) {
    
    
                Button button = (Button) event.getSource();
                button.setText("键盘按键" + event.getCode().getName() + "按下了");
            }
        });

        // 绑定键盘按键松开事件监听
        b2.setOnKeyReleased(new EventHandler<KeyEvent>() {
    
    
            @Override
            public void handle(KeyEvent event) {
    
    
                Button button = (Button) event.getSource();
                button.setText("键盘按键" + event.getCode().getName() + "松开了");

                if (event.getCode().getName().equals(KeyCode.ESCAPE.getName()))
                    primaryStage.close();  // ESC关闭程序
            }

        });

        Group group = new Group();  // 容器
        group.getChildren().addAll(b1, b2, b3);  // 添加b1, b2, b3

        Scene scene = new Scene(group);  // 场景

        primaryStage.setScene(scene);


        primaryStage.show();
    }

}

11. 设置快捷键

package top.onefine;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.*;
import javafx.stage.Stage;


public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");

        Button b1 = new Button("按钮1");  // button属于node
        Button b2 = new Button("按钮2");
        Button b3 = new Button("按钮3");

        b1.setLayoutX(0);
        b2.setLayoutX(150);
        b3.setLayoutX(300);

        // 绑定单击事件
        b1.setOnAction(new EventHandler<ActionEvent>() {
    
    
            @Override
            public void handle(ActionEvent event) {
    
    
                Button button = (Button) event.getSource();// 获取事件源
//                button.setText("刚刚单击了");
                System.out.println("刚刚单击了");
            }
        });


        Group group = new Group();  // 容器
        group.getChildren().addAll(b1, b2, b3);  // 添加b1, b2, b3

        Scene scene = new Scene(group);  // 场景

        // 快捷键,使用方式一
        KeyCombination kc1 = new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN, KeyCombination.CONTROL_DOWN);  // CTRL + ALT + C
        Mnemonic mnemonic = new Mnemonic(b1, kc1);  // 快捷键绑定到b1,b1的事件监听等...会触发
        scene.addMnemonic(mnemonic);  // 将快捷键绑定添加到场景中

        // 快捷键,使用方式二
        KeyCombination kc2 = new KeyCharacterCombination("O", KeyCombination.ALT_DOWN);// ALT + O
        Mnemonic mnemonic2 = new Mnemonic(b1, kc2);
        scene.addMnemonic(mnemonic2);

        // 快捷键,使用方式三,常用
        KeyCombination kc3 = new KeyCodeCombination(KeyCode.Y, KeyCombination.SHORTCUT_DOWN);  // WINDOWS: CTRL + Y MAC: MATE + Y
        scene.getAccelerators().put(kc3, new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("快捷键3");
                // 注意,并不是多线程,而是在UI线程中继续执行
//                System.out.println(Thread.currentThread());  // Thread[JavaFX Application Thread,5,main]
                b1.fire();  // 调用b1.setOnAction中的handle方法
            }
        });


        primaryStage.setScene(scene);

        primaryStage.show();
    }

}

12. 输入框,密码框,标签

package top.onefine;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.*;
import javafx.scene.text.Font;
import javafx.stage.Stage;


public class Main extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.getIcons().add(new Image("Icon.png"));  // 设置图标
        primaryStage.setTitle("demo");

        // 标签
        Label label_id = new Label("账号");
        Label label_psd = new Label("密码");
        label_id.setLayoutX(5);
        label_id.setLayoutY(50);
        label_psd.setLayoutX(5);
        label_psd.setLayoutY(100);


        // 输入框
        TextField textField = new TextField();
        textField.setText("输入框内默认文字");
        textField.setLayoutX(40);
        textField.setLayoutY(50);
//        textField.setPrefWidth(400);  // 宽
//        textField.setPrefHeight(36);  // 高
//        textField.setFont(Font.font(40));  // 字体大小
//        textField.setStyle();  // css
        textField.setTooltip(new Tooltip("输入框是输入文字的"));  // 输入框旁侧的提示文字
        textField.setPromptText("请输入7个文字以下");  // 输入框内提示文字
        textField.setText(null);
        textField.setFocusTraversable(false);  // 移除此焦点

        // 输入框监听
        textField.textProperty().addListener(new ChangeListener<String>() {
    
    
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
    
    
//                System.out.println("observable: " + observable);
//                System.out.println("oldValue: " + oldValue);
//                System.out.println("newValue: " + newValue);
                if (newValue.length() > 7)
//                    textField.setText(oldValue.toString());
                    textField.setText(newValue.toString().substring(0, 7));
            }
        });

        // 输入框内选中文本的监听
        textField.selectedTextProperty().addListener(new ChangeListener<String>() {
    
    
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
    
    
//                System.out.println("observable: " + observable);
//                System.out.println("oldValue: " + oldValue);
//                System.out.println("newValue: " + newValue);
                if (newValue.length() != 0)
                    System.out.println("选中的文字为: " + newValue);
            }
        });

        // 输入框回车事件绑定
//        textField.setOnAction(new EventHandler<ActionEvent>() {
    
    
//            @Override
//            public void handle(ActionEvent event) {
    
    
//                System.out.println("键盘按键Enter!");
//            }
//        });
        // 输入框鼠标单击事件绑定监听
        textField.setOnMouseClicked(new EventHandler<MouseEvent>() {
    
    
            @Override
            public void handle(MouseEvent event) {
    
    
                System.out.println("鼠标单击了文本框");
            }
        });

        // 标签绑定单击事件监听
        label_id.setOnMouseClicked(new EventHandler<MouseEvent>() {
    
    
            @Override
            public void handle(MouseEvent event) {
    
    
//                System.out.println("点击了标签");
                if (event.getButton().name().equals(MouseButton.PRIMARY.name()))
                    System.out.println("鼠标左键点击了标签");
            }
        });

        // 密码输入框
        PasswordField passwordField = new PasswordField();
        passwordField.setLayoutX(40);
        passwordField.setLayoutY(100);

        Group group = new Group();  // 容器
        group.getChildren().addAll(textField, passwordField, label_id, label_psd);

        Scene scene = new Scene(group);  // 场景

        primaryStage.setScene(scene);

        primaryStage.show();
    }

}

13. ListView组件,简单介绍和基本使用方式

package top.onefine.demo.javafx;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.net.URL;

public class TestDemo extends Application {
    
    
    public static void main(String[] args) {
    
    
        Application.launch(args);
//        System.out.println(System.getProperty("java.version"));
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        primaryStage.setTitle("demo");
        primaryStage.setWidth(1600);
        primaryStage.setHeight(900);

        Button button = new Button("按钮");

        // 创建可观察列表
        ObservableList<String> observableList = FXCollections.observableArrayList();
        for (int i = 0; i < 30; i++) {
    
    
            observableList.add("data - " + i + " - test");
        }

        // ListView
        ListView<String> listView = new ListView<>(observableList);
        listView.getItems().add("observableList");  // 添加item
        listView.setPlaceholder(new Label("没有数据!"));  // 设置占位符
//        listView.setOrientation(Orientation.HORIZONTAL);  // 设置方向为垂直,默认是垂直
        listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);  // 设置可以多选,默认单选
//        listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  // 单选
//        listView.getSelectionModel().select(0);  // 选中数据

//        // 列表单击事件-数据
//        listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
    
    
//            @Override
//            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
    
    
//                System.out.println(newValue);
//            }
//        });
//        // 列表单击事件-索引
//        listView.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
    
    
//            @Override
//            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
    
    
//                System.out.println(newValue.intValue());
//            }
//        });
        // 滚动事件
        // listView.scrollTo()方法才有效,在button的监听中
//        listView.setOnScrollTo(new EventHandler<ScrollToEvent<Integer>>() {
    
    
//            @Override
//            public void handle(ScrollToEvent<Integer> event) {
    
    
//                System.out.println(event.getScrollTarget());  // 打印滚动位置索引
//            }
//        });

        // 设置列表为可编辑状态
        listView.setEditable(true);  // 双击编辑,回车保存
        listView.setCellFactory(TextFieldListCell.forListView());  // 设置工厂方法

        // 设置宽高
        listView.setPrefWidth(300);
        listView.setPrefHeight(500);

		// 设置单元格尺寸
        listView.setFixedCellSize(50);


		// 设置焦点在单元格上 注意位置
        listView.getFocusModel().focus(2);
        // 焦点信息
        System.out.println(listView.getFocusModel().getFocusedItem());

		// 焦点单元格值监听
        listView.getFocusModel().focusedItemProperty().addListener(new ChangeListener<String>() {
    
    
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
    
    
                System.out.println("new value: " + newValue);
            }
        });

        AnchorPane an = new AnchorPane();
        AnchorPane.setTopAnchor(listView, 100.0);  // 上锚点,指定子组件距100.0
        AnchorPane.setLeftAnchor(listView, 100.0);
        AnchorPane.setTopAnchor(button, 660.0);
        AnchorPane.setLeftAnchor(button, 160.0);
        an.getChildren().addAll(button, listView);
        Scene scene = new Scene(an);
        primaryStage.setScene(scene);
        primaryStage.show();

//        listView.requestFocus();  // 获得焦点  注意放置位置
//        button.setFocusTraversable(false);  // 阻止获得焦点,默认true

        // 对按钮进行监听
        button.setOnAction(new EventHandler<ActionEvent>() {
    
    
            @Override
            public void handle(ActionEvent event) {
    
    
//                observableList.add("one fine");  // 往列表添加数据
//                observableList.set(0, "update");  // 修改列表中数据
//                if (observableList.size() > 0)
//                    observableList.remove(0);  // 移除列表中的数据
                // 选中一个数据并获得焦点
//                listView.getSelectionModel().select(0);
//                listView.getSelectionModel().select("data - 28 - test");  // 直接根据名称选中
                listView.scrollTo(28);  // 滚动条滚动28位
//                listView.scrollTo("data - 28 - test");  // 滚动到指定位置
//                listView.requestFocus();  // 获得焦点
                // 获取选中的数据
//                System.out.println(listView.getSelectionModel().getSelectedIndex());  // 打印选中数据的索引(最后一个)
//                System.out.println(listView.getSelectionModel().getSelectedItem());  // 选中的数据(最后一个)
//                System.out.println(listView.getSelectionModel().getSelectedIndices());  // 选中数据的索引(多个)
//                System.out.println(listView.getSelectionModel().getSelectedItems());  // 选中的数据(多个)
                listView.getSelectionModel().getSelectedItems().forEach(System.out::println);  // 另一种打印方式
                // 多选的其他操作
//                listView.getSelectionModel().clearAndSelect(1);  // 清除选中并选中指定新的,如这里是1
//                listView.getSelectionModel().clearSelection();  // 清除全部选中
//                listView.getSelectionModel().clearSelection(2);  // 清除第2个选中
//                listView.getSelectionModel().selectAll();  // 全部选中
//                listView.getSelectionModel().selectIndices(2, 4);  // 选中部分

            }
        });
    }
}

14. 显示转换对象类型的数据,四种可编辑样式

https://www.bilibili.com/video/BV1Bb411y7ne

14:32 stop 待完善

猜你喜欢

转载自blog.csdn.net/jiduochou963/article/details/105084279