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); }
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/94e181ae8959b4fc300b5aa20dc11af1.png)