gpt4 book ai didi

java - 如果字符串太长,则将字符串拆分为 List

转载 作者:行者123 更新时间:2023-12-01 15:34:59 28 4
gpt4 key购买 nike

我有这个字符串:“这是我的很长的字符串,无法容纳在一行中”我需要将其分成多行,以便它适合我需要的地方。

假设每行只能容纳大约 15 个字母,那么它应该如下所示:

"This is my very" 
"long String"
"that wont fit"
"on one line"

我想把它分成 List<String>所以我可以做

for(String s : lines) draw(s,x,y);

任何有关如何执行此操作的帮助将不胜感激!

我渲染文本的方式是使用 Graphics.drawString()

这是我迄今为止尝试过的(我知道这很糟糕)

String diaText = "This is my very long String that wont fit on one line";
String[] txt = diaText.trim().split(" ");
int max = 23;
List<String> lines = new ArrayList<String>();
String s1 = "";
if (!(diaText.length() > max)) {
lines.add(diaText);
} else {
for (int i = 0; i < txt.length; i++) {
String ns = s1 += txt[i] + " ";
if (ns.length() < 23) {
lines.add(s1);
s1 = "";
} else {
s1 += txt[i] + "";
}
}
}
int yo = 0;
for (String s : lines) {
Font.draw(s, screen, 70, 15 + yo, Color.get(-1, 555, 555,555));
yo += 10;
}

最佳答案

Label rendered on image

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {

String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";

JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);

JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());

Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);

ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);

f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);

f.setVisible(true);
}
});
}
}

关于java - 如果字符串太长,则将字符串拆分为 List<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005804/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com