Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

JavaFX에서 창 너비 내에서 텍스트를 래핑하는 방법은 무엇입니까?


JavaFX에서 텍스트 노드는 Javafx.scene.text.Text 수업. 다음을 수행해야 하는 JavaFx 창에 텍스트 삽입/표시

  • Text 클래스를 인스턴스화합니다.

  • setter 메서드를 사용하거나 생성자의 인수로 무시하여 위치 및 텍스트 문자열과 같은 기본 속성을 설정합니다.

  • 생성된 노드를 Group 개체에 추가합니다.

전달한 텍스트의 줄 길이가 창 너비보다 길면 텍스트의 일부가 아래와 같이 잘립니다. -

JavaFX에서 창 너비 내에서 텍스트를 래핑하는 방법은 무엇입니까?

솔루션으로 setWrappingWidth()를 사용하여 값을 속성 래핑으로 설정하여 창 너비 내에서 텍스트를 래핑할 수 있습니다. 방법.

이 메서드는 텍스트의 너비(픽셀)를 나타내는 double 값을 허용합니다. 창의 너비보다 작은 값을 전달하면 텍스트가 창 안에 줄바꿈됩니다(주어진 너비).

예시

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class WrappingTheText extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Reading the contents of a text file.
      InputStream inputStream = new FileInputStream("D:\\sample.txt");
      Scanner sc = new Scanner(inputStream);
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine()+"\n");
      }
      //Creating a text object
      Text text = new Text(10.0, 25.0, sb.toString());
      //Wrapping the text
      text.setWrappingWidth(590);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Wrapping The Text");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

샘플.txt

다음은 sample.txt 파일의 내용이라고 가정합니다. -

JavaFX is a Java library used to build Rich Internet Applications. The applications written 
using this library can run consistently across multiple platforms. The applications developed 
using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..
To develop GUI Applications using Java programming language, the programmers rely on libraries 
such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers 
can now develop GUI applications effectively with rich content.

출력

Font Name: Brush Script MT

출력

JavaFX에서 창 너비 내에서 텍스트를 래핑하는 방법은 무엇입니까?