下面列出了怎么用javafx.scene.text.Font的API类实例代码及写法,或者点击链接到github查看源代码。
private void drawText() {
final double CENTER_X = 0.5 * width;
final double CENTER_Y = 0.5 * height;
final int NO_OF_SECTORS = getNoOfSectors();
Font font = Fonts.latoRegular(0.035 * size);
double radAngle = RadarChartMode.SECTOR == getMode() ? Math.toRadians(180 + angleStep * 0.5) : Math.toRadians(180);
double radAngleStep = Math.toRadians(angleStep);
textGroup.getChildren().clear();
for (int i = 0 ; i < NO_OF_SECTORS ; i++) {
double r = size * 0.48;
double x = CENTER_X - size * 0.015 + (-Math.sin(radAngle) * r);
double y = CENTER_Y + (+Math.cos(radAngle) * r);
Text text = new Text(data.get(i).getName());
text.setFont(font);
text.setFill(data.get(i).getTextColor());
text.setTextOrigin(VPos.CENTER);
text.setTextAlignment(TextAlignment.CENTER);
text.setRotate(Math.toDegrees(radAngle) - 180);
text.setX(x);
text.setY(y);
textGroup.getChildren().add(text);
radAngle += radAngleStep;
}
}
@Override
public Pane getParamPane(final PluginParametersNode node) {
if (node.getChildren().isEmpty()) {
return null;
}
if (currentChild == -1) {
titleLabel = new Label(title);
titleLabel.setFont(Font.font(Font.getDefault().getFamily(), FontPosture.ITALIC, fontSize));
final Separator separator = new Separator();
separator.setStyle("-fx-background-color:#444444;");
HBox separatorBox = new HBox(separator);
HBox.setHgrow(separator, Priority.ALWAYS);
HBox.setMargin(separator, new Insets(PADDING, 0, 0, 0));
return new VBox(titleLabel, separatorBox);
}
final Pane paramPane = super.getParamPane(node);
final SimpleDoubleProperty updated = new SimpleDoubleProperty();
updated.bind(Bindings.max(maxParamWidth, paramPane.widthProperty()));
maxParamWidth = updated;
if (titleLabel != null) {
titleLabel.prefWidthProperty().bind(maxParamWidth);
}
return paramPane;
}
private void drawGraphics() {
graphics.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
graphics.drawImage(image, 0, 0);
if (annotations.size() > 0) {
for (int i = 0; i < annotations.size(); i++) {
Annotation annotationFX = annotations.get(i);
double x = annotationFX.getX();
double y = annotationFX.getY();
graphics.setFill(ANNOTATION_COLOR);
graphics.fillRect(x, y, annotationFX.getWidth(), annotationFX.getHeight());
graphics.setFill(Color.RED);
graphics.fillArc(x - 25, y - 25, 50, 50, 270, 90, ArcType.ROUND);
graphics.setFill(Color.WHITE);
graphics.setFont(Font.font(null, FontWeight.EXTRA_BOLD, 14));
if (i > 8) {
graphics.fillText(Integer.toString(i + 1), x + 5, y + 15);
} else {
graphics.fillText(Integer.toString(i + 1), x + 5, y + 15);
}
}
}
}
@Override
public void start(Stage stage) {
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewSample");
box.getChildren().addAll(list, label);
VBox.setVgrow(list, Priority.ALWAYS);
label.setLayoutX(10);
label.setLayoutY(115);
label.setFont(Font.font("Verdana", 20));
list.setItems(data);
list.setCellFactory((ListView<String> l) -> new ColorRectCell());
list.getSelectionModel().selectedItemProperty()
.addListener((ObservableValue<? extends String> ov, String old_val, String new_val) -> {
label.setText(new_val);
label.setTextFill(Color.web(new_val));
});
stage.show();
}
default void updatePathLabels() {
final Axes model = getModel();
final Font font = new Font("cmr10", model.getLabelsSize()); //NON-NLS
final PlottingStyle labelsDisplay = model.getLabelsDisplayed();
final PlottingStyle ticksDisplay = model.getTicksDisplayed();
final TicksStyle ticksStyle = model.getTicksStyle();
// This fake text is used to compute widths and heights and other font metrics of a current text.
final Text fooText = new Text("foo"); //NON-NLS
fooText.setFont(font);
if(labelsDisplay.isX()) {
updatePathLabelsX(ticksDisplay, ticksStyle, fooText);
}
if(labelsDisplay.isY()) {
updatePathLabelsY(ticksDisplay, ticksStyle, fooText);
}
}
/** Convert model font into JFX font
* @param font {@link WidgetFont}
* @return {@link Font}
*/
public static Font convert(final WidgetFont font)
{
return fontCache.computeIfAbsent(font, f ->
{
final double calibrated = f.getSize() * font_calibration;
switch (f.getStyle())
{
case BOLD:
return Font.font(f.getFamily(), FontWeight.BOLD, FontPosture.REGULAR, calibrated);
case ITALIC:
return Font.font(f.getFamily(), FontWeight.NORMAL, FontPosture.ITALIC, calibrated);
case BOLD_ITALIC:
return Font.font(f.getFamily(), FontWeight.BOLD, FontPosture.ITALIC, calibrated);
default:
return Font.font(f.getFamily(), FontWeight.NORMAL, FontPosture.REGULAR, calibrated);
}
});
}
private void drawDataPoints() {
ctx.setTextAlign(TextAlignment.CENTER);
ctx.setTextBaseline(VPos.CENTER);
ctx.setFont(Font.font(size * 0.0175));
for (int i = 0 ; i < points.size() ; i++) {
DataPoint point = points.get(i);
ctx.setFill(Color.rgb(255, 255, 255, 0.5));
ctx.fillOval(point.getX() - 8, point.getY() - 8, 16, 16);
//ctx.setStroke(getUseColorMapping() ? getColorForValue(point.getValue(), 1) : getColorForValue(point.getValue(), isDiscreteColors()));
ctx.setStroke(Color.BLACK);
ctx.strokeOval(point.getX() - 8, point.getY() - 8, 16, 16);
ctx.setFill(Color.BLACK);
ctx.fillText(Long.toString(Math.round(point.getValue())), point.getX(), point.getY(), 16);
}
}
public static Node createIconContent() {
Text text = new Text("abc");
text.setTextOrigin(VPos.TOP);
text.setLayoutX(10);
text.setLayoutY(11);
text.setFill(Color.BLACK);
text.setOpacity(0.5);
text.setFont(Font.font(null, FontWeight.BOLD, 20));
text.setStyle("-fx-font-size: 20px;");
Text text2 = new Text("abc");
text2.setTextOrigin(VPos.TOP);
text2.setLayoutX(28);
text2.setLayoutY(51);
text2.setFill(Color.BLACK);
text2.setFont(javafx.scene.text.Font.font(null, FontWeight.BOLD, 20));
text2.setStyle("-fx-font-size: 20px;");
Line line = new Line(30, 32, 45, 57);
line.setStroke(Color.DARKMAGENTA);
return new javafx.scene.Group(text, line, text2);
}
private HBox getHBox(final String TEXT, final Gauge GAUGE) {
Label label = new Label(TEXT);
label.setPrefWidth(150);
label.setFont(Font.font(26));
label.setTextFill(MaterialDesign.GREY_800.get());
label.setAlignment(Pos.CENTER_LEFT);
label.setPadding(new Insets(0, 10, 0, 0));
GAUGE.setBarBackgroundColor(Color.rgb(232, 231, 223));
GAUGE.setAnimated(true);
GAUGE.setAnimationDuration(1000);
HBox hBox = new HBox(label, GAUGE);
hBox.setSpacing(20);
hBox.setAlignment(Pos.CENTER_LEFT);
return hBox;
}
private void populateDigits() {
for (int i = 0; i < digits.length; i++) {
digits[i] = new Digit();
Text text = new Text(i + "");
text.setFont(Font.font(144));
text.setFill(Color.BLACK);
Image snapshot = text.snapshot(null, null);
for (int y = 0; y < snapshot.getHeight(); y++) {
for (int x = 0; x < snapshot.getWidth(); x++) {
if (snapshot.getPixelReader().getColor(x, y).equals(Color.BLACK)) {
digits[i].positions.add(new Point2D(x, y));
}
}
}
if (digits[i].positions.size() > maxParticles) {
maxParticles = digits[i].positions.size();
}
}
}
private void draw() {
Canvas canvas = new Canvas(scale, scale);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.TRANSPARENT);
gc.fillRect(0, 0, scale, scale);
gc.setFill(background);
gc.fillRect(0, 0, scale, scale);
gc.setFill(Color.WHITE);
gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.setFont(Font.font("Tahoma", FontWeight.SEMI_BOLD, scale * 0.6));
gc.fillText(String.valueOf(character), Math.round(scale / 2.0), Math.round(scale / 2.0));
Platform.runLater(() -> canvas.snapshot(null, this));
}
public static Dialog showFontPicker(BindableValue<Font> fontProperty) {
ComboBox<String> fontNames = new ComboBox<>(
observableList(Font.getFontNames().stream().distinct().collect(toList())));
fontNames.getSelectionModel().select(fontProperty.getValue().getName());
ComboBox<Double> fontSizes = new ComboBox<>(
observableList(rangeClosed(6, 42)
.asDoubleStream().boxed()
.collect(toList()))
);
fontSizes.getSelectionModel().select(fontProperty.getValue().getSize());
EventHandler<ActionEvent> eventHandler = (event) ->
fontProperty.setValue(new Font(fontNames.getValue(), fontSizes.getValue()));
fontNames.setOnAction(eventHandler);
fontSizes.setOnAction(eventHandler);
GridPane grid = new GridPane();
grid.setVgap(5);
grid.add(new Label("Font name:"), 0, 0);
grid.add(fontNames, 1, 0);
grid.add(new Label("Font size:"), 0, 1);
grid.add(fontSizes, 1, 1);
Dialog dialog = new Dialog(grid);
dialog.setTitle("Select a font");
dialog.setAlwaysOnTop(true);
dialog.setResizable(false);
dialog.makeTransparentWhenLoseFocus();
dialog.show();
return dialog;
}
private void startSimpleMetaDataAnimation() {
float animationExtension = 3.25f;
bulgingTransition = new ScaleTransition(Duration.millis(1000), load_image_button);
bulgingTransition.setToX(animationExtension);
bulgingTransition.setToY(animationExtension);
bulgingTransition.autoReverseProperty().setValue(true);
bulgingTransition.setCycleCount(2);
bulgingTransition.play();
load_image_button.setFont(Font.font("Roboto", FontWeight.NORMAL, 8));
load_image_button.setText("Checking Metadata..");
}
public Status() {
super("Ready");
Font font = getFont();
double size = font.getSize();
setFont(Font.font("Arial", FontWeight.BOLD, FontPosture.ITALIC, size - 1));
setPrefHeight(size + 14);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(final ScanCommand command, final boolean empty)
{
super.updateItem(command, empty);
if (empty)
{
setText("");
setGraphic(null);
}
else
{
setText(command.toString());
setGraphic(ImageCache.getImageView(ScanCommandFactory.getImage(command.getCommandID())));
setTooltip(new Tooltip(command.getCommandName() + " @ " + command.getAddress()));
// Highlight the active command
// Cannot use 'background' because that's already used for 'selected' item
if (command.getAddress() == model.getActiveAddress())
{
setTextFill(Color.LAWNGREEN);
setFont(STANDOUT);
}
else
{
setTextFill(Color.BLACK);
setFont(Font.getDefault());
}
}
}
private TextArea getTextArea ()
{
TextArea textArea = new TextArea ();
textArea.setEditable (false);
textArea.setFont (Font.font ("Monospaced", 12));
textArea.setPrefWidth (TEXT_WIDTH);
return textArea;
}
@Override protected void resizeStaticText() {
double maxWidth = width - size * 0.1;
double fontSize = size * textSize.factor;
boolean customFontEnabled = tile.isCustomFontEnabled();
Font customFont = tile.getCustomFont();
Font font = (customFontEnabled && customFont != null) ? Font.font(customFont.getFamily(), fontSize) : Fonts.latoRegular(fontSize);
titleText.setFont(font);
if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
switch(tile.getTitleAlignment()) {
default :
case LEFT : titleText.relocate(size * 0.05, size * 0.05); break;
case CENTER: titleText.relocate((width - titleText.getLayoutBounds().getWidth()) * 0.5, size * 0.05); break;
case RIGHT : titleText.relocate(width - (size * 0.05) - titleText.getLayoutBounds().getWidth(), size * 0.05); break;
}
text.setFont(font);
if (text.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(text, maxWidth, fontSize); }
switch(tile.getTextAlignment()) {
default :
case LEFT : text.setX(size * 0.05); break;
case CENTER: text.setX((width - text.getLayoutBounds().getWidth()) * 0.5); break;
case RIGHT : text.setX(width - (size * 0.05) - text.getLayoutBounds().getWidth()); break;
}
text.setY(height - size * 0.05);
}
private void configureName(String string) {
Font font = new Font(9);
name.setText(string);
name.setBoundsType(TextBoundsType.VISUAL);
name.setLayoutX(-name.getBoundsInLocal().getWidth() / 2 + 4.8);
name.setLayoutY(radius * 1 / 2 + 4);
name.setFill(FILL_COLOR);
name.setFont(font);
}
private void readyGui(Stage primaryStage) {
this.primaryStage = primaryStage;
editorStage = new Stage();
tabbedHMDPostEditor = new TabbedHMDPostEditor(editorStage);
editorStage.setScene(new Scene(tabbedHMDPostEditor));
primaryStage.setTitle("Main Application");
editorStage.setTitle("Hugo Markdown Editor");
//Must do this for opening browser;
HostServicesProviderUtil.INSTANCE.init(getHostServices());
pane = new VBox();
File f = new File("kalpurush.ttf");
try {
Font.loadFont(f.getCanonicalPath(), 10);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
pane.getStylesheets().add(Paths.get("res/material.css").toAbsolutePath().toUri().toString());
pane.getStylesheets().add(Paths.get("res/custom.css").toAbsolutePath().toUri().toString());
//
primaryStage.setScene(new Scene(pane));
}
@Override protected void resizeStaticText() {
double maxWidth = width - size * 0.1;
double fontSize = size * textSize.factor;
boolean customFontEnabled = tile.isCustomFontEnabled();
Font customFont = tile.getCustomFont();
Font font = (customFontEnabled && customFont != null) ? Font.font(customFont.getFamily(), fontSize) : Fonts.latoRegular(fontSize);
titleText.setFont(font);
if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
switch(tile.getTitleAlignment()) {
default :
case LEFT : titleText.relocate(size * 0.05, size * 0.05); break;
case CENTER: titleText.relocate((width - titleText.getLayoutBounds().getWidth()) * 0.5, size * 0.05); break;
case RIGHT : titleText.relocate(width - (size * 0.05) - titleText.getLayoutBounds().getWidth(), size * 0.05); break;
}
text.setFont(font);
if (text.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(text, maxWidth, fontSize); }
switch(tile.getTextAlignment()) {
default :
case LEFT : text.setX(size * 0.05); break;
case CENTER: text.setX((width - text.getLayoutBounds().getWidth()) * 0.5); break;
case RIGHT : text.setX(width - (size * 0.05) - text.getLayoutBounds().getWidth()); break;
}
text.setY(height - size * 0.05);
}
/** @param font Font to use for markers */
public void setFont(final Font font)
{
hihi_label.setFont(font);
high_label.setFont(font);
low_label.setFont(font);
lolo_label.setFont(font);
update();
}
@Override
public void saveValueToXML(Element xmlElement) {
if (value == null)
return;
Font f = value.getFont();
StringBuilder s = new StringBuilder();
s.append(f.getName());
s.append(",");
s.append(f.getStyle());
s.append(",");
s.append(f.getSize());
Document parentDocument = xmlElement.getOwnerDocument();
Element newElement = parentDocument.createElement("font");
newElement.setTextContent(s.toString());
xmlElement.appendChild(newElement);
Color c = value.getColor();
s = new StringBuilder();
s.append(c.getRed());
s.append(",");
s.append(c.getGreen());
s.append(",");
s.append(c.getBlue());
s.append(",");
s.append(c.getOpacity());
newElement = parentDocument.createElement("color");
newElement.setTextContent(s.toString());
xmlElement.appendChild(newElement);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Tooltip Sample");
stage.setWidth(330);
stage.setHeight(150);
total.setFont(new Font("Arial", 20));
for (int i = 0; i < rooms.length; i++) {
final CheckBox cb = cbs[i] = new CheckBox(rooms[i]);
final Integer rate = rates[i];
final Tooltip tooltip = new Tooltip("$" + rates[i].toString());
tooltip.setFont(new Font("Arial", 16));
cb.setTooltip(tooltip);
cb.selectedProperty().addListener((ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
if (cb.isSelected()) {
sum = sum + rate;
} else {
sum = sum - rate;
}
total.setText("Total: $" + sum.toString());
});
}
VBox vbox = new VBox();
vbox.getChildren().addAll(cbs);
vbox.setSpacing(5);
HBox root = new HBox();
root.getChildren().add(vbox);
root.getChildren().add(total);
root.setSpacing(40);
root.setPadding(new Insets(20, 10, 10, 20));
((Group) scene.getRoot()).getChildren().add(root);
stage.setScene(scene);
stage.show();
}
private void addNullValueFiller(boolean add) {
masterPane.getChildren().clear();
if (add) {
Button btnInsert = new Button("{}");
btnInsert.setFont(Font.font("monospace", 14));
btnInsert.setOnAction(event -> {
addNullValueFiller(false);
valueObserver.updateValue(new SVArray());
});
masterPane.getChildren().add(btnInsert);
} else {
masterPane.getChildren().addAll(editorsPane, btnDecreaseSize, btnIncreaseSize);
}
}
public static final double adjustTextSize(final Text TEXT, final double MAX_WIDTH, final double FONT_SIZE) {
final String FONT_NAME = TEXT.getFont().getName();
double adjustableFontSize = FONT_SIZE;
while (TEXT.getLayoutBounds().getWidth() > MAX_WIDTH && adjustableFontSize > MIN_FONT_SIZE) {
adjustableFontSize -= 0.1;
TEXT.setFont(new Font(FONT_NAME, adjustableFontSize));
}
return adjustableFontSize;
}
public ProcessTab(Process process) {
this.process = process;
hbox = new HBox();
vbox = new VBox(log, hbox);
Button killButton = new Button("Kill");
killButton.setOnAction((e) -> {
process.destroyForcibly();
});
hbox.setAlignment(Pos.CENTER_RIGHT);
hbox.getChildren().add(killButton);
VBox.setVgrow(log, Priority.ALWAYS);
this.setContent(vbox);
log.setWrapText(true);
log.setFont(Font.font("Courier", 12));
reader = new Thread(() -> {
BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = stream.readLine()) != null) {
final String tmpLine = line;
Platform.runLater(() -> {
String old = log.getText();
old += tmpLine;
old += "\n";
log.setText(old);
log.setScrollTop(Double.MAX_VALUE);
});
}
} catch (IOException e) {
e.printStackTrace();
}
});
reader.start();
}
@Override protected void resizeStaticText() {
double maxWidth = width - size * 0.1;
double fontSize = size * textSize.factor;
boolean customFontEnabled = tile.isCustomFontEnabled();
Font customFont = tile.getCustomFont();
Font font = (customFontEnabled && customFont != null) ? Font.font(customFont.getFamily(), fontSize) : Fonts.latoRegular(fontSize);
titleText.setFont(font);
if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
switch(tile.getTitleAlignment()) {
default :
case LEFT : titleText.relocate(size * 0.05, size * 0.05); break;
case CENTER: titleText.relocate((width - titleText.getLayoutBounds().getWidth()) * 0.5, size * 0.05); break;
case RIGHT : titleText.relocate(width - (size * 0.05) - titleText.getLayoutBounds().getWidth(), size * 0.05); break;
}
maxWidth = width - (width - size * 0.275);
fontSize = upperUnitText.getText().isEmpty() ? size * 0.12 : size * 0.10;
upperUnitText.setFont(Fonts.latoRegular(fontSize));
if (upperUnitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(upperUnitText, maxWidth, fontSize); }
fontSize = upperUnitText.getText().isEmpty() ? size * 0.12 : size * 0.10;
unitText.setFont(Fonts.latoRegular(fontSize));
if (unitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(unitText, maxWidth, fontSize); }
averageText.setX(size * 0.05);
highText.setX(size * 0.05);
lowText.setX(size * 0.05);
}
@Override
public void start(Stage stage) {
VBox vbox = new VBox();
Scene scene = new Scene(vbox);
stage.setTitle("Hyperlink Sample");
stage.setWidth(570);
stage.setHeight(550);
selectedImage.setLayoutX(100);
selectedImage.setLayoutY(10);
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
for (int i = 0; i < captions.length; i++) {
final Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
final Image image = images[i] = new Image(getClass().getResourceAsStream(imageFiles[i]));
hpl.setGraphic(new ImageView(image));
hpl.setFont(Font.font("Arial", 14));
final String url = urls[i];
hpl.setOnAction((ActionEvent e) -> {
webEngine.load(url);
});
}
HBox hbox = new HBox();
hbox.setAlignment(Pos.BASELINE_CENTER);
hbox.getChildren().addAll(hpls);
vbox.getChildren().addAll(hbox, browser);
VBox.setVgrow(browser, Priority.ALWAYS);
stage.setScene(scene);
stage.show();
}
/** @param font Scale font */
public void setLegendFont(final Font font)
{
legend_font = font;
for (ModelListener listener : listeners)
listener.changedColorsOrFonts();
}
@Override
public java.awt.Dimension getBounds(String s)
{
Font currentFont = ctx.getFont();
Text t = new Text(s);
t.setFont(currentFont);
Bounds b = t.getLayoutBounds();
java.awt.Dimension bounds = new java.awt.Dimension((int)b.getWidth(), (int)b.getHeight());
return bounds;
}