package fx;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
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.layout.Pane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
public class Exercise16_14 extends Application {
private ComboBox<String> fontName = new ComboBox<>(FXCollections.observableArrayList(Font.getFamilies())); //字体名
private ComboBox<Integer> fontSize; //字体大小
private CheckBox bold = new CheckBox("Bold"); //粗体
private CheckBox italic = new CheckBox("Italic"); //斜体
private Text text = new Text(10, 50, "Programming is fun"); //文本
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
ArrayList<Integer> size = new ArrayList<>(100);
for (int i = 0; i < 100; i++) //字体大小复选框添加值
size.add(i + 1);
fontSize = new ComboBox<>(FXCollections.observableArrayList(size));
fontName.setValue(fontName.getItems().get(0)); //组合框设置初值
fontSize.setValue(fontSize.getItems().get(15));
HBox topHBox = new HBox(10, new Label("Font Name"), fontName, new Label("Font Size"), fontSize);
topHBox.setAlignment(Pos.CENTER);
HBox bottomHBox = new HBox(10, bold, italic);
bottomHBox.setAlignment(Pos.CENTER);
fontName.setOnAction(event -> handle()); //注册动作事件
fontSize.setOnAction(event -> handle());
bold.setOnAction(event -> handle());
italic.setOnAction(event -> handle());
BorderPane pane = new BorderPane(new Pane(text));
pane.setTop(topHBox);
pane.setBottom(bottomHBox);
pane.getCenter().setStyle("-fx-pref-height: 200px;");
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise16_14");
primaryStage.show();
}
/** 处理动作事件 */
private void handle() {
ObservableList<String> fontNameItems = fontName.getItems(); //字体名列表
ObservableList<Integer> fontSizeItems = fontSize.getItems(); //字体大小列表
String name = fontNameItems.get(fontNameItems.indexOf(fontName.getValue())); //字体名
Integer size = fontSizeItems.get(fontSizeItems.indexOf(fontSize.getValue())); //字体大小
if (bold.isSelected() && italic.isSelected()) //粗斜体
text.setFont(Font.font(name, FontWeight.BOLD, FontPosture.ITALIC, size));
else if (bold.isSelected()) //粗体
text.setFont(Font.font(name, FontWeight.BOLD, FontPosture.REGULAR, size));
else if (italic.isSelected()) //斜体
text.setFont(Font.font(name, FontWeight.NORMAL, FontPosture.ITALIC, size));
else //非粗斜体
text.setFont(Font.font(name, FontWeight.NORMAL, FontPosture.REGULAR, size));
}
}