2016-11-26 68 views
0

我想通過從我構建的組合框中選擇值來分配標籤的字體(node)。組合框只有幾個選項,所以它們都應該可以安全地在這個應用程序中使用。從Combobox分配JavaFX標籤字體不起作用

一切工作正常,並從組合框中所有正確的字符串值被拉和分配到標籤。但是標籤中的字體不會改變,當我從標籤中輸出字體時,活動字體仍然是系統默認的字體。我有另一種方法只編輯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標籤字體(不過系統默認)

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

回答

0

如果指定,而不是姓氏字體名稱,你需要使用的Font的constuctor,因爲所有靜態方法預計字體家族:

@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(); 
} 
+0

這樣做了。我用'new Font(font,fontSize)'替換了'font.font(font)',它就像一個魅力一樣。謝謝。 – LazyBear