我做错了什么,我忘记了什么?
真的没什么。我修改了您的示例以在宽度上使用“<=”并突出显示一些功能:FontMetrics注意到,“a的推进String不一定是孤立测量的人物进步的总和......”
对于最宽的行,文本组件的首选大小与度量范围非常匹配。由于比例间距,这会因字体而异。
TextLayout 显示更严格的界限,但请注意“基线相对坐标”。
该getLineCount()方法计算line.separator分隔线,而不是包裹线。line:Twas brillig和狡猾的tovesline:gyre中的gyre和gimble;行数:2preferred:java.awt.Dimension [width = 207,height = 48]bounds1:java.awt.geom.Rectangle2D $ Float [x = 0.0,y = -12.568359,w = 205.0,h = 15.310547]layout1:java.awt.geom.Rectangle2D $ Float [x = 0.0,y = -10.0,w = 200.0,h = 13.0]bounds2:java.awt.geom.Rectangle2D $ Float [x = 0.0,y = -12.568359,w = 207.0,h = 15.310547]layout2:java.awt.geom.Rectangle2D $ Float [x = 1.0,y = -10.0,w = 205.0,h = 13.0]import java.awt.Dimension;import java.awt.FontMetrics;import java.awt.font.FontRenderContext;import java.awt.font.TextLayout;import java.util.ArrayList;import java.util.List;import javax.swing.JFrame;import javax.swing.JTextArea;import javax.swing.SwingUtilities;/** #see http://stackoverflow.com/questions/5979795 */public class TextAreaLine {
private static final String text1 =
"Twas brillig and the slithy toves\n";
private static final String text2 =
"Did gyre and gimble in the wabe;";
private static final JTextArea ta = new JTextArea(text1 + text2);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
static void display() {
JFrame f = new JFrame();
ta.setWrapStyleWord(false);
ta.setLineWrap(false);
ta.setRows(3);
f.add(ta);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
FontMetrics fm = ta.getFontMetrics(ta.getFont());
List texts = new ArrayList();
Dimension d = ta.getPreferredSize();
String text = ta.getText();
String line = "";
for (int i = 0; i
char c = text.charAt(i);
if (c != '\n') {
if (fm.stringWidth(line + c) <= d.width) {
line += c;
} else {
texts.add(line);
line = "" + c;
}
}
}
texts.add(line);
for (String s : texts) {
System.out.println("line: " + s);
}
System.out.println("line count: " + ta.getLineCount());
System.out.println("preferred: " + d);
System.out.println("bounds1: " + fm.getStringBounds(text1, null));
FontRenderContext frc = new FontRenderContext(null, false, false);
TextLayout layout = new TextLayout(text1, ta.getFont(), frc);
System.out.println("layout1: " + layout.getBounds());
System.out.println("bounds2: " + fm.getStringBounds(text2, null));
layout = new TextLayout(text2, ta.getFont(), frc);
System.out.println("layout2: " + layout.getBounds());
}}