jtextarea可以让某一行右对齐吗_如何计算文本在JTextArea中的行数(以及每行中的列数)?...

我做错了什么,我忘记了什么?

真的没什么。我修改了您的示例以在宽度上使用“<=”并突出显示一些功能: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());

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值