下面列出了怎么用javafx.scene.text.Text的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
}
@Override
public void start(final Stage primaryStage) throws IOException {
log.info("Starting program");
final FxUtils fxUtils = new FxUtils();
Property.loadProperties();
Text lowerKey = fxUtils.createLowerKey();
midiModule = new MidiModule();
lowerKeyHandler = new LowerKeyHandler(lowerKey, midiModule);
thread = new Thread(lowerKeyHandler);
primaryStage.setTitle(PROGRAM_TITLE);
Scene scene = fxUtils.createScene(lowerKey);
scene.setOnKeyTyped(new SceneKeyTypedHandler(primaryStage));
primaryStage.setScene(scene);
fxUtils.startOnCorrectScreen(primaryStage);
primaryStage.setOnCloseRequest(getEventHandler());
primaryStage.setFullScreen(Property.START_IN_FULLSCREEN.isTrue());
primaryStage.show();
thread.start();
}
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || (long) item <= 0) {
setText(null);
setGraphic(null);
return;
}
text.setText(FileTools.showFileSize((long) item));
setGraphic(text);
}
};
return cell;
}
@Override // Override the start method on the Application class
public void start(Stage primaryStage) {
// Create a pane
Pane pane = new Pane();
// Create and register the handler
pane.setOnMouseClicked(e -> {
pane.getChildren().clear();
pane.getChildren().add(new Text(e.getX(), e.getY(),
"(" + e.getX() + ", " + e.getY() + ")"));
});
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 200, 200);
primaryStage.setTitle("Exercise_15_08a"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
/**
* Creates the SVG element corresponding to the labels of the grid.
*/
private void createSVGGridLabels(final SVGDocument document, final SVGElement elt, final String prefix, final double minX, final double maxX, final double
minY, final double maxY, final double tlx, final double tly, final double xStep, final double yStep, final double gridWidth, final double absStep) {
final Color gridLabelsColor = shape.getGridLabelsColour();
final SVGElement texts = new SVGGElement(document);
final double originX = shape.getOriginX();
final double originY = shape.getOriginY();
final double xorigin = xStep * originX;
final Text fooText = new Text(String.valueOf((int) maxX));
fooText.setFont(new Font(null, shape.getLabelsSize()));
final double labelHeight = fooText.getBaselineOffset();
final double labelWidth = fooText.getBoundsInLocal().getWidth();
final double yorigin = shape.isXLabelSouth() ? yStep * originY + labelHeight : yStep * originY - 2d;
texts.setAttribute(SVGAttributes.SVG_FONT_SIZE, String.valueOf(shape.getLabelsSize()));
texts.setAttribute(SVGAttributes.SVG_STROKE, CSSColors.INSTANCE.getColorName(gridLabelsColor, true));
texts.setAttribute(prefix + LNamespace.XML_TYPE, LNamespace.XML_TYPE_TEXT);
if(gridLabelsColor.getO() < 1d) {
texts.setAttribute(SVGAttributes.SVG_OPACITY, MathUtils.INST.format.format(gridLabelsColor.getO()));
}
produceSVGGridLabelsTexts(document, texts, gridWidth, xorigin, yorigin, fooText, minX, maxX, minY, maxY, tlx, tly, labelWidth, labelHeight, absStep);
elt.appendChild(texts);
}
private void createLetter(String c) {
final Text letter = new Text(c);
letter.setFill(Color.BLACK);
letter.setFont(FONT_DEFAULT);
letter.setTextOrigin(VPos.TOP);
letter.setTranslateX((getWidth() - letter.getBoundsInLocal().getWidth()) / 2);
letter.setTranslateY((getHeight() - letter.getBoundsInLocal().getHeight()) / 2);
getChildren().add(letter);
// over 3 seconds move letter to random position and fade it out
final Timeline timeline = new Timeline();
timeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(3), new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
// we are done remove us from scene
getChildren().remove(letter);
}
},
new KeyValue(letter.translateXProperty(), getRandom(0.0f, getWidth() - letter.getBoundsInLocal().getWidth()),INTERPOLATOR),
new KeyValue(letter.translateYProperty(), getRandom(0.0f, getHeight() - letter.getBoundsInLocal().getHeight()),INTERPOLATOR),
new KeyValue(letter.opacityProperty(), 0f)
));
timeline.play();
}
@Override protected void initGraphics() {
super.initGraphics();
titleText = new Text();
titleText.setFill(tile.getTitleColor());
Helper.enableNode(titleText, !tile.getTitle().isEmpty());
description = new Label(tile.getDescription());
description.setAlignment(tile.getDescriptionAlignment());
description.setTextAlignment(TextAlignment.RIGHT);
description.setWrapText(true);
description.setTextOverrun(OverrunStyle.WORD_ELLIPSIS);
description.setTextFill(tile.getTextColor());
description.setPrefSize(PREFERRED_WIDTH * 0.9, PREFERRED_HEIGHT * 0.795);
Helper.enableNode(description, tile.isTextVisible());
text = new Text(tile.getText());
text.setFill(tile.getUnitColor());
Helper.enableNode(text, tile.isTextVisible());
getPane().getChildren().addAll(titleText, text, description);
}
public Text3DHelper(String text, String font, int size){
this.text=text;
list=new ArrayList<>();
Text textNode = new Text(text);
textNode.setFont(new Font(font,size));
// Convert Text to Path
Path subtract = (Path)(Shape.subtract(textNode, new Rectangle(0, 0)));
// Convert Path elements into lists of points defining the perimeter (exterior or interior)
subtract.getElements().forEach(this::getPoints);
// Group exterior polygons with their interior polygons
polis.stream().filter(LineSegment::isHole).forEach(hole->{
polis.stream().filter(poly->!poly.isHole())
.filter(poly->!((Path)Shape.intersect(poly.getPath(), hole.getPath())).getElements().isEmpty())
.filter(poly->poly.getPath().contains(new Point2D(hole.getOrigen().x,hole.getOrigen().y)))
.forEach(poly->poly.addHole(hole));
});
polis.removeIf(LineSegment::isHole);
}
@Spawns("LevelInfo")
public Entity newLevelInfo(SpawnData data) {
Text levelText = getUIFactoryService().newText("Level " + geti("level"), Color.AQUAMARINE, 44);
Entity levelInfo = entityBuilder()
.view(levelText)
.with(new ExpireCleanComponent(Duration.seconds(LEVEL_START_DELAY)))
.build();
animationBuilder()
.interpolator(Interpolators.BOUNCE.EASE_OUT())
.duration(Duration.seconds(LEVEL_START_DELAY - 0.1))
.translate(levelInfo)
.from(new Point2D(getAppWidth() / 2 - levelText.getLayoutBounds().getWidth() / 2, 0))
.to(new Point2D(getAppWidth() / 2 - levelText.getLayoutBounds().getWidth() / 2, getAppHeight() / 2))
.buildAndPlay();
return levelInfo;
}
/**
* {@inheritDoc}
*/
@Override
public void initialise() {
final Region circle = new Region();
circle.getStyleClass().add("indicator-circle");
final Text text = new Text();
text.getStyleClass().add("indicator-information");
text.textProperty().bind(getControl().textProperty());
final StackPane container = new StackPane(circle, text);
container.getStyleClass().add("indicator-container");
final StackPane tabIndicator = new StackPane(container);
tabIndicator.getStyleClass().add("tab-indicator");
getChildren().add(tabIndicator);
}
private Node createRightContent() {
String title = "Please Subscribe :)";
HBox letters = new HBox(0);
letters.setAlignment(Pos.CENTER);
for (int i = 0; i < title.length(); i++) {
Text letter = new Text(title.charAt(i) + "");
letter.setFont(FONT);
letter.setFill(Color.WHITE);
letter.setOpacity(0);
letters.getChildren().add(letter);
FadeTransition ft = new FadeTransition(Duration.seconds(2), letter);
ft.setDelay(Duration.millis(i * 50));
ft.setToValue(1);
ft.setAutoReverse(true);
ft.setCycleCount(TranslateTransition.INDEFINITE);
ft.play();
}
return letters;
}
@Override protected void initGraphics() {
// Set initial size
if (Double.compare(clock.getPrefWidth(), 0.0) <= 0 || Double.compare(clock.getPrefHeight(), 0.0) <= 0 ||
Double.compare(clock.getWidth(), 0.0) <= 0 || Double.compare(clock.getHeight(), 0.0) <= 0) {
if (clock.getPrefWidth() > 0 && clock.getPrefHeight() > 0) {
clock.setPrefSize(clock.getPrefWidth(), clock.getPrefHeight());
} else {
clock.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
timeText = new Text();
timeText.setTextOrigin(VPos.CENTER);
timeText.setFill(textColor);
dateText = new Text();
dateText.setTextOrigin(VPos.CENTER);
dateText.setFill(dateColor);
pane = new Pane(timeText, dateText);
pane.setBorder(new Border(new BorderStroke(clock.getBorderPaint(), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(clock.getBorderWidth()))));
pane.setBackground(new Background(new BackgroundFill(clock.getBackgroundPaint(), CornerRadii.EMPTY, Insets.EMPTY)));
getChildren().setAll(pane);
}
public static void setDialouge(JFXButton applyButton , String heading , String text , Node ob) {
JFXButton button = applyButton;
content.setHeading(new Text(heading));
content.setBody(new Text(text));
JFXDialog dialoge = new JFXDialog(pane, content, JFXDialog.DialogTransition.CENTER);
button.addEventHandler(MouseEvent.MOUSE_CLICKED, (e6) -> {
dialoge.close();
});
content.setActions(ob, button);
// To show overlay dialougge box
dialoge.show();
}
/**
* Some Biomes come back as null. No idea. The Names match each other so it
* should work (Apparently it works like 1 in 10 times...)
*
* @return
*/
private List<String> comboBoxManager(GridPane pane, String inORex) {
List<String> checkedTexts = new ArrayList<String>();
int k = 0;
for(int i = 0; i < (pane.getChildren().size() / 3) + 1; i++) {
for(int j =0; j < 3; j++) {
//Adding an empty pane to the grid to fill in blanks check based on visiblity because its the only object going to be invisible
if(pane.getChildren().get(k).isVisible()){
VBox tempVbox = (VBox) pane.getChildren().get(k);
Text tempText = (Text) tempVbox.getChildren().get(0);
ComboBox tempCombo = (ComboBox) tempVbox.getChildren().get(1);
if (tempCombo.getValue() != null && tempCombo.getValue().equals(inORex)) {
checkedTexts.add(tempText.getText());
}
k++;
}
}
}
return checkedTexts;
}
private void addLine(String title, String value) {
rowCount++;
Text titleText = new Text(title);
titleText.setFill(_textColor);
titleText.setFont(regularFont);
Text valueText = new Text(value);
valueText.setFill(_textColor);
valueText.setFont(regularFont);
vBoxTitles.getChildren().add(titleText);
vBoxValues.getChildren().add(valueText);
Helper.enableNode(titleText, true);
Helper.enableNode(valueText, true);
}
@Override
public void updateItem(Pair<Integer, String> item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
setText(item.getValue());
int index = item.getKey();
Node g = new Text(String.valueOf(index + 1));
g.getStyleClass().addAll("bold", "error-cell");
setGraphic(g);
// on-click: go to line
if(index >= 0) {
setOnMouseClicked(me -> {
codeArea.moveTo(index, 0);
codeArea.requestFollowCaret();
codeArea.requestFocus();
});
} else {
setText(getText() + "\n(Cannot resolve line number from error)");
}
}
}
@Override protected void initGraphics() {
super.initGraphics();
chartItems = new ArrayList<>();
double sum = tile.getChartData().stream().mapToDouble(chartData -> chartData.getValue()).sum();
tile.getChartData().forEach(chartData -> chartItems.add(new ChartItem(chartData, sum)));
chartBox = new VBox(0);
chartBox.setFillWidth(true);
chartBox.getChildren().addAll(chartItems);
titleText = new Text();
titleText.setFill(tile.getTitleColor());
Helper.enableNode(titleText, !tile.getTitle().isEmpty());
text = new Text(tile.getText());
text.setFill(tile.getUnitColor());
Helper.enableNode(text, tile.isTextVisible());
getPane().getChildren().addAll(titleText, text, chartBox);
}
public static final void adjustTextSize(final Text TEXT, final double MAX_WIDTH, double fontSize) {
final String FONT_NAME = TEXT.getFont().getName();
while (TEXT.getLayoutBounds().getWidth() > MAX_WIDTH && fontSize > 0) {
fontSize -= 0.005;
TEXT.setFont(new Font(FONT_NAME, fontSize));
}
}
private List<TweetWord> recalcTweetLayout() {
TextFlow flow = new TextFlow();
flow.setMaxWidth(300);
pattern.splitAsStream(configuration.tweet.getDisplayEnhancedText())
.forEach(w -> {
Text textWord = wordNodeFactory.createTextNode(w.concat(" "));
fontSizeAdaption(textWord, configuration.tweetFontSize);
textWord.getStyleClass().setAll("tag");
flow.getChildren().add(textWord);
});
flow.requestLayout();
return flow.getChildren().stream().map(node -> new TweetWord(node.getBoundsInParent(), ((Text) node).getText())).collect(Collectors.toList());
}
private void initGraphics() {
// Set initial size
if (Double.compare(gauge.getPrefWidth(), 0.0) <= 0 || Double.compare(gauge.getPrefHeight(), 0.0) <= 0 ||
Double.compare(gauge.getWidth(), 0.0) <= 0 || Double.compare(gauge.getHeight(), 0.0) <= 0) {
if (gauge.getPrefWidth() > 0 && gauge.getPrefHeight() > 0) {
gauge.setPrefSize(gauge.getPrefWidth(), gauge.getPrefHeight());
} else {
gauge.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
batteryBackground = new Path();
batteryBackground.setFillRule(FillRule.EVEN_ODD);
batteryBackground.setStroke(null);
battery = new Path();
battery.setFillRule(FillRule.EVEN_ODD);
battery.setStroke(null);
valueText = new Text(String.format(locale, "%.0f%%", gauge.getCurrentValue()));
valueText.setVisible(gauge.isValueVisible());
valueText.setManaged(gauge.isValueVisible());
// Add all nodes
pane = new Pane();
pane.setBorder(new Border(new BorderStroke(gauge.getBorderPaint(), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(1))));
pane.setBackground(new Background(new BackgroundFill(gauge.getBackgroundPaint(), CornerRadii.EMPTY, Insets.EMPTY)));
pane.getChildren().setAll(batteryBackground, battery, valueText);
getChildren().setAll(pane);
}
SplitOptionsPane() {
super(Style.DEFAULT_SPACING);
getStyleClass().addAll(Style.CONTAINER.css());
I18nContext ctx = DefaultI18nContext.getInstance();
levelCombo.setId("bookmarksLevel");
regexpField.setId("bookmarksRegexp");
regexpField.setPromptText(ctx.i18n("Regular expression the bookmark has to match"));
regexpField.setPrefWidth(350);
getChildren().addAll(createLine(new Label(ctx.i18n("Split at this bookmark level:")), levelCombo),
createLine(new Label(ctx.i18n("Matching regular expression:")), regexpField, helpIcon(new TextFlow(
new Text(ctx.i18n("A regular expression the bookmark text has to match")
+ System.lineSeparator()),
new Text(ctx.i18n(
"Example: use .*Chapter.* to match bookmarks containing the word \"Chapter\""))))));
}
@Override
public boolean makeMoreParameters() {
if (!super.makeMoreParameters()) {
return false;
}
String fontFamily = waterFamilyBox.getSelectionModel().getSelectedItem();
String fontStyle = waterStyleBox.getSelectionModel().getSelectedItem();
Font FxFont;
if (AppVariables.message("Bold").equals(fontStyle)) {
font = new java.awt.Font(fontFamily, java.awt.Font.BOLD, waterSize);
FxFont = Font.font(fontFamily, FontWeight.BOLD, FontPosture.REGULAR, waterSize);
} else if (AppVariables.message("Italic").equals(fontStyle)) {
font = new java.awt.Font(fontFamily, java.awt.Font.ITALIC, waterSize);
FxFont = Font.font(fontFamily, FontWeight.NORMAL, FontPosture.ITALIC, waterSize);
} else if (AppVariables.message("Bold Italic").equals(fontStyle)) {
font = new java.awt.Font(fontFamily, java.awt.Font.BOLD + java.awt.Font.ITALIC, waterSize);
FxFont = Font.font(fontFamily, FontWeight.BOLD, FontPosture.ITALIC, waterSize);
} else {
font = new java.awt.Font(fontFamily, java.awt.Font.PLAIN, waterSize);
FxFont = Font.font(fontFamily, FontWeight.NORMAL, FontPosture.REGULAR, waterSize);
}
color = FxmlImageManufacture.toAwtColor((Color) colorRect.getFill());
final String msg = waterInput.getText().trim();
final Text text = new Text(msg);
text.setFont(FxFont);
textWidth = (int) Math.round(text.getLayoutBounds().getWidth());
textHeight = (int) Math.round(text.getLayoutBounds().getHeight());
return true;
}
public WordView(String word) {
letters = word.toUpperCase().toCharArray();
for (char c : letters) {
Text letter = new Text(c + "");
letter.setFont(Font.font(108));
getChildren().add(letter);
}
setAlignment(Pos.CENTER);
}
public GCObject() {
Text text = new Text();
text.setFill(Color.WHITE);
text.setFont(Font.font(32));
text.textProperty().bind(age.asString());
getChildren().addAll(bg, text);
}
private final void produceSVGGridYWestLabelsTexts(final SVGDocument document, final SVGElement texts, final double xorigin, final double tly,
final double gridWidth, final Text fooText, final double minY, final double maxY, final double labelHeight, final double absStep) {
final double width = gridWidth / 2d;
final int gridLabelsSize = shape.getLabelsSize();
for(double i = tly + (shape.isXLabelSouth() ? -width - gridLabelsSize / 4d : width + labelHeight), j = maxY; j >= minY; i += absStep, j--) {
final String label = String.valueOf((int) j);
final SVGElement text = new SVGTextElement(document);
fooText.setText(label);
text.setAttribute(SVGAttributes.SVG_X, String.valueOf((int) (xorigin - fooText.getLayoutBounds().getWidth() - gridLabelsSize / 4d - width)));
text.setAttribute(SVGAttributes.SVG_Y, String.valueOf((int) i));
text.setTextContent(label);
texts.appendChild(text);
}
}
public void start2(Stage primaryStage) {
Text txt = new Text("Fill the form and click Submit");
TextField tfFirstName = new TextField();
TextField tfLastName = new TextField();
TextField tfAge = new TextField();
Button btn = new Button("Submit");
btn.setOnAction(e -> action(tfFirstName, tfLastName, tfAge));
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(15);
grid.setVgap(5);
grid.setPadding(new Insets(20, 20, 20, 20));
int i = 0;
grid.add(txt, 0, i++, 2, 1);
GridPane.setHalignment(txt, HPos.CENTER);
grid.addRow(i++, new Label("First Name"),tfFirstName);
grid.addRow(i++, new Label("Last Name"), tfLastName);
grid.addRow(i++, new Label("Age"), tfAge);
grid.add(btn, 1, i);
GridPane.setHalignment(btn, HPos.CENTER);
//grid.setGridLinesVisible(true);
primaryStage.setTitle("Simple form example");
primaryStage.onCloseRequestProperty()
.setValue(e -> System.out.println("\nBye! See you later!"));
primaryStage.setScene(new Scene(grid, 300, 300));
primaryStage.show();
}
private Node getTextObj(TreeCell<?> cell) {
for (Node child : cell.getChildrenUnmodifiable()) {
if (child instanceof Text) {
return child;
}
}
return cell;
}
/**
* Creates an {@link Image} object visualizing a dragged repository location
*
* @param repositoryLocation The dragged repository location
* @return An {@link Image} object visualizing a dragged repository location
*/
private Image createPreviewImage(RepositoryLocation<? extends Repository> repositoryLocation) {
final Text text = new Text(repositoryLocation.toDisplayString());
// force the layout to be able to create a snapshot
new Scene(new Group(text));
final SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setFill(Color.TRANSPARENT);
return text.snapshot(snapshotParameters, null);
}
@Ignore
public void testMultipleZeroDecimal() {
ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("1.2000", 3);
Text beforeZeros = (Text) text.getChildren().get(0);
Text zeroDecimals = (Text) text.getChildren().get(1);
assertEquals("1.2", beforeZeros.getText());
assertEquals("000", zeroDecimals.getText());
}
/**
* highlights the matching text in the specified pane
* @param pane node to search into its text
* @param query search text
*/
public synchronized void highlight(Parent pane, String query) {
if (this.parent != null && !boxes.isEmpty()) {
clear();
}
if(query == null || query.isEmpty()) return;
this.parent = pane;
Set<Node> nodes = getTextNodes(pane);
ArrayList<Rectangle> allRectangles = new ArrayList<>();
for (Node node : nodes) {
Text text = ((Text) node);
final int beginIndex = text.getText().toLowerCase().indexOf(query.toLowerCase());
if (beginIndex > -1 && node.impl_isTreeVisible()) {
ArrayList<Bounds> boundingBoxes = getMatchingBounds(query, text);
ArrayList<Rectangle> rectangles = new ArrayList<>();
for (Bounds boundingBox : boundingBoxes) {
HighLightRectangle rect = new HighLightRectangle(text);
rect.setCacheHint(CacheHint.SPEED);
rect.setCache(true);
rect.setMouseTransparent(true);
rect.setBlendMode(BlendMode.MULTIPLY);
rect.fillProperty().bind(paintProperty());
rect.setManaged(false);
rect.setX(boundingBox.getMinX());
rect.setY(boundingBox.getMinY());
rect.setWidth(boundingBox.getWidth());
rect.setHeight(boundingBox.getHeight());
rectangles.add(rect);
allRectangles.add(rect);
}
boxes.put(node, rectangles);
}
}
JFXUtilities.runInFXAndWait(()-> getParentChildren(pane).addAll(allRectangles));
}