
1. Java에서 wordwrap을 사용하기 위해서는 `Text` 클래스를 사용해야 합니다. 하지만 `Text` 클래스는 deprecated 상태이므로 `Text` 대신 `TextLayout` 클래스를 사용하는 것을 권장합니다. `TextLayout` 클래스는 텍스트를 레이아웃하는 데 사용됩니다.
2. `TextLayout` 클래스를 사용하여 wordwrap을 할 때, 텍스트의 줄바꿈 위치를 지정할 수 있습니다. `TextLayout` 클래스의 `breakMask` 필드에 `BREAK_MASK_EVERYWHERE`를 설정하면 텍스트의 줄바꿈 위치를 지정할 수 있습니다.
3. 텍스트의 줄바꿈 위치를 지정하는 방법은 `TextLayout` 클래스의 `breakMask` 필드를 설정하는 것입니다. 예를 들어, 다음 코드는 텍스트의 줄바꿈 위치를 지정하는 방법을 보여줍니다.
#hostingforum.kr
java
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
public class WordWrapExample {
public static void main(String[] args) {
// 텍스트를 지정합니다.
String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
// 텍스트를 레이아웃합니다.
Font font = new Font("Arial", Font.PLAIN, 12);
FontMetrics fontMetrics = getFontMetrics(font);
int width = 400; // 레이아웃할 너비를 지정합니다.
int height = fontMetrics.getHeight() * 10; // 레이아웃할 높이를 지정합니다.
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setFont(font);
graphics.setColor(java.awt.Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 텍스트의 줄바꿈 위치를 지정합니다.
int x = 10;
int y = 10;
int breakMask = TextLayout.BREAK_MASK_EVERYWHERE;
TextLayout textLayout = new TextLayout(text, font, graphics.getFontRenderContext());
textLayout.breakMask = breakMask;
// 텍스트를 레이아웃합니다.
int charIndex = 0;
while (charIndex < text.length()) {
int breakIndex = textLayout.getBreakIndex(charIndex, width - x);
if (breakIndex == -1) {
breakIndex = text.length();
}
String line = text.substring(charIndex, breakIndex);
graphics.drawString(line, x, y + fontMetrics.getAscent());
charIndex = breakIndex;
y += fontMetrics.getHeight();
}
graphics.dispose();
// 이미지 파일로 저장합니다.
javax.imageio.ImageIO.write(image, "png", new java.io.File("wordwrap.png"));
}
private static FontMetrics getFontMetrics(Font font) {
Graphics2D graphics = new java.awt.Graphics2D(null);
graphics.setFont(font);
return graphics.getFontMetrics();
}
}
이 코드는 텍스트의 줄바꿈 위치를 지정하는 방법을 보여줍니다. `TextLayout` 클래스의 `breakMask` 필드를 설정하여 텍스트의 줄바꿈 위치를 지정할 수 있습니다.
2025-08-10 19:59