从Combobox分配JavaFX标签字体不起作用

时间:2016-11-26 19:53:46

标签: java list javafx combobox observablelist

我试图通过从我构造的组合框中选择值来指定标签的字体(node)。组合框只有几个选项,所以在这个应用程序中使用它们都应该是安全的。

一切正常,组合框中的所有正确字符串值都被拉出并分配给标签。但标签中的字体不会改变,当我从标签输出字体时,活动字体仍然是系统默认值。我有另一种方法只编辑fontSize,并且工作正常。所以它必须是实际的字符串值无效。但是没有抛出任何错误,并且组合框列表名称来自系统上安装的字体。

用例和代码如下。我错过了什么?

1)选择字体,然后单击确定更改

enter image description here

2)分配给标签(代码段)

String font = String.valueOf(combobox_font.getValue());

label.setFont(Font.font(font));

注意:为了我的程序,我试图分别指定字体类型和大小,但我也尝试使用字体大小分配值,没有运气。

label.setFont(Font.font(font, fontSize)); ///fontSize is a double value gotten from teh textfled above

3)Outbut Label Font (静止系统默认)

   Font[name=System Regular, family=System, style=Regular, size=12.0]

1 个答案:

答案 0 :(得分:0)

如果要指定字体名称而不是系列名称,则需要使用Font的构造函数,因为所有静态方法都需要字体系列:

@Override
public void start(Stage primaryStage) {
    ComboBox<String> fontChoice = new ComboBox<>(FXCollections.observableList(Font.getFontNames()));

    Spinner<Integer> spinner = new Spinner<>(1, 40, 12);

    Text text = new Text("Hello World!");

    text.fontProperty().bind(Bindings.createObjectBinding(() -> new Font(fontChoice.getValue(), spinner.getValue()), spinner.valueProperty(), fontChoice.valueProperty()));

    HBox hBox = new HBox(fontChoice, spinner);
    StackPane.setAlignment(hBox, Pos.TOP_CENTER);

    StackPane root = new StackPane(hBox, text);

    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}

要使用静态方法,请使用系列名称:

@Override
public void start(Stage primaryStage) {
    ComboBox<String> familyChoice = new ComboBox<>(FXCollections.observableList(Font.getFamilies()));

    Spinner<Integer> spinner = new Spinner<>(1, 40, 12);

    Text text = new Text("Hello World!");
    text.fontProperty().bind(Bindings.createObjectBinding(() -> Font.font(familyChoice.getValue(), spinner.getValue()), spinner.valueProperty(), familyChoice.valueProperty()));

    HBox hBox = new HBox(familyChoice, spinner);
    StackPane.setAlignment(hBox, Pos.TOP_CENTER);

    StackPane root = new StackPane(hBox, text);

    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}