Domanda

i wanna load text from an external text or xml file in to a javafx container. i dont know which container i should use for this (textarea, with noneditable or label). problem, the file have more than one lines to read. For example: File.txt contains: "Hello

I'm the third row"

I actual use (for text-files) the normal BufferedReader-Code: Possible1:

String text;
while ((text = bufferedReader.readLine()) != null) {
   textlabel_about.setText(text);
}

or Possible2:

textlabel_about.setText(ReadTextfile(file){
StringBuilder stringBuffer = new StringBuilder();
String text;
while ((text = bufferedReader.readLine()) != null) {
      stringBuffer.append(text);
}
return stringBuffer.toString();
);

(Yes i cut the functions - of course i'm using exceptions and so on) But if i run the program i only can see: Possible1: "I'm the third row" Possible2: "HelloI'm the third row"

I only know the function while using the console with system.out.println to get the diffrent lines. So what can i do to show the text in the javafx container in the right formation?

È stato utile?

Soluzione

BufferedReader.readLine removes the line breaks. Just add the line breaks back in and use a TextArea:

StringBuilder stringBuilder = new StringBuilder();
String text;
while ((text = bufferedReader.readLine()) != null) {
    stringBuilder.append(text).append("\n");
}
// set the text in the TextArea
your_text_area.setText(stringBuilder.toString());

A TextArea breaks lines that are too wide, but adds a ScrollBar if the content gets too high for the container (does not resize vertically normaly).

Alternatively you can to use javafx.scene.text.Text. Text resizes to the content size by default.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top