【问题标题】:Assigning JavaFX Label Font from Combobox not working从组合框中分配 JavaFX 标签字体不起作用
【发布时间】:2016-11-26 19:53:45
【问题描述】:

我正在尝试通过从我构建的组合框中选择值来分配标签的字体 (node)。组合框只有几个选项,因此所有选项都应该可以安全地在此应用中使用。

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

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

1) 选择字体并单击确定已更改)

2) 分配给标签(代码 sn-ps)

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]

【问题讨论】:

    标签: java list javafx combobox observablelist


    【解决方案1】:

    如果您指定字体名称而不是系列名称,则需要使用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();
    }
    

    【讨论】:

    • 做到了。我用new Font(font, fontSize) 替换了font.font(font),它就像一个魅力。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2020-02-28
    相关资源
    最近更新 更多