解決方案方法
我從Javafx How to display custom font in webview?更新所述樣品使用用CSS樣式JavaFX的控制自定義真實型字體來證明。
關鍵點是:
- 放置在相同的位置,你的應用程序類的字體,並確保在您的二元構建軟件包(如應用程序JAR文件)你的編譯系統的地方吧。
- 在應用使用它的樣式之前,在您的JavaFX代碼中加載代碼字體。
Font.loadFont(CustomFontApp.class.getResource("TRON.TTF").toExternalForm(), 10);
- 要在樣式類中使用自定義字體,請使用
-fx-font-family
css屬性並只引用字體的名稱(例如在此例中爲"TRON"
)。
- 創建並加載定義樣式類的樣式表。
- 將樣式類應用於您的控件。
其他信息
如果您使用的是Java 8中,您可能感興趣的Use web(Google) fonts in JavaFX。
樣本輸出使用自定義字體
示例代碼
的例子依賴於TRON.TTF字體,你可以從dafont下載。
CustomFontApp.java
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.*;
import javafx.stage.Stage;
// demonstrates the use of a custom font.
public class CustomFontApp extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage) {
stage.setTitle("TRON Synopsis");
// load the tron font.
Font.loadFont(
CustomFontApp.class.getResource("TRON.TTF").toExternalForm(),
10
);
Label title = new Label("TRON");
title.getStyleClass().add("title");
Label caption = new Label("A sci-fi flick set in an alternate reality.");
caption.getStyleClass().add("caption");
caption.setMaxWidth(220);
caption.setWrapText(true);
caption.setTextAlignment(TextAlignment.CENTER);
VBox layout = new VBox(10);
layout.setStyle("-fx-padding: 20px; -fx-background-color: silver");
layout.setAlignment(Pos.CENTER);
layout.getChildren().setAll(
title,
new ImageView(
new Image(
"http://ia.media-imdb.com/images/M/MV5BMTY5NjM2MjAwOV5BMl5BanBnXkFtZTYwMTgyMzA5.V1.SY317.jpg"
)
),
caption
);
// layout the scene.
final Scene scene = new Scene(layout);
scene.getStylesheets().add(getClass().getResource("custom-font-styles.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
}
定製字體styles.css的
/** file: custom-font-styles.css
* Place in same directory as CustomFontApp.java
*/
.title {
-fx-font-family: "TRON";
-fx-font-size: 20;
}
.caption {
-fx-font-family: "TRON";
-fx-font-size: 10;
}
在FXML用法
Font.loadFont(url, size)是一個靜態方法以兩個參數。我不認爲你可以調用字體。來自FXML的loadFont,如果可以的話,不會提供建議。相反,在加載需要字體的FXML或樣式表之前,請使用Java代碼加載字體(正如我在答案中所做的那樣)。
錯誤出現,說找不到符號:'loadFont'類'Font'。預計有三個標識符。 (我在fxml中導入字體爲'import javafx.scene.text.Font;') –
在答案中添加了關於FXML用法的章節。 – jewelsea
出現錯誤。在此處查看:https://docs.google.com/document/d/1GSQeo8CHQhMEU_nS-gl6yWL1qQF4T08kYwPa_OELer4/edit?usp=sharing –