The following code dynamically creates a TextFlow and Text that originally has new line characters in it (potentially images and other panes).
InputStream stream = new ByteArrayInputStream(text.toString().getBytes(StandardCharsets.UTF_8));
TextFlow element = new FXMLLoader().load(stream);
However, the ByteArrayInputStream method with FXML strips out all the new lines.
Tried using both Windows&Unix end of line characters, not that that should make a difference anyway, but you get to that point when you try different combinations in vain.
Usually it's recommended to use a BufferedReader to get the new lines back, but here I'm not in control. The other load methods seem to take URL's and resource links, however this is a manipulated string.
An example
The java code:
package simpleexample;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import com.jcabi.xml.XMLDocument;
public class TestFxmlWithBreaks extends Application {
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(createEntry(), 750, 750, Color.web("#666970"));
primaryStage.setScene(scene);
primaryStage.show();
}
private VBox createEntry() {
VBox entryBox = new VBox();
entryBox.setFillWidth(true);
entryBox.setSpacing(20);
entryBox.setMaxWidth(750);
try {
XMLDocument test = new XMLDocument(this.getClass().getResourceAsStream("inputFxml.xml"));
System.out.println(test.toString());
InputStream stream = new ByteArrayInputStream(test.toString().getBytes(StandardCharsets.UTF_8));
TextFlow element = new FXMLLoader().load(stream);
element.setMaxWidth(750);
entryBox.getChildren().add(element);
} catch (Exception e) {
//log something
}
return entryBox;
}
public static void main(String[] args) {
launch(args);
}
}
inputFxml.xml:
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.text.*?><TextFlow xmlns:fx="http://javafx.com/fxml" styleClass="paragraph">
<Text style="-fx-font-size: 20;">A list of stuff</Text>
<Text>
* stuff
* more stuff
* even more stuff, all with new lines
</Text>
<Text style="-fx-font-size: 15;">This should demonstrate it</Text>
</TextFlow>