Java黑皮书16.14(选择一种字体)

Java黑皮书16.14(选择一种字体)

package sample;
import java.util.List;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

public class Main extends Application {
    public Label label = new Label("我是一行文本!");
    private CheckBox checkBox1 = new CheckBox("Bold");
    private CheckBox checkBox2 = new CheckBox("Italic");
    private ComboBox<String> comboBox1 = new ComboBox<>();
    private ComboBox<Integer> comboBox2 = new ComboBox<>();
    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(label);

        List<String> list = Font.getFamilies();
        comboBox1.getItems().addAll(list);
        comboBox1.setValue(list.get(0));

        for (int i = 1; i <= 100; i++) comboBox2.getItems().add(i);
        comboBox2.setValue(50);

        HBox hBox1 = new HBox(10);
        hBox1.getChildren().addAll(new Label("Font Name"), comboBox1, new Label("Font Size"), comboBox2);
        hBox1.setAlignment(Pos.CENTER);
        borderPane.setTop(hBox1);

        HBox hBox2 = new HBox(10);
        hBox2.getChildren().addAll(checkBox1, checkBox2);
        hBox2.setAlignment(Pos.CENTER);
        borderPane.setBottom(hBox2);

        Scene scene = new Scene(borderPane, 600, 300);
        primaryStage.setTitle("选择一种字体");
        primaryStage.setScene(scene);
        primaryStage.show();

        comboBox1.setOnAction(e -> setFont());
        comboBox2.setOnAction(e -> setFont());
        checkBox1.setOnAction(e -> setFont());
        checkBox2.setOnAction(e -> setFont());
    }

    private void setFont() {
        FontWeight fontWeight;
        if (checkBox1.isSelected()) fontWeight = FontWeight.BOLD;
        else fontWeight = FontWeight.NORMAL;

        FontPosture fontPosture;
        if(checkBox2.isSelected()) fontPosture = FontPosture.ITALIC;
        else fontPosture = FontPosture.REGULAR;

        label.setFont(Font.font(comboBox1.getValue(), fontWeight, fontPosture, comboBox2.getValue()));
    }
    public static void main(String[] args) { launch(args); }
}

运行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值